diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index 60b431b27..1d150ff19 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/likely.hpp" #include "duckdb/function/function_set.hpp" #include "duckdb/planner/expression.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" namespace duckdb { @@ -500,6 +501,14 @@ static AggregateFunction NameXParameter(AggregateFunction fun) { return fun; } +unique_ptr AveragePropagateStats(ClientContext &context, BoundAggregateExpression &expr, + AggregateStatisticsInput &input) { + auto bounds = SumAccumulatorBounds::TryGet(input); + expr.FunctionMutable().SetErrorMode(bounds ? FunctionErrors::CANNOT_ERROR + : FunctionErrors::CAN_THROW_RUNTIME_ERROR); + return nullptr; +} + AggregateFunction GetAverageAggregate(PhysicalType type) { switch (type) { case PhysicalType::INT16: { @@ -522,6 +531,7 @@ AggregateFunction GetAverageAggregate(PhysicalType type) { AggregateFunction::UnaryAggregate, hugeint_t, double, HugeintAverageOperation>( LogicalType::HUGEINT, LogicalType::DOUBLE); function.SetFallible(); // adding HUGEINT values to the HUGEINT accumulator throws on overflow + function.SetStatisticsCallback(AveragePropagateStats); return NameXParameter(std::move(function)); } case PhysicalType::INTERVAL: { diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index 06c87c9f1..1d981f8d5 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -16,6 +16,54 @@ namespace duckdb { +optional SumAccumulatorBounds::TryGet(const AggregateStatisticsInput &input) { + if (!input.node_stats || !input.node_stats->has_max_cardinality) { + return {}; + } + auto &numeric_stats = input.child_stats[0]; + if (!NumericStats::HasMinMax(numeric_stats)) { + return {}; + } + hugeint_t min_value; + hugeint_t max_value; + switch (numeric_stats.GetType().InternalType()) { + case PhysicalType::BOOL: + min_value = NumericStats::Min(numeric_stats).GetValueUnsafe() ? 1 : 0; + max_value = NumericStats::Max(numeric_stats).GetValueUnsafe() ? 1 : 0; + break; + case PhysicalType::INT16: + min_value = NumericStats::Min(numeric_stats).GetValueUnsafe(); + max_value = NumericStats::Max(numeric_stats).GetValueUnsafe(); + break; + case PhysicalType::INT32: + min_value = NumericStats::Min(numeric_stats).GetValueUnsafe(); + max_value = NumericStats::Max(numeric_stats).GetValueUnsafe(); + break; + case PhysicalType::INT64: + min_value = NumericStats::Min(numeric_stats).GetValueUnsafe(); + max_value = NumericStats::Max(numeric_stats).GetValueUnsafe(); + break; + case PhysicalType::INT128: + min_value = NumericStats::Min(numeric_stats).GetValueUnsafe(); + max_value = NumericStats::Max(numeric_stats).GetValueUnsafe(); + break; + default: + return {}; + } + if (min_value > max_value) { + return {}; + } + const auto max_count = Hugeint::Convert(input.node_stats->max_cardinality); + SumAccumulatorBounds bounds; + if (!Hugeint::TryMultiply(min_value, max_count, bounds.min) || + !Hugeint::TryMultiply(max_value, max_count, bounds.max)) { + return {}; + } + bounds.min = MinValue(min_value, bounds.min); + bounds.max = MaxValue(max_value, bounds.max); + return bounds; +} + namespace { struct SumSetOperation { @@ -354,46 +402,19 @@ unique_ptr SumNoOverflowBind(BindAggregateFunctionInput &input) { unique_ptr SumPropagateStats(ClientContext &context, BoundAggregateExpression &expr, AggregateStatisticsInput &input) { - if (!input.node_stats || !input.node_stats->has_max_cardinality) { - return nullptr; - } auto &numeric_stats = input.child_stats[0]; - if (!NumericStats::HasMinMax(numeric_stats)) { - return nullptr; - } auto internal_type = numeric_stats.GetType().InternalType(); - hugeint_t max_negative = 0; - hugeint_t max_positive = 0; - switch (internal_type) { - case PhysicalType::BOOL: - max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe() ? 1 : 0; - max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe() ? 1 : 0; - break; - case PhysicalType::INT16: - max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe(); - max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe(); - break; - case PhysicalType::INT32: - max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe(); - max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe(); - break; - case PhysicalType::INT64: - max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe(); - max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe(); - break; - case PhysicalType::INT128: - max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe(); - max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe(); - break; - default: - throw InternalException("Unsupported type for propagate sum stats"); + auto bounds = SumAccumulatorBounds::TryGet(input); + if (internal_type == PhysicalType::INT128) { + bool cannot_overflow = bounds.has_value(); + if (cannot_overflow && expr.GetReturnType().id() == LogicalTypeId::DECIMAL) { + const auto decimal_limit = Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_DECIMAL]; + cannot_overflow = bounds->min > -decimal_limit && bounds->max < decimal_limit; + } + expr.FunctionMutable().SetErrorMode(cannot_overflow ? FunctionErrors::CANNOT_ERROR + : FunctionErrors::CAN_THROW_RUNTIME_ERROR); } - - const auto max_card = Hugeint::Convert(input.node_stats->max_cardinality); - hugeint_t wide_negative = 0; - hugeint_t wide_positive = 0; - if (!Hugeint::TryMultiply(max_negative, max_card, wide_negative) || - !Hugeint::TryMultiply(max_positive, max_card, wide_positive)) { + if (!bounds) { return nullptr; } @@ -401,17 +422,15 @@ unique_ptr SumPropagateStats(ClientContext &context, BoundAggreg // swap in. const bool has_no_overflow_variant = internal_type == PhysicalType::INT32 || internal_type == PhysicalType::INT64; const bool sum_fits_in_int64 = - wide_negative > NumericLimits::Minimum() && wide_positive < NumericLimits::Maximum(); + bounds->min > NumericLimits::Minimum() && bounds->max < NumericLimits::Maximum(); if (has_no_overflow_variant && sum_fits_in_int64) { expr.FunctionMutable().ReplaceImplementation(GetSumAggregateNoOverflow(internal_type)); } // Propagate stats. - auto sum_min = max_negative <= 0 ? wide_negative : max_negative; - auto sum_max = max_positive >= 0 ? wide_positive : max_positive; auto result = NumericStats::CreateEmpty(expr.GetReturnType()).ToUnique(); - NumericStats::SetMin(*result, Value::HUGEINT(sum_min)); - NumericStats::SetMax(*result, Value::HUGEINT(sum_max)); + NumericStats::SetMin(*result, Value::HUGEINT(bounds->min)); + NumericStats::SetMax(*result, Value::HUGEINT(bounds->max)); result->Set(StatsInfo::CAN_HAVE_NULL_AND_VALID_VALUES); return result; } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp index c0822e354..1a92a758d 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp @@ -114,6 +114,10 @@ struct ModeStandard { return new MAP_TYPE(); } + static ModeAttr &GetOrCreate(MAP_TYPE &map, const T &key, ArenaAllocator &) { + return map[key]; + } + template static RESULT_TYPE Assign(Vector &result, INPUT_TYPE input) { return RESULT_TYPE(input); @@ -136,13 +140,17 @@ struct ModeStandard { struct ModeString { using MAP_TYPE = OwningStringMap; - static MAP_TYPE *CreateEmpty(ArenaAllocator &allocator) { - return new MAP_TYPE(allocator); + static MAP_TYPE *CreateEmpty(ArenaAllocator &) { + return new MAP_TYPE(); } static MAP_TYPE *CreateEmpty(Allocator &allocator) { return new MAP_TYPE(allocator); } + static ModeAttr &GetOrCreate(MAP_TYPE &map, const string_t &key, ArenaAllocator &allocator) { + return map.GetOrCreate(key, allocator); + } + template static RESULT_TYPE Assign(Vector &result, INPUT_TYPE input) { return StringVector::AddStringOrBlob(result, input); @@ -376,7 +384,7 @@ struct BaseModeFunction { if (!state.frequency_map) { state.frequency_map = TYPE_OP::CreateEmpty(input_data.allocator); } - auto &i = (*state.frequency_map)[key]; + auto &i = TYPE_OP::GetOrCreate(*state.frequency_map, key, input_data.allocator); ++i.count; i.first_row = MinValue(i.first_row, state.count); ++state.count; @@ -396,7 +404,7 @@ struct BaseModeFunction { target.frequency_map = TYPE_OP::CreateEmpty(aggr_input_data.allocator); } for (auto &val : *source.frequency_map) { - auto &i = (*target.frequency_map)[val.first]; + auto &i = TYPE_OP::GetOrCreate(*target.frequency_map, val.first, aggr_input_data.allocator); i.count += val.second.count; i.first_row = MinValue(i.first_row, val.second.first_row); } @@ -420,7 +428,7 @@ struct TypedModeFunction : BaseModeFunction { if (!state.frequency_map) { state.frequency_map = TYPE_OP::CreateEmpty(aggr_input.input.allocator); } - auto &i = (*state.frequency_map)[key]; + auto &i = TYPE_OP::GetOrCreate(*state.frequency_map, key, aggr_input.input.allocator); i.count += count; i.first_row = MinValue(i.first_row, state.count); state.count += count; @@ -667,9 +675,9 @@ static FrequencyAggregateFinalizeResult FinalizeEntropyRewrite(FrequencyAggregat auto log_total = BindScalar(context, "log2", total_ref->Copy()); auto normalized = BindScalar(context, "/", std::move(weighted_ref), std::move(total_ref)); auto entropy = BindScalar(context, "-", std::move(log_total), std::move(normalized)); - auto coalesce = make_uniq(ExpressionType::OPERATOR_COALESCE, LogicalType::DOUBLE); - coalesce->GetChildrenMutable().push_back(std::move(entropy)); - coalesce->GetChildrenMutable().push_back(make_uniq(Value::DOUBLE(0))); + auto coalesce = + make_uniq(ExpressionType::OPERATOR_COALESCE, LogicalType::DOUBLE, std::move(entropy), + make_uniq(Value::DOUBLE(0))); result.result = std::move(coalesce); return result; } diff --git a/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp index 889170860..c0abf5a74 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp @@ -63,7 +63,7 @@ struct HistogramFunction { target.hist = MAP_TYPE::CreateEmpty(input_data.allocator); } for (auto &entry : *source.hist) { - (*target.hist)[entry.first] += entry.second; + MAP_TYPE::GetOrCreate(*target.hist, entry.first, input_data.allocator) += entry.second; } } }; @@ -75,14 +75,23 @@ struct DefaultMapType { static TYPE *CreateEmpty(ArenaAllocator &) { return new TYPE(); } + + template + static typename TYPE::mapped_type &GetOrCreate(TYPE &map, const KEY &key, ArenaAllocator &) { + return map[key]; + } }; template struct StringMapType { using MAP_TYPE = TYPE; - static TYPE *CreateEmpty(ArenaAllocator &allocator) { - return new TYPE(allocator); + static TYPE *CreateEmpty(ArenaAllocator &) { + return new TYPE(); + } + + static typename TYPE::mapped_type &GetOrCreate(TYPE &map, const string_t &key, ArenaAllocator &allocator) { + return map.GetOrCreate(key, allocator); } }; @@ -109,7 +118,7 @@ void HistogramUpdateFunction(Vector inputs[], AggregateInputData &aggr_input, id state.hist = MAP_TYPE::CreateEmpty(aggr_input.allocator); } auto &input_value = input_values[idx]; - ++(*state.hist)[input_value]; + ++MAP_TYPE::GetOrCreate(*state.hist, input_value, aggr_input.allocator); } } diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp index 59cc898d3..086fe7afb 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp @@ -13,6 +13,7 @@ #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" #include "duckdb/common/types/value.hpp" +#include "duckdb/common/optional.hpp" #include "duckdb/function/aggregate_state.hpp" #include "duckdb/function/aggregate_state_layout.hpp" #include "duckdb/common/operator/cast_operators.hpp" @@ -22,6 +23,15 @@ namespace duckdb { +struct AggregateStatisticsInput; + +struct SumAccumulatorBounds { + hugeint_t min; + hugeint_t max; + + static optional TryGet(const AggregateStatisticsInput &input); +}; + struct RepeatedStateValue { template static T Multiply(const T &input, idx_t count) { @@ -171,14 +181,9 @@ struct AddToHugeint { result.lower += value; // now handle overflows int overflow = result.lower < value; - // we consider two situations: - // (1) input[idx] is positive, and current value is lower than value: overflow - // (2) input[idx] is negative, and current value is higher than value: underflow - if (!(overflow ^ positive)) { - // in the case of an overflow or underflow we either increment or decrement the upper base - // positive: +1, negative: -1 - result.upper += -1 + 2 * positive; - } + D_ASSERT(positive == 0 || positive == 1); + // Add the unsigned carry and the sign extension of the input. + result.upper += overflow + positive - 1; } template diff --git a/src/duckdb/extension/core_functions/lambda_functions.cpp b/src/duckdb/extension/core_functions/lambda_functions.cpp index 335c10f96..af2d4c606 100644 --- a/src/duckdb/extension/core_functions/lambda_functions.cpp +++ b/src/duckdb/extension/core_functions/lambda_functions.cpp @@ -1,6 +1,7 @@ #include "duckdb/function/lambda_functions.hpp" #include "duckdb/common/exception/binder_exception.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" @@ -20,8 +21,8 @@ namespace duckdb { //! LambdaExecuteInfo holds information for executing the lambda expression on an input chunk and //! a resulting lambda chunk. struct LambdaExecuteInfo { - LambdaExecuteInfo(ClientContext &context, const Expression &lambda_expr, const DataChunk &args, - const bool has_index, const Vector &child_vector) + LambdaExecuteInfo(Context &context, const Expression &lambda_expr, const DataChunk &args, const bool has_index, + const Vector &child_vector) : has_index(has_index) { expr_executor = make_uniq(context, lambda_expr); diff --git a/src/duckdb/extension/core_functions/scalar/date/age.cpp b/src/duckdb/extension/core_functions/scalar/date/age.cpp index 21cce7804..332f44ac2 100644 --- a/src/duckdb/extension/core_functions/scalar/date/age.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/age.cpp @@ -15,7 +15,7 @@ static void AgeFunctionStandard(DataChunk &input, ExpressionState &state, Vector // plain TZ when ICU is not loaded, we implement this in UTC (like everything else) // To get the PG behaviour, we overload these functions in ICU for TSTZ arguments. auto current_date = Timestamp::FromDatetime( - Timestamp::GetDate(MetaTransaction::Get(state.GetContext()).start_timestamp), dtime_t(0)); + Timestamp::GetDate(MetaTransaction::Get(state.GetClientContext()).start_timestamp), dtime_t(0)); UnaryExecutor::Execute(input.data[0], result, [&](timestamp_t input) -> optional { diff --git a/src/duckdb/extension/core_functions/scalar/date/current.cpp b/src/duckdb/extension/core_functions/scalar/date/current.cpp index 5a529212d..44b412a46 100644 --- a/src/duckdb/extension/core_functions/scalar/date/current.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/current.cpp @@ -6,7 +6,7 @@ namespace duckdb { static timestamp_t GetTransactionTimestamp(ExpressionState &state) { - return MetaTransaction::Get(state.GetContext()).start_timestamp; + return MetaTransaction::Get(state.GetClientContext()).start_timestamp; } static void CurrentTimestampFunction(DataChunk &input, ExpressionState &state, Vector &result) { 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 76cfb2b1f..01329407a 100644 --- a/src/duckdb/extension/core_functions/scalar/date/date_part.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/date_part.cpp @@ -152,7 +152,7 @@ struct DatePart { return OP::template TryOperation(input, result); } template - static bool TryDatePartOperation(T input, TR &result, long) { + static bool TryDatePartOperation(T input, TR &result, int64_t) { result = OP::template Operation(input); return true; } @@ -2150,19 +2150,19 @@ void DatePartFunction(DataChunk &args, ExpressionState &state, Vector &result) { const auto &spec_arg = args.data[0]; const auto &date_arg = args.data[1]; - BinaryExecutor::Execute( - spec_arg, date_arg, result, [&](string_t specifier, T date) -> optional { - if (date.IsFinite()) { - const auto part_code = GetDatePartSpecifier(specifier.GetString()); - if (IsBigintDatepart(part_code)) { - return ExtractElement(part_code, date); - } else { - return ExtractDoubleElement(part_code, date); - } - } else { - return nullopt; - } - }); + BinaryExecutor::Execute(spec_arg, date_arg, result, + [&](string_t specifier, T date) -> optional { + if (date.IsFinite()) { + const auto part_code = GetDatePartSpecifier(specifier); + if (IsBigintDatepart(part_code)) { + return ExtractElement(part_code, date); + } else { + return ExtractDoubleElement(part_code, date); + } + } else { + return nullopt; + } + }); } template diff --git a/src/duckdb/extension/core_functions/scalar/debug/sleep.cpp b/src/duckdb/extension/core_functions/scalar/debug/sleep.cpp index f037a4eda..539c7e7b5 100644 --- a/src/duckdb/extension/core_functions/scalar/debug/sleep.cpp +++ b/src/duckdb/extension/core_functions/scalar/debug/sleep.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "core_functions/scalar/debug_functions.hpp" #include "duckdb/common/vector_operations/generic_executor.hpp" diff --git a/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp b/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp index 096a2ce5d..efa5070bb 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp @@ -16,19 +16,19 @@ namespace { // current_query void CurrentQueryFunction(DataChunk &input, ExpressionState &state, Vector &result) { - Value val(state.GetContext().GetCurrentQuery()); + Value val(state.GetClientContext().GetCurrentQuery()); result.Reference(val, count_t(input.size())); } // current_schema void CurrentSchemaFunction(DataChunk &input, ExpressionState &state, Vector &result) { - Value val(ClientData::Get(state.GetContext()).catalog_search_path->GetDefault().GetSchema()); + Value val(ClientData::Get(state.GetClientContext()).catalog_search_path->GetDefault().GetSchema()); result.Reference(val, count_t(input.size())); } // current_database void CurrentDatabaseFunction(DataChunk &input, ExpressionState &state, Vector &result) { - Value val(DatabaseManager::GetDefaultDatabase(state.GetContext())); + Value val(DatabaseManager::GetDefaultDatabase(state.GetClientContext())); result.Reference(val, count_t(input.size())); } @@ -82,7 +82,7 @@ void CurrentSchemasFunction(DataChunk &input, ExpressionState &state, Vector &re // in_search_path void InSearchPathFunction(DataChunk &input, ExpressionState &state, Vector &result) { - auto &context = state.GetContext(); + auto &context = state.GetClientContext(); auto &search_path = ClientData::Get(context).catalog_search_path; BinaryExecutor::Execute( input.data[0], input.data[1], result, [&](string_t db_name, string_t schema_name) { @@ -93,7 +93,7 @@ void InSearchPathFunction(DataChunk &input, ExpressionState &state, Vector &resu // txid_current void TransactionIdCurrent(DataChunk &input, ExpressionState &state, Vector &result) { - auto &transaction = MetaTransaction::Get(state.GetContext()); + auto &transaction = MetaTransaction::Get(state.GetClientContext()); auto val = Value::UBIGINT(transaction.global_transaction_id); result.Reference(val, count_t(input.size())); } 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 6749581f0..1e6127b03 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "core_functions/aggregate/nested_functions.hpp" #include "core_functions/scalar/list_functions.hpp" #include "duckdb/catalog/catalog.hpp" @@ -84,7 +85,7 @@ ListAggregatesBindData::~ListAggregatesBindData() { } struct ListAggregatesLocalState : public FunctionLocalState { - ListAggregatesLocalState(ClientContext &context, optional_ptr bind_data) + ListAggregatesLocalState(Context &context, optional_ptr bind_data) : arena_allocator(BufferAllocator::Get(context)) { if (!bind_data) { return; 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 148f67f7e..5b3f0ed3f 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp @@ -2,6 +2,7 @@ #include "duckdb/function/lambda_functions.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_lambda_expression.hpp" @@ -10,7 +11,7 @@ namespace duckdb { namespace { struct ReduceExecuteInfo { - ReduceExecuteInfo(LambdaFunctions::LambdaInfo &info, ClientContext &context) + ReduceExecuteInfo(LambdaFunctions::LambdaInfo &info, Context &context) : context(context), left_slice(make_uniq(Vector::Ref(*info.child_vector))) { if (info.has_initial) { initial_value_offset = 0; @@ -62,7 +63,7 @@ struct ReduceExecuteInfo { }; ValidityMask active_rows; - ClientContext &context; + Context &context; unique_ptr left_slice; unique_ptr accumulator_cast; unique_ptr expr_executor; diff --git a/src/duckdb/extension/core_functions/scalar/list/list_value.cpp b/src/duckdb/extension/core_functions/scalar/list/list_value.cpp index 4fb2e9a7c..20de34161 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_value.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_value.cpp @@ -39,13 +39,13 @@ void TemplatedPopulateChild(DataChunk &args, Vector &result) { } } -void PopulateChildFallback(DataChunk &args, Vector &result) { +void PopulateChildFallback(DataChunk &args, ExpressionState &state, Vector &result) { auto &child_type = ListType::GetChildType(result.GetType()); auto result_data = FlatVector::Writer(result, args.size()); for (idx_t i = 0; i < args.size(); i++) { const auto entry_offset = ListVector::GetListSize(result); for (idx_t col_idx = 0; col_idx < args.ColumnCount(); col_idx++) { - auto val = args.GetValue(col_idx, i).DefaultCastAs(child_type); + auto val = args.GetValue(col_idx, i).CastAs(state.GetContext(), child_type); ListVector::PushBack(result, val); } result_data.WriteValue(list_entry_t(entry_offset, args.ColumnCount())); @@ -226,7 +226,7 @@ void ListValueFunction(DataChunk &args, ExpressionState &state, Vector &result) auto &result_child = ListVector::GetChildMutable(result); if (!PopulateChild(args, result_child)) { - PopulateChildFallback(args, result); + PopulateChildFallback(args, state, result); } const idx_t column_count = args.ColumnCount(); diff --git a/src/duckdb/extension/core_functions/scalar/random/random.cpp b/src/duckdb/extension/core_functions/scalar/random/random.cpp index 4c2f1e52f..cc7065a2a 100644 --- a/src/duckdb/extension/core_functions/scalar/random/random.cpp +++ b/src/duckdb/extension/core_functions/scalar/random/random.cpp @@ -77,7 +77,7 @@ void RandomFunction(DataChunk &args, ExpressionState &state, Vector &result) { unique_ptr RandomInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data) { - auto &random_engine = RandomEngine::Get(state.GetContext()); + 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 3b3c84693..265af59fd 100644 --- a/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp @@ -1,6 +1,6 @@ #include "core_functions/scalar/string_functions.hpp" #include "core_functions/scalar/string_characters.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/map.hpp" #include "duckdb/common/vector.hpp" @@ -10,8 +10,8 @@ namespace duckdb { // Can't calculate as trivial modification to levenshtein algorithm // as we need to potentially know about earlier in the string template -static idx_t DamerauLevenshteinDistance(optional_ptr context, const T *source_str, idx_t source_len, - const T *target_str, idx_t target_len) { +static idx_t DamerauLevenshteinDistance(Context &context, const T *source_str, idx_t source_len, const T *target_str, + idx_t target_len) { // costs associated with each type of edit, to aid readability constexpr uint8_t COST_SUBSTITUTION = 1; constexpr uint8_t COST_INSERTION = 1; @@ -47,9 +47,7 @@ static idx_t DamerauLevenshteinDistance(optional_ptr context, con } // loop through string indices - these are offset by 2 from distance indices for (idx_t source_idx = 0; source_idx < source_len; source_idx++) { - if (context) { - context->InterruptCheck(); - } + context.InterruptCheck(); // 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; @@ -86,8 +84,7 @@ static idx_t DamerauLevenshteinDistance(optional_ptr context, con } //! The distance between the characters of the strings - not their bytes -static idx_t DamerauLevenshteinDistance(optional_ptr context, const string_t &source, - const string_t &target) { +static idx_t DamerauLevenshteinDistance(Context &context, const string_t &source, const string_t &target) { if (StringIsAscii(source) && StringIsAscii(target)) { return DamerauLevenshteinDistance(context, source.GetData(), source.GetSize(), target.GetData(), target.GetSize()); @@ -98,8 +95,7 @@ static idx_t DamerauLevenshteinDistance(optional_ptr context, con target_chars.size()); } -static int64_t DamerauLevenshteinScalarFunction(optional_ptr context, const string_t source, - const string_t target) { +static int64_t DamerauLevenshteinScalarFunction(Context &context, const string_t source, const string_t target) { return (int64_t)DamerauLevenshteinDistance(context, source, target); } @@ -107,8 +103,7 @@ static void DamerauLevenshteinFunction(DataChunk &args, ExpressionState &state, const auto &source_vec = args.data[0]; const auto &target_vec = args.data[1]; - // the client context only serves interrupt checks, and index keys are computed without one - optional_ptr context = state.HasContext() ? &state.GetContext() : nullptr; + auto &context = state.GetContext(); BinaryExecutor::Execute( source_vec, target_vec, result, [&](string_t source, string_t target) { return DamerauLevenshteinScalarFunction(context, source, target); }); diff --git a/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp b/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp index dca9e2575..dab42aebf 100644 --- a/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp @@ -1,6 +1,6 @@ #include "core_functions/scalar/string_functions.hpp" #include "core_functions/scalar/string_characters.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/string_util.hpp" @@ -15,8 +15,7 @@ namespace duckdb { // (too muach memory usage) template -static idx_t LevenshteinDistance(optional_ptr context, const T *txt_str, idx_t txt_len, const T *tgt_str, - idx_t tgt_len) { +static idx_t LevenshteinDistance(Context &context, const T *txt_str, idx_t txt_len, const T *tgt_str, idx_t tgt_len) { // If one string is empty, the distance equals the length of the other string if (txt_len == 0) { return tgt_len; @@ -39,9 +38,7 @@ static idx_t LevenshteinDistance(optional_ptr context, const T *t } for (idx_t pos_txt = 0; pos_txt < txt_len; pos_txt++) { - if (context) { - context->InterruptCheck(); - } + context.InterruptCheck(); // calculate distances1 (current raw distances) from the previous row distances1[0] = pos_txt + 1; @@ -66,7 +63,7 @@ static idx_t LevenshteinDistance(optional_ptr context, const T *t } //! The distance between the characters of the strings - not their bytes -static idx_t LevenshteinDistance(optional_ptr context, const string_t &txt, const string_t &tgt) { +static idx_t LevenshteinDistance(Context &context, const string_t &txt, const string_t &tgt) { if (StringIsAscii(txt) && StringIsAscii(tgt)) { return LevenshteinDistance(context, txt.GetData(), txt.GetSize(), tgt.GetData(), tgt.GetSize()); } @@ -75,7 +72,7 @@ static idx_t LevenshteinDistance(optional_ptr context, const stri return LevenshteinDistance(context, txt_chars.data(), txt_chars.size(), tgt_chars.data(), tgt_chars.size()); } -static int64_t LevenshteinScalarFunction(optional_ptr context, const string_t str, string_t tgt) { +static int64_t LevenshteinScalarFunction(Context &context, const string_t str, string_t tgt) { return (int64_t)LevenshteinDistance(context, str, tgt); } @@ -83,8 +80,7 @@ static void LevenshteinFunction(DataChunk &args, ExpressionState &state, Vector const auto &str_vec = args.data[0]; const auto &tgt_vec = args.data[1]; - // the client context only serves interrupt checks, and index keys are computed without one - optional_ptr context = state.HasContext() ? &state.GetContext() : nullptr; + auto &context = state.GetContext(); BinaryExecutor::Execute(str_vec, tgt_vec, result, [&](string_t str, string_t tgt) { return LevenshteinScalarFunction(context, str, tgt); }); diff --git a/src/duckdb/extension/core_functions/scalar/struct/struct_insert.cpp b/src/duckdb/extension/core_functions/scalar/struct/struct_insert.cpp index 9f51a1071..98111e58b 100644 --- a/src/duckdb/extension/core_functions/scalar/struct/struct_insert.cpp +++ b/src/duckdb/extension/core_functions/scalar/struct/struct_insert.cpp @@ -33,11 +33,6 @@ static void StructInsertFunction(DataChunk &args, ExpressionState &state, Vector static unique_ptr StructInsertBind(BindScalarFunctionInput &input) { auto &bound_function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - for (auto &argument : arguments) { - if (argument->GetReturnType().id() == LogicalTypeId::UNKNOWN) { - throw ParameterNotResolvedException(); - } - } if (LogicalTypeId::STRUCT != arguments[0]->GetReturnType().id()) { throw InvalidInputException("The first argument to struct_insert must be a STRUCT"); } 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 e8642bb69..c8b8ec467 100644 --- a/src/duckdb/extension/core_functions/scalar/struct/struct_update.cpp +++ b/src/duckdb/extension/core_functions/scalar/struct/struct_update.cpp @@ -8,6 +8,7 @@ #include "duckdb/common/case_insensitive_map.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" #include "duckdb/planner/expression_binder.hpp" +#include "duckdb/common/serializer/deserializer.hpp" namespace duckdb { @@ -39,8 +40,33 @@ struct StructUpdateBindData : public FunctionData { static unique_ptr Deserialize(Deserializer &deserializer, BoundScalarFunction &bound_function) { auto stype = deserializer.ReadProperty(100, "variable_return_type"); auto field_indexes = deserializer.ReadPropertyWithDefault>(101, "field_indexes"); + if (field_indexes.empty()) { + // Binding always records a field for every updated argument, so the mapping is only missing from plans + // that were serialized before it existed + field_indexes = FieldIndexesFromAliases(stype, deserializer.Get()); + } return make_uniq(std::move(stype), std::move(field_indexes)); } + + //! Plans serialized before v2.0 only name the field every argument updates through the alias of that argument + static vector FieldIndexesFromAliases(const LogicalType &stype, const const_expression_list_t &children) { + identifier_tree_t result_fields; + auto &result_children = StructType::GetChildTypes(stype); + for (idx_t field_idx = 0; field_idx < result_children.size(); field_idx++) { + result_fields.emplace(result_children[field_idx].first, field_idx); + } + vector field_indexes; + for (idx_t arg_idx = 1; arg_idx < children.size(); arg_idx++) { + auto &alias = children[arg_idx].get().GetAlias(); + auto entry = result_fields.find(alias); + if (entry == result_fields.end()) { + throw SerializationException("struct_update argument \"%s\" does not name a field of the result", + alias.GetIdentifierName()); + } + field_indexes.push_back(entry->second); + } + return field_indexes; + } }; //! For every result field, the argument that provides it - fields without one keep the value of the source struct diff --git a/src/duckdb/extension/icu/collation/collation_collator.cpp b/src/duckdb/extension/icu/collation/collation_collator.cpp index d52e5e530..08173a1ef 100644 --- a/src/duckdb/extension/icu/collation/collation_collator.cpp +++ b/src/duckdb/extension/icu/collation/collation_collator.cpp @@ -2,6 +2,7 @@ #include "collation_data.hpp" #include "collation_normalizer.hpp" +#include "duckdb/common/algorithm.hpp" #include "duckdb/common/string_util.hpp" namespace duckdb { @@ -464,7 +465,8 @@ static void WriteSortKey(const vector &elements, const Coll const auto alternate_shifted = settings.alternate_shifted; const auto backward_secondary = settings.backward_secondary; const auto primary_strength = settings.strength == CollationStrength::PRIMARY; - uint32_t variable_top = alternate_shifted ? variable_top_primary + 1 : 0; + uint32_t variable_top = + alternate_shifted ? variable_top_primaries[static_cast(settings.max_variable)] + 1 : 0; SortKeyLevel secondaries(buffer.levels[0]); SortKeyLevel cases(buffer.levels[1]); @@ -808,11 +810,10 @@ static const CollationInfo *FindCollation(const string &collation) { return nullptr; } -Collator::Collator(const string &collation) { - auto info = FindCollation(StringUtil::Lower(collation)); +//! The settings of a collation, or of the root collation for nullptr +static CollationSettings GetCollationSettings(const CollationInfo *info) { + CollationSettings settings; if (info) { - // the tables of the collation are decompressed here, the sort keys only read them - tailoring = &GetCollationTailoring(info->unit); settings.strength = static_cast(info->strength); settings.case_level = info->case_level; settings.case_first = static_cast(info->case_first); @@ -820,9 +821,132 @@ Collator::Collator(const string &collation) { settings.backward_secondary = info->backward_secondary; settings.normalization = info->normalization; } + return settings; +} + +Collator::Collator(const CollationInfo *info, CollationSettings settings_p) : settings(settings_p) { + if (info) { + // the tables of the collation are decompressed here, the sort keys only read them + tailoring = &GetCollationTailoring(info->unit); + } BuildFastPath(); } +Collator::Collator(const string &collation) : Collator(FindCollation(StringUtil::Lower(collation))) { +} + +Collator::Collator(const CollationInfo *info) : Collator(info, GetCollationSettings(info)) { +} + +//! Looks the value of a collation keyword up among its options, a keyword without a value is true +template +static T GetKeywordValue(const string &tag, const string &key, const string &value, + std::initializer_list> options) { + auto name = value.empty() ? string("true") : value; + for (auto &option : options) { + if (name == option.first) { + return option.second; + } + } + throw InvalidInputException("Invalid value \"%s\" for the collation keyword \"%s\" in \"%s\"", value, key, tag); +} + +static bool GetBooleanKeyword(const string &tag, const string &key, const string &value) { + return GetKeywordValue(tag, key, value, {{"true", true}, {"false", false}}); +} + +//! Applies a collation keyword of the "-u-" extension of a language tag, as Unicode Technical Standard #35 defines it +static void ApplyCollationKeyword(const string &tag, const string &key, const string &value, + CollationSettings &settings) { + if (key == "ka") { + settings.alternate_shifted = GetKeywordValue(tag, key, value, {{"shifted", true}, {"noignore", false}}); + } else if (key == "ks") { + settings.strength = GetKeywordValue(tag, key, value, + {{"level1", CollationStrength::PRIMARY}, + {"level2", CollationStrength::SECONDARY}, + {"level3", CollationStrength::TERTIARY}, + {"level4", CollationStrength::QUATERNARY}, + {"identic", CollationStrength::IDENTICAL}}); + } else if (key == "kf") { + settings.case_first = GetKeywordValue( + tag, key, value, + {{"upper", CaseFirst::UPPER_FIRST}, {"lower", CaseFirst::LOWER_FIRST}, {"false", CaseFirst::DEFAULT}}); + } else if (key == "kv") { + settings.max_variable = GetKeywordValue(tag, key, value, + {{"space", MaxVariable::SPACE}, + {"punct", MaxVariable::PUNCTUATION}, + {"symbol", MaxVariable::SYMBOL}, + {"currency", MaxVariable::CURRENCY}}); + } else if (key == "kc") { + settings.case_level = GetBooleanKeyword(tag, key, value); + } else if (key == "kb") { + settings.backward_secondary = GetBooleanKeyword(tag, key, value); + } else if (key == "kk") { + settings.normalization = GetBooleanKeyword(tag, key, value); + } else if ((key == "co" && value != "standard") || key == "kn" || key == "kr" || key == "kh" || key == "vt") { + throw NotImplementedException("The collation keyword \"%s\" in \"%s\" is not supported", key, tag); + } + // the other keywords, such as the calendar or the numbering system, do not change the collation +} + +Collator Collator::FromLanguageTag(const string &tag) { + // subtags are case insensitive, and "_" separates them as well, as in "en_US" + auto subtags = StringUtil::Split(StringUtil::Replace(StringUtil::Lower(tag), "_", "-"), '-'); + for (auto &subtag : subtags) { + bool valid = !subtag.empty() && subtag.size() <= 8; + for (auto c : subtag) { + valid = valid && StringUtil::CharacterIsAlphaNumeric(c); + } + if (!valid) { + throw InvalidInputException("Invalid collation \"%s\"", tag); + } + } + // the language, script, region and variants come before the first single character subtag + idx_t locale_end = 0; + while (locale_end < subtags.size() && subtags[locale_end].size() > 1) { + locale_end++; + } + // a locale without a collation of its own uses the one of its language, as "sv_se" uses "sv" + const CollationInfo *info = nullptr; + for (idx_t count = locale_end; count > 0 && !info; count--) { + info = FindCollation(StringUtil::Join(subtags, count, "_", [](const string &subtag) { return subtag; })); + } + auto settings = GetCollationSettings(info); + // the "u" extension holds attributes, then keywords: a two character key followed by the subtags of its value + idx_t pos = locale_end; + while (pos < subtags.size()) { + auto singleton = subtags[pos++]; + if (singleton == "x") { + // the rest of the tag is for private use + break; + } + auto end = pos; + while (end < subtags.size() && subtags[end].size() > 1) { + end++; + } + if (singleton == "u") { + while (pos < end && subtags[pos].size() != 2) { + pos++; + } + // when a key is repeated, its first value counts + vector keys; + while (pos < end) { + auto key = subtags[pos++]; + string value; + while (pos < end && subtags[pos].size() != 2) { + value += (value.empty() ? "" : "-") + subtags[pos++]; + } + if (std::find(keys.begin(), keys.end(), key) == keys.end()) { + keys.push_back(key); + ApplyCollationKeyword(tag, key, value, settings); + } + } + } + pos = end; + } + return Collator(info, settings); +} + void Collator::BuildFastPath() { auto &root = GetCollationRoot(); if (tailoring) { diff --git a/src/duckdb/extension/icu/collation/generated/collation_data.cpp b/src/duckdb/extension/icu/collation/generated/collation_data.cpp index 7af3c1fd6..46d7c8ce0 100644 --- a/src/duckdb/extension/icu/collation/generated/collation_data.cpp +++ b/src/duckdb/extension/icu/collation/generated/collation_data.cpp @@ -31742,7 +31742,7 @@ const CollationInfo collation_infos[] = { }; const uint32_t collation_count = 140; -const uint32_t variable_top_primary = 0x0BFFFFFF; +const uint32_t variable_top_primaries[] = {0x0505FFFF, 0x0BFFFFFF, 0x0DA2FFFF, 0x0EFFFFFF}; } // namespace collation } // namespace duckdb diff --git a/src/duckdb/extension/icu/collation/include/collation_collator.hpp b/src/duckdb/extension/icu/collation/include/collation_collator.hpp index 53ed16bc2..eaf24be48 100644 --- a/src/duckdb/extension/icu/collation/include/collation_collator.hpp +++ b/src/duckdb/extension/icu/collation/include/collation_collator.hpp @@ -21,6 +21,9 @@ enum class CollationStrength : uint8_t { PRIMARY = 0, SECONDARY = 1, TERTIARY = enum class CaseFirst : uint8_t { DEFAULT = 0, LOWER_FIRST = 1, UPPER_FIRST = 2 }; +//! The last group of characters that are variable, each group includes the ones before it +enum class MaxVariable : uint8_t { SPACE = 0, PUNCTUATION = 1, SYMBOL = 2, CURRENCY = 3 }; + struct CollationSettings { CollationStrength strength = CollationStrength::TERTIARY; //! Whether to add a separate case level after the secondary level @@ -28,12 +31,15 @@ struct CollationSettings { CaseFirst case_first = CaseFirst::DEFAULT; //! Whether variable (punctuation, symbol, ...) weights are shifted to the quaternary level bool alternate_shifted = false; + //! Which characters are variable when alternate_shifted is set + MaxVariable max_variable = MaxVariable::PUNCTUATION; //! Whether secondary weights are compared backwards, as in Canadian French bool backward_secondary = false; //! Whether text that is not in canonical order is normalized before it is collated bool normalization = false; }; +struct CollationInfo; struct CollationTailoring; //! An index of the code points a locale tailors: a bitmap that rejects the characters it @@ -91,6 +97,8 @@ class Collator { //! Creates a collator for a collation name such as "de" or "fr_ca", falling back to the //! root collation when the locale is unknown explicit Collator(const string &collation); + //! Creates a collator for a BCP 47 language tag such as "sv-SE" or "en-u-ka-shifted" + static Collator FromLanguageTag(const string &tag); //! Whether a collation with this name exists static bool HasCollation(const string &collation); @@ -106,6 +114,10 @@ class Collator { } private: + //! Creates a collator for a collation (nullptr for the root collation) with its own settings + explicit Collator(const CollationInfo *info); + //! Creates a collator for a collation (nullptr for the root collation) with the given settings + Collator(const CollationInfo *info, CollationSettings settings_p); //! Fills the table of ASCII characters that map to a single collation element void BuildFastPath(); //! Writes the sort key of a string of simple characters, returns false when the string diff --git a/src/duckdb/extension/icu/collation/include/collation_data.hpp b/src/duckdb/extension/icu/collation/include/collation_data.hpp index 4ea70945d..edd580607 100644 --- a/src/duckdb/extension/icu/collation/include/collation_data.hpp +++ b/src/duckdb/extension/icu/collation/include/collation_data.hpp @@ -142,7 +142,8 @@ extern const CollationUnit collation_units[]; extern const uint32_t collation_unit_count; extern const CollationInfo collation_infos[]; extern const uint32_t collation_count; -extern const uint32_t variable_top_primary; +//! The last variable primary for each MaxVariable group +extern const uint32_t variable_top_primaries[]; //! The units that hold the tables every collation uses static constexpr uint32_t COLLATION_ROOT_UNIT = 0; diff --git a/src/duckdb/extension/icu/icu-current.cpp b/src/duckdb/extension/icu/icu-current.cpp index c9f295bee..f784c7a87 100644 --- a/src/duckdb/extension/icu/icu-current.cpp +++ b/src/duckdb/extension/icu/icu-current.cpp @@ -4,13 +4,14 @@ #include "duckdb/common/types/time.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/transaction/meta_transaction.hpp" +#include "duckdb/main/context.hpp" #include "include/icu-current.hpp" #include "include/icu-casts.hpp" namespace duckdb { static timestamp_t GetTransactionTimestamp(ExpressionState &state) { - return MetaTransaction::Get(state.GetContext()).start_timestamp; + return MetaTransaction::Get(state.GetClientContext()).start_timestamp; } static void CurrentTimeFunction(DataChunk &input, ExpressionState &state, Vector &result) { diff --git a/src/duckdb/extension/icu/icu-datefunc.cpp b/src/duckdb/extension/icu/icu-datefunc.cpp index c2c0ebb5e..06f30eeac 100644 --- a/src/duckdb/extension/icu/icu-datefunc.cpp +++ b/src/duckdb/extension/icu/icu-datefunc.cpp @@ -1,6 +1,7 @@ #include "include/icu-datefunc.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" #include "duckdb/common/types/timestamp.hpp" @@ -18,7 +19,10 @@ ICUDateFunc::BindData::BindData(const string &tz_setting_p, const string &cal_se InitCalendar(); } -ICUDateFunc::BindData::BindData(ClientContext &context) : cal_setting("gregorian") { +ICUDateFunc::BindData::BindData(ClientContext &context) : BindData(context.GetContext()) { +} + +ICUDateFunc::BindData::BindData(Context &context) : cal_setting("gregorian") { context.TryGetCurrentSetting("TimeZone", tz_setting); context.TryGetCurrentSetting("Calendar", cal_setting); diff --git a/src/duckdb/extension/icu/icu-datetrunc.cpp b/src/duckdb/extension/icu/icu-datetrunc.cpp index d4a18bffc..84f1dd2e8 100644 --- a/src/duckdb/extension/icu/icu-datetrunc.cpp +++ b/src/duckdb/extension/icu/icu-datetrunc.cpp @@ -242,7 +242,7 @@ ICUDateFunc::part_trunc_t ICUDateFunc::TruncationFactory(DatePartSpecifier type) } timestamp_tz_t ICUDateFunc::CurrentMidnight(Calendar *calendar, ExpressionState &state) { - const timestamp_tz_t current_timestamp(MetaTransaction::Get(state.GetContext()).start_timestamp); + const timestamp_tz_t current_timestamp(MetaTransaction::Get(state.GetClientContext()).start_timestamp); auto current_micros = SetTime(calendar, current_timestamp); ICUDateTrunc::TruncDay(calendar, current_micros); return GetTime(calendar); diff --git a/src/duckdb/extension/icu/icu-makedate.cpp b/src/duckdb/extension/icu/icu-makedate.cpp index 8b792a7a0..fcac01a6f 100644 --- a/src/duckdb/extension/icu/icu-makedate.cpp +++ b/src/duckdb/extension/icu/icu-makedate.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/vector_operations/variadic_executor.hpp" #include "duckdb/main/extension/extension_loader.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "include/icu-casts.hpp" #include "include/icu-datefunc.hpp" @@ -36,7 +37,7 @@ date_t ICUMakeDate::Operation(Calendar *calendar, timestamp_tz_t instant) { return result; } -date_t ICUMakeDate::ToDate(ClientContext &context, timestamp_tz_t instant) { +date_t ICUMakeDate::ToDate(Context &context, timestamp_tz_t instant) { ICUDateFunc::BindData data(context); return Operation(data.calendar.get(), instant); } diff --git a/src/duckdb/extension/icu/icu-timezone.cpp b/src/duckdb/extension/icu/icu-timezone.cpp index 64dd09167..7d3c714e3 100644 --- a/src/duckdb/extension/icu/icu-timezone.cpp +++ b/src/duckdb/extension/icu/icu-timezone.cpp @@ -206,6 +206,16 @@ struct ICUFromNaiveTimestamp : public ICUDateFunc { return timestamp_tz_ns_t(result); } + static inline timestamp_tz_t Operation(Calendar *calendar, date_t naive) { + if (DUCKDB_UNLIKELY(naive == date_t::infinity())) { + return timestamp_tz_t::infinity(); + } + if (DUCKDB_UNLIKELY(naive == date_t::ninfinity())) { + return timestamp_tz_t::ninfinity(); + } + return Operation(calendar, Timestamp::FromDatetime(naive, dtime_t(0))); + } + template static bool CastFromNaive(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { auto &cast_data = parameters.cast_data->Cast(); @@ -735,6 +745,11 @@ struct ICUTimeZoneFunc : public ICUDateFunc { .AddParameter("timestamp", LogicalType::TIMESTAMP_TZ_NS); set.AddFunction(timetzns_fun); + ScalarFunction date_fun({}, LogicalType::TIMESTAMP_TZ, Execute, + Bind); + date_fun.GetSignature().AddParameter("timezone", LogicalType::VARCHAR).AddParameter("date", LogicalType::DATE); + set.AddFunction(date_fun); + set.ApplyToFunctions([](ScalarFunction &func) { func.SetFallible(); func.SetStability(FunctionStability::CONSISTENT_WITHIN_QUERY); diff --git a/src/duckdb/extension/icu/icu_extension.cpp b/src/duckdb/extension/icu/icu_extension.cpp index 985929511..3fb65567a 100644 --- a/src/duckdb/extension/icu/icu_extension.cpp +++ b/src/duckdb/extension/icu/icu_extension.cpp @@ -29,18 +29,6 @@ namespace duckdb { -//! The collation settings of the tagged collations that are registered by the extension -static collation::CollationSettings SettingsFromTag(const string &tag) { - collation::CollationSettings settings; - // "und-u-ks-level1-kc-true": compare at the primary level, but keep case differences - if (tag == "und-u-ks-level1-kc-true") { - settings.strength = collation::CollationStrength::PRIMARY; - settings.case_level = true; - return settings; - } - throw InvalidInputException("Unknown collation tag %s", tag); -} - struct IcuBindData : public FunctionData { collation::Collator collator; string language; @@ -52,7 +40,8 @@ struct IcuBindData : public FunctionData { country(std::move(country_p)) { } - explicit IcuBindData(string tag_p) : collator(SettingsFromTag(tag_p)), tag(std::move(tag_p)) { + //! A BCP 47 language tag such as "und-u-ks-level1-kc-true" + explicit IcuBindData(string tag_p) : collator(collation::Collator::FromLanguageTag(tag_p)), tag(std::move(tag_p)) { } static duckdb::unique_ptr CreateInstance(const string &language, const string &country, @@ -197,14 +186,12 @@ static duckdb::unique_ptr ICUSortKeyBind(BindScalarFunctionInput & if (!bound_function.GetExtraInfo().empty()) { return make_uniq(bound_function.GetExtraInfo()); } - auto splits = StringUtil::Split(StringValue::Get(val), "_"); - if (splits.size() == 1) { - return make_uniq(splits[0], ""); - } else if (splits.size() == 2) { - return make_uniq(splits[0], splits[1]); - } else { + // the collator is a language and a country such as "de_DE", or a language tag such as "en-u-ka-shifted" + auto &collator = StringValue::Get(val); + if (StringUtil::Split(collator, "_").size() > 2) { throw InvalidInputException("Expected one or two splits"); } + return make_uniq(collator); } //! The function a collation pushes into a query, it writes the sort key as a blob diff --git a/src/duckdb/extension/icu/include/icu-casts.hpp b/src/duckdb/extension/icu/include/icu-casts.hpp index 97f00f4cd..08607caf2 100644 --- a/src/duckdb/extension/icu/include/icu-casts.hpp +++ b/src/duckdb/extension/icu/include/icu-casts.hpp @@ -25,7 +25,7 @@ struct ICUMakeDate : public ICUDateFunc { static void AddCasts(ExtensionLoader &loader); - static date_t ToDate(ClientContext &context, timestamp_tz_t instant); + static date_t ToDate(Context &context, timestamp_tz_t instant); }; struct ICUToTimeTZ : public ICUDateFunc { diff --git a/src/duckdb/extension/icu/include/icu-datefunc.hpp b/src/duckdb/extension/icu/include/icu-datefunc.hpp index 0ee8876ae..77b511c4a 100644 --- a/src/duckdb/extension/icu/include/icu-datefunc.hpp +++ b/src/duckdb/extension/icu/include/icu-datefunc.hpp @@ -19,6 +19,7 @@ namespace duckdb { struct ICUDateFunc { struct BindData : public FunctionData { + explicit BindData(Context &context); explicit BindData(ClientContext &context); BindData(const string &tz_setting, const string &cal_setting); BindData(const BindData &other); diff --git a/src/duckdb/extension/json/include/json_functions.hpp b/src/duckdb/extension/json/include/json_functions.hpp index 3816a8639..400794052 100644 --- a/src/duckdb/extension/json/include/json_functions.hpp +++ b/src/duckdb/extension/json/include/json_functions.hpp @@ -18,6 +18,7 @@ namespace duckdb { class TableRef; class Expression; class ClientContext; +class Context; struct ReplacementScanData; class CastFunctionSet; struct CastParameters; @@ -65,7 +66,7 @@ struct JSONReadManyFunctionData : public FunctionData { struct JSONFunctionLocalState : public FunctionLocalState { public: explicit JSONFunctionLocalState(Allocator &allocator); - explicit JSONFunctionLocalState(ClientContext &context); + explicit JSONFunctionLocalState(Context &context); static unique_ptr Init(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data); static unique_ptr InitCastLocalState(CastLocalStateParameters ¶meters); diff --git a/src/duckdb/extension/json/json_functions.cpp b/src/duckdb/extension/json/json_functions.cpp index 9fe7fd5cb..f2d8d1b62 100644 --- a/src/duckdb/extension/json/json_functions.cpp +++ b/src/duckdb/extension/json/json_functions.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/common/vector/string_vector.hpp" @@ -142,7 +143,7 @@ JSONFunctionLocalState::JSONFunctionLocalState(Allocator &allocator) : json_allocator(make_shared_ptr(allocator)) { } -JSONFunctionLocalState::JSONFunctionLocalState(ClientContext &context) +JSONFunctionLocalState::JSONFunctionLocalState(Context &context) : JSONFunctionLocalState(BufferAllocator::Get(context)) { } @@ -152,7 +153,7 @@ unique_ptr JSONFunctionLocalState::Init(ExpressionState &sta } unique_ptr JSONFunctionLocalState::InitCastLocalState(CastLocalStateParameters ¶meters) { - return parameters.context ? make_uniq(*parameters.context) + return parameters.context ? make_uniq(parameters.context->GetContext()) : make_uniq(Allocator::DefaultAllocator()); } diff --git a/src/duckdb/extension/json/json_functions/json_create.cpp b/src/duckdb/extension/json/json_functions/json_create.cpp index 31349e4fc..5fd18508c 100644 --- a/src/duckdb/extension/json/json_functions/json_create.cpp +++ b/src/duckdb/extension/json/json_functions/json_create.cpp @@ -18,6 +18,7 @@ #include "duckdb/common/serializer/serializer.hpp" #include "json_common.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "json_functions.hpp" #include "json_geojson.hpp" @@ -82,7 +83,7 @@ struct JSONCopyFormatOptions { JSONGeometryFormat geometry_format = JSONGeometryFormat::WKT; mutable optional_ptr date_format; mutable optional_ptr timestamp_format; - mutable optional_ptr context; + mutable optional_ptr context; optional_ptr timestamptz_format_expression; optional_ptr timestamptz_ns_format_expression; }; @@ -108,7 +109,7 @@ void JSONFunctions::ValidateGeometryFormat(ClientContext &, SetScope, Value &par //! GEOMETRY is written as WKT unless the json_geometry_format setting says otherwise. COPY ... TO ... //! (FORMAT GEOJSON) writes GeoJSON regardless, by overriding this afterwards. -static JSONGeometryFormat ClientGeometryFormat(ClientContext &context) { +static JSONGeometryFormat ClientGeometryFormat(Context &context) { Value value; if (!context.TryGetCurrentSetting("json_geometry_format", value)) { return JSONGeometryFormat::WKT; @@ -116,7 +117,7 @@ static JSONGeometryFormat ClientGeometryFormat(ClientContext &context) { return ParseGeometryFormat(value); } -static JSONCopyFormatOptions ClientFormatOptions(ClientContext &context) { +static JSONCopyFormatOptions ClientFormatOptions(Context &context) { JSONCopyFormatOptions result; result.context = context; result.geometry_format = ClientGeometryFormat(context); @@ -154,7 +155,7 @@ struct JSONCopyToJSONFunctionData : public FunctionData { const_struct_names.Equals(other.const_struct_names); } - JSONCopyFormatOptions GetFormatOptions(ClientContext &context) { + JSONCopyFormatOptions GetFormatOptions(Context &context) { JSONCopyFormatOptions result; result.geometry_format = ClientGeometryFormat(context); result.date_format = has_date_format ? optional_ptr(&date_format) : nullptr; @@ -1571,17 +1572,17 @@ ScalarFunctionSet JSONFunctions::GetRowToJSONFunction() { struct NestedToJSONCastData : public BoundCastData { public: - explicit NestedToJSONCastData(optional_ptr client) : client(client) { + explicit NestedToJSONCastData(Context &context_p) : context(context_p) { } unique_ptr Copy() const override { - auto result = make_uniq(client); + auto result = make_uniq(context); result->const_struct_names = const_struct_names.Copy(); return std::move(result); } public: - optional_ptr client; + Context &context; StructNames const_struct_names; }; @@ -1593,16 +1594,14 @@ static bool AnyToJSONCast(Vector &source, Vector &result, idx_t count, CastParam const auto &names = cast_data.const_struct_names; JSONCopyFormatOptions options; - options.context = cast_data.client; - if (cast_data.client) { - options.geometry_format = ClientGeometryFormat(*cast_data.client); - } + options.context = cast_data.context; + options.geometry_format = ClientGeometryFormat(cast_data.context); ToJSONFunctionInternal(names, source, count, result, alc, options); return true; } static BoundCastInfo AnyToJSONCastBind(BindCastInput &input, const LogicalType &source, const LogicalType &target) { - auto cast_data = make_uniq(input.context); + auto cast_data = make_uniq(input.GetContext()); GetJSONType(cast_data->const_struct_names, source); return BoundCastInfo(AnyToJSONCast, std::move(cast_data), JSONFunctionLocalState::InitCastLocalState); } @@ -1630,6 +1629,8 @@ void JSONFunctions::RegisterJSONCreateCastFunctions(ExtensionLoader &loader) { case LogicalTypeId::ARRAY: source_type = LogicalType::ARRAY(LogicalType::ANY, optional_idx()); break; + case LogicalTypeId::VARIANT: + continue; case LogicalTypeId::VARCHAR: // We skip this one here as it's handled in json_functions.cpp continue; diff --git a/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp b/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp index 00fdba96c..a9d9f250d 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp @@ -113,10 +113,10 @@ static void JsonSerializePlanFunction(DataChunk &args, ExpressionState &state, V auto &func_expr = state.expr.Cast(); const auto &info = func_expr.BindInfo()->Cast(); - if (!state.HasContext()) { + if (!state.HasClientContext()) { throw InvalidInputException("json_serialize_plan: No client context available"); } - auto &context = state.GetContext(); + auto &context = state.GetClientContext(); auto &heap = StringVector::GetStringHeap(result); UnaryExecutor::Execute(inputs, result, [&](string_t input) { @@ -125,7 +125,7 @@ static void JsonSerializePlanFunction(DataChunk &args, ExpressionState &state, V yyjson_mut_doc_set_root(doc, result_obj); try { - Parser parser(state.GetContext()); + Parser parser(state.GetClientContext()); parser.ParseQuery(input.GetString()); auto plans_arr = yyjson_mut_arr(doc); 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 e4b270295..22e372c6b 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/main/connection.hpp" @@ -94,7 +95,7 @@ static void JsonSerializeFunction(DataChunk &args, ExpressionState &state, Vecto yyjson_mut_doc_set_root(doc, result_obj); try { - Parser parser(state.GetContext()); + Parser parser(state.GetClientContext()); parser.ParseQuery(input.GetString()); auto statements_arr = yyjson_mut_arr(doc); @@ -106,7 +107,7 @@ static void JsonSerializeFunction(DataChunk &args, ExpressionState &state, Vecto auto &select = statement->Cast(); auto options = make_uniq(); - options->storage_compatibility = state.GetContext().db->config.options.storage_compatibility; + options->storage_compatibility = state.GetContext().GetDatabase().config.options.storage_compatibility; auto json = JsonSerializer::Serialize(select, doc, info.skip_if_null, info.skip_if_empty, info.skip_if_default, *options); @@ -260,7 +261,7 @@ ScalarFunctionSet JSONFunctions::GetDeserializeSqlFunction() { // JSON EXECUTE SERIALIZED SQL (PRAGMA) //---------------------------------------------------------------------- static string ExecuteJsonSerializedSqlPragmaFunction(ClientContext &context, const FunctionParameters ¶meters) { - JSONFunctionLocalState local_state(context); + JSONFunctionLocalState local_state(context.GetContext()); auto alc = local_state.json_allocator->GetYYAlc(); if (parameters.values[0].IsNull()) { @@ -306,7 +307,7 @@ struct ExecuteSqlTableFunction { static unique_ptr Bind(ClientContext &context, TableFunctionBindInput &input, vector &return_types, vector &names) { - JSONFunctionLocalState local_state(context); + JSONFunctionLocalState local_state(context.GetContext()); auto alc = local_state.json_allocator->GetYYAlc(); auto result = make_uniq(); diff --git a/src/duckdb/extension/json/json_functions/json_structure.cpp b/src/duckdb/extension/json/json_functions/json_structure.cpp index 1c5f75e07..b2b21f354 100644 --- a/src/duckdb/extension/json/json_functions/json_structure.cpp +++ b/src/duckdb/extension/json/json_functions/json_structure.cpp @@ -243,7 +243,7 @@ yyjson_mut_val *ExtractStructure(yyjson_val *val, yyjson_mut_doc *doc) { case YYJSON_TYPE_ARR | YYJSON_SUBTYPE_NONE: { auto child = HandleArrayFrame(nodes, frame, doc); if (child) { - stack.push_back(std::move(*child)); + stack.push_back(*child); } else { stack.pop_back(); } @@ -252,7 +252,7 @@ yyjson_mut_val *ExtractStructure(yyjson_val *val, yyjson_mut_doc *doc) { case YYJSON_TYPE_OBJ | YYJSON_SUBTYPE_NONE: { auto child = HandleObjectFrame(nodes, frame, doc); if (child) { - stack.push_back(std::move(*child)); + stack.push_back(*child); } else { stack.pop_back(); } diff --git a/src/duckdb/extension/json/json_functions/json_transform.cpp b/src/duckdb/extension/json/json_functions/json_transform.cpp index 39720c58f..62792a0bd 100644 --- a/src/duckdb/extension/json/json_functions/json_transform.cpp +++ b/src/duckdb/extension/json/json_functions/json_transform.cpp @@ -1328,6 +1328,8 @@ void JSONFunctions::RegisterJSONTransformCastFunctions(ExtensionLoader &loader) case LogicalTypeId::ARRAY: target_type = LogicalType::ARRAY(LogicalType::ANY, optional_idx()); break; + case LogicalTypeId::VARIANT: + continue; case LogicalTypeId::VARCHAR: // We skip this one here as it's handled in json_functions.cpp continue; diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index 952b2a96b..1643f1205 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -63,6 +63,10 @@ using duckdb_parquet::Encoding; using duckdb_parquet::PageType; using duckdb_parquet::Type; +void ByteBuffer::ThrowOutOfBuffer() { + throw std::runtime_error("Out of buffer"); +} + const uint64_t ParquetDecodeUtils::BITPACK_MASKS[] = {0, 1, 3, @@ -147,6 +151,10 @@ Allocator &ColumnReader::GetAllocator() { return reader.allocator; } +BufferManager &ColumnReader::GetBufferManager() { + return reader.buffer_manager; +} + const ParquetReader &ColumnReader::Reader() { return reader; } @@ -621,7 +629,7 @@ void ColumnReader::PreparePageV2(PageHeader &page_hdr) { page_hdr.uncompressed_page_size, page_body_size); // LCOV_EXCL_STOP } - ReadData(block->ptr, page_body_size, page_hdr.type); + ReadData(block->GetCurrentLoc(), page_body_size, page_hdr.type); return; } @@ -659,9 +667,9 @@ void ColumnReader::PreparePageV2(PageHeader &page_hdr) { // only the values are compressed, and an encrypted page body is a single module, so the body is read at once ResizeableBuffer page_buffer; - page_buffer.resize(GetAllocator(), page_body_size + 1); - ReadData(page_buffer.ptr, page_body_size, page_hdr.type); - memcpy(block->ptr, page_buffer.ptr, uncompressed_bytes); + page_buffer.Resize(GetAllocator(), page_body_size + 1); + ReadData(page_buffer.GetCurrentLoc(), page_body_size, page_hdr.type); + memcpy(block->GetCurrentLoc(), page_buffer.GetCurrentLoc(), uncompressed_bytes); auto compressed_bytes = page_body_size - uncompressed_bytes; @@ -675,8 +683,9 @@ void ColumnReader::PreparePageV2(PageHeader &page_hdr) { } if (compressed_bytes > 0) { - DecompressInternal(chunk->meta_data.codec, page_buffer.ptr + uncompressed_bytes, compressed_bytes, - block->ptr + uncompressed_bytes, page_hdr.uncompressed_page_size - uncompressed_bytes); + DecompressInternal(chunk->meta_data.codec, page_buffer.GetCurrentLoc() + uncompressed_bytes, compressed_bytes, + block->GetCurrentLoc() + uncompressed_bytes, + page_hdr.uncompressed_page_size - uncompressed_bytes); } } @@ -705,13 +714,12 @@ uint32_t ColumnReader::GetPageBodySize(const PageHeader &page_hdr) const { void ColumnReader::AllocateBlock(idx_t payload_size) { const auto allocation_size = payload_size + 1; if (!block) { - block = make_shared_ptr(GetAllocator(), allocation_size); - } else { - block->resize(GetAllocator(), allocation_size); + block = make_shared_ptr(); } + block->Resize(GetAllocator(), GetBufferManager(), allocation_size); // Keep a zeroed guard byte for decoder lookahead, but exclude it from the payload. - block->ptr[payload_size] = 0; - block->len = payload_size; + *block->GetPtrAt(payload_size) = 0; + block->Truncate(payload_size); } void ColumnReader::PreparePage(PageHeader &page_hdr) { @@ -727,16 +735,16 @@ void ColumnReader::PreparePage(PageHeader &page_hdr) { page_hdr.uncompressed_page_size, compressed_page_size); // LCOV_EXCL_STOP } - ReadData(block->ptr, compressed_page_size, page_hdr.type); + ReadData(block->GetCurrentLoc(), compressed_page_size, page_hdr.type); return; } ResizeableBuffer compressed_buffer; - compressed_buffer.resize(GetAllocator(), compressed_page_size + 1); - ReadData(compressed_buffer.ptr, compressed_page_size, page_hdr.type); + compressed_buffer.Resize(GetAllocator(), compressed_page_size + 1); + ReadData(compressed_buffer.GetCurrentLoc(), compressed_page_size, page_hdr.type); - DecompressInternal(chunk->meta_data.codec, compressed_buffer.ptr, compressed_page_size, block->ptr, - page_hdr.uncompressed_page_size); + DecompressInternal(chunk->meta_data.codec, compressed_buffer.GetCurrentLoc(), compressed_page_size, + block->GetCurrentLoc(), page_hdr.uncompressed_page_size); } static bool TryDecompressLZ4Hadoop(const_data_ptr_t src, idx_t src_size, data_ptr_t dst, idx_t dst_size) { @@ -893,23 +901,25 @@ void ColumnReader::PrepareDataPage(PageHeader &page_hdr) { auto page_encoding = is_v1 ? v1_header.encoding : v2_header.encoding; if (HasRepeats()) { - uint32_t rep_length = is_v1 ? block->read() : v2_header.repetition_levels_byte_length; - block->available(rep_length); - repeated_decoder = - make_uniq(block->ptr, rep_length, RleBpDecoder::ComputeBitWidthFromMaxValue(MaxRepeat())); - block->inc(rep_length); + uint32_t rep_length = is_v1 ? block->Read() : v2_header.repetition_levels_byte_length; + block->Available(rep_length); + repeated_decoder_offset = block->GetOffset(); + repeated_decoder = make_uniq(block->GetCurrentLoc(), rep_length, + RleBpDecoder::ComputeBitWidthFromMaxValue(MaxRepeat())); + block->Inc(rep_length); } else if (is_v2 && v2_header.repetition_levels_byte_length > 0) { - block->inc(v2_header.repetition_levels_byte_length); + block->Inc(v2_header.repetition_levels_byte_length); } if (HasDefines()) { - uint32_t def_length = is_v1 ? block->read() : v2_header.definition_levels_byte_length; - block->available(def_length); - defined_decoder = - make_uniq(block->ptr, def_length, RleBpDecoder::ComputeBitWidthFromMaxValue(MaxDefine())); - block->inc(def_length); + uint32_t def_length = is_v1 ? block->Read() : v2_header.definition_levels_byte_length; + block->Available(def_length); + defined_decoder_offset = block->GetOffset(); + defined_decoder = make_uniq(block->GetCurrentLoc(), def_length, + RleBpDecoder::ComputeBitWidthFromMaxValue(MaxDefine())); + block->Inc(def_length); } else if (is_v2 && v2_header.definition_levels_byte_length > 0) { - block->inc(v2_header.definition_levels_byte_length); + block->Inc(v2_header.definition_levels_byte_length); } switch (page_encoding) { @@ -1002,6 +1012,35 @@ bool ColumnReader::PrepareRead(idx_t read_now, data_ptr_t define_out, data_ptr_t return true; // No defines, so everything is valid } +void ColumnReader::PinBlock() { + if (block) { + block->Pin(GetBufferManager()); + RebaseDecoders(); + } +} + +void ColumnReader::RebaseDecoders() { + // Block's offset has moved on so we need to use the decoders own stored offset to calculate current location. + RebaseDecoder(repeated_decoder, *block, repeated_decoder_offset); + RebaseDecoder(defined_decoder, *block, defined_decoder_offset); + switch (encoding) { + case ColumnEncoding::DICTIONARY: + dictionary_decoder.Rebase(); + break; + case ColumnEncoding::DELTA_BINARY_PACKED: + delta_binary_packed_decoder.Rebase(); + break; + case ColumnEncoding::RLE: + rle_decoder.Rebase(); + break; + case ColumnEncoding::BYTE_STREAM_SPLIT: + byte_stream_split_decoder.Rebase(); + break; + default: + break; + } +} + void ColumnReader::ReadData(idx_t read_now, data_ptr_t define_out, data_ptr_t repeat_out, Vector &result, idx_t result_offset) { // flatten the result vector if required @@ -1018,6 +1057,9 @@ void ColumnReader::ReadData(idx_t read_now, data_ptr_t define_out, data_ptr_t re page_rows_available -= read_now; return; } + + BlockPinGuard pin_guard(*this); + // read the defines/repeats const auto all_valid = PrepareRead(read_now, define_out, repeat_out, result_offset); if (!IsRoot() && AllValuesAreNull()) { @@ -1134,7 +1176,8 @@ void ColumnReader::DirectSelect(ColumnReaderInput &input, Vector &result, const auto read_now = ReadPageHeaders(to_read); // we can only push the filter into the decoder if we are reading the ENTIRE vector in one go - if (read_now == to_read && encoding == ColumnEncoding::PLAIN) { + if (!page_is_filtered_out && read_now == to_read && encoding == ColumnEncoding::PLAIN) { + BlockPinGuard pin_guard(*this); const auto all_valid = PrepareRead(read_now, define_out, repeat_out, 0); const auto define_ptr = all_valid ? nullptr : static_cast(define_out); PlainSelect(block, define_ptr, read_now, result, sel, approved_tuple_count); @@ -1173,6 +1216,7 @@ void ColumnReader::DirectFilter(ColumnReaderInput &input, Vector &result, const // 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()) { + BlockPinGuard pin_guard(*this); if (page_is_filtered_out) { // the page has been filtered out entirely - skip approved_tuple_count = 0; @@ -1214,6 +1258,9 @@ void ColumnReader::ApplyPendingSkips(data_ptr_t define_out, data_ptr_t repeat_ou data_t skip_repeats[STANDARD_VECTOR_SIZE]; data_ptr_t skip_define_out = HasDefines() ? skip_defines : define_out; data_ptr_t skip_repeat_out = HasRepeats() ? skip_repeats : repeat_out; + + BlockPinGuard pin_guard(*this); + // start reading but do not apply skips (we are skipping now) BeginRead(nullptr, nullptr); diff --git a/src/duckdb/extension/parquet/decoder/byte_stream_split_decoder.cpp b/src/duckdb/extension/parquet/decoder/byte_stream_split_decoder.cpp index 346da31e3..b8eae394f 100644 --- a/src/duckdb/extension/parquet/decoder/byte_stream_split_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/byte_stream_split_decoder.cpp @@ -36,26 +36,31 @@ static idx_t GetValueWidth(const ParquetColumnSchema &schema) { void ByteStreamSplitDecoder::InitializePage() { auto &block = reader.block; - bss_decoder = make_uniq(block->ptr, block->len, GetValueWidth(reader.Schema())); - block->inc(block->len); + block_offset = block->GetOffset(); + idx_t bss_len; + auto loc = block->ConsumeRemaining(bss_len); + bss_decoder = make_uniq(loc, NumericCast(bss_len), GetValueWidth(reader.Schema())); +} + +void ByteStreamSplitDecoder::Rebase() { + ColumnReader::RebaseDecoder(bss_decoder, *reader.block, block_offset); } void ByteStreamSplitDecoder::Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset) { idx_t valid_count = reader.GetValidCount(defines, read_count, result_offset); - auto &allocator = reader.reader.allocator; + auto &allocator = reader.GetAllocator(); auto value_width = GetValueWidth(reader.Schema()); if (reader.Schema().parquet_type == duckdb_parquet::Type::FIXED_LEN_BYTE_ARRAY) { // string readers can reference the decoded values, so the buffer must be able to outlive this call auto plain_data = make_shared_ptr(allocator, value_width * valid_count); - bss_decoder->GetBatch(plain_data->ptr, NumericCast(valid_count)); + bss_decoder->GetBatch(plain_data->GetCurrentLoc(), NumericCast(valid_count)); reader.Plain(plain_data, defines, read_count, result_offset, result); return; } - decoded_data_buffer.reset(); - decoded_data_buffer.resize(allocator, value_width * valid_count); - bss_decoder->GetBatch(decoded_data_buffer.ptr, NumericCast(valid_count)); + decoded_data_buffer.Resize(allocator, value_width * valid_count); + bss_decoder->GetBatch(decoded_data_buffer.GetCurrentLoc(), NumericCast(valid_count)); reader.Plain(decoded_data_buffer, defines, read_count, result_offset, result); } diff --git a/src/duckdb/extension/parquet/decoder/delta_binary_packed_decoder.cpp b/src/duckdb/extension/parquet/decoder/delta_binary_packed_decoder.cpp index cac61098e..c2c6ed181 100644 --- a/src/duckdb/extension/parquet/decoder/delta_binary_packed_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/delta_binary_packed_decoder.cpp @@ -19,23 +19,28 @@ DeltaBinaryPackedDecoder::DeltaBinaryPackedDecoder(ColumnReader &reader) void DeltaBinaryPackedDecoder::InitializePage() { auto &block = reader.block; - dbp_decoder = make_uniq(block->ptr, block->len); - block->inc(block->len); + block_offset = block->GetOffset(); + idx_t dbp_len; + auto loc = block->ConsumeRemaining(dbp_len); + dbp_decoder = make_uniq(loc, dbp_len); +} + +void DeltaBinaryPackedDecoder::Rebase() { + ColumnReader::RebaseDecoder(dbp_decoder, *reader.block, block_offset); } void DeltaBinaryPackedDecoder::Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset) { idx_t valid_count = reader.GetValidCount(defines, read_count, result_offset); - auto &allocator = reader.reader.allocator; - decoded_data_buffer.reset(); + auto &allocator = reader.GetAllocator(); switch (reader.Schema().parquet_type) { case duckdb_parquet::Type::INT32: - decoded_data_buffer.resize(allocator, sizeof(int32_t) * (valid_count)); - dbp_decoder->GetBatch(decoded_data_buffer.ptr, valid_count); + decoded_data_buffer.Resize(allocator, sizeof(int32_t) * (valid_count)); + dbp_decoder->GetBatch(decoded_data_buffer.GetCurrentLoc(), valid_count); break; case duckdb_parquet::Type::INT64: - decoded_data_buffer.resize(allocator, sizeof(int64_t) * (valid_count)); - dbp_decoder->GetBatch(decoded_data_buffer.ptr, valid_count); + decoded_data_buffer.Resize(allocator, sizeof(int64_t) * (valid_count)); + dbp_decoder->GetBatch(decoded_data_buffer.GetCurrentLoc(), valid_count); break; default: diff --git a/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp b/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp index 4dc20134e..8327018ce 100644 --- a/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp @@ -25,49 +25,62 @@ class Vector; DeltaByteArrayDecoder::DeltaByteArrayDecoder(ColumnReader &reader) : reader(reader) { } -void DeltaByteArrayDecoder::ReadDbpData(Allocator &allocator, ResizeableBuffer &buffer, ResizeableBuffer &result_buffer, +template +void DeltaByteArrayDecoder::ReadDbpData(BACKING &backing, ResizeableBuffer &buffer, ResizeableBuffer &result_buffer, idx_t &value_count) { - auto decoder = make_uniq(buffer.ptr, buffer.len); + auto decoder = make_uniq(buffer.GetCurrentLoc(), buffer.GetRemaining()); value_count = decoder->TotalValues(); - result_buffer.reset(); // value_count is read from the file, so the buffer size can overflow on a corrupt input idx_t result_size; if (!TryMultiplyOperator::Operation(value_count, sizeof(uint32_t), result_size)) { throw InvalidInputException("DELTA_BYTE_ARRAY value count is too large - corrupt file?"); } - result_buffer.resize(allocator, result_size); - decoder->GetBatch(result_buffer.ptr, value_count); + result_buffer.Resize(backing, result_size); + decoder->GetBatch(result_buffer.GetCurrentLoc(), value_count); decoder->Finalize(); - buffer.inc(buffer.len - decoder->BufferPtr().len); + buffer.Inc(decoder->BytesConsumed()); } +template void DeltaByteArrayDecoder::ReadDbpData(ResizeableBuffer::SizedBacking &, + ResizeableBuffer &, ResizeableBuffer &, + idx_t &); + void DeltaByteArrayDecoder::InitializePage() { + auto &schema = reader.Schema(); + if (schema.parquet_type != duckdb_parquet::Type::BYTE_ARRAY && + schema.parquet_type != duckdb_parquet::Type::FIXED_LEN_BYTE_ARRAY) { + throw DataCorruptionException( + "DELTA_BYTE_ARRAY encoding is only supported for BYTE_ARRAY or FIXED_LEN_BYTE_ARRAY data"); + } auto &block = *reader.block; - auto &allocator = reader.reader.allocator; + auto &buffer_manager = reader.reader.buffer_manager; + auto &allocator = reader.GetAllocator(); idx_t prefix_count, suffix_count; + auto &prefix_buffer = reader.encoding_buffers[0]; - auto &suffix_buffer = reader.encoding_buffers[1]; ReadDbpData(allocator, block, prefix_buffer, prefix_count); + + auto &suffix_buffer = reader.encoding_buffers[1]; ReadDbpData(allocator, block, suffix_buffer, suffix_count); + if (prefix_count != suffix_count) { throw std::runtime_error("DELTA_BYTE_ARRAY - prefix and suffix counts are different - corrupt file?"); } - auto prefix_data = reinterpret_cast(prefix_buffer.ptr); - auto suffix_data = reinterpret_cast(suffix_buffer.ptr); + auto prefix_data = reinterpret_cast(prefix_buffer.GetCurrentLoc()); + auto suffix_data = reinterpret_cast(suffix_buffer.GetCurrentLoc()); // Allocate the plain data buffer per page plain_data = make_shared_ptr(); if (prefix_count == 0) { - plain_data->resize(allocator, 0); + plain_data->Resize(allocator, buffer_manager, 0); return; } // Decode DELTA_BYTE_ARRAY into plain Parquet page format // Plain format for BYTE_ARRAY: [4-byte length][data] repeated // Plain format for FIXED_LEN_BYTE_ARRAY: [data] repeated (no length prefix) - auto &schema = reader.Schema(); bool is_fixed_len = (schema.parquet_type == duckdb_parquet::Type::FIXED_LEN_BYTE_ARRAY); idx_t fixed_len = is_fixed_len ? schema.type_length : 0; @@ -96,11 +109,11 @@ void DeltaByteArrayDecoder::InitializePage() { } } - plain_data->resize(allocator, total_size); + plain_data->Resize(allocator, buffer_manager, total_size); unsafe_vector prev_value(max_len); idx_t prev_len = 0; - auto output = plain_data->ptr; + auto output = plain_data->GetCurrentLoc(); for (idx_t i = 0; i < prefix_count; i++) { idx_t prefix_len = prefix_data[i]; idx_t suffix_len = suffix_data[i]; @@ -115,23 +128,25 @@ void DeltaByteArrayDecoder::InitializePage() { output += sizeof(uint32_t); } - block.available(suffix_len); + block.Available(suffix_len); if (value_len > 0) { memcpy(output, prev_value.data(), prefix_len); - memcpy(output + prefix_len, block.ptr, suffix_len); + memcpy(output + prefix_len, block.GetCurrentLoc(), suffix_len); memcpy(prev_value.data(), output, value_len); } - block.inc(suffix_len); + block.Inc(suffix_len); prev_len = value_len; output += value_len; } } void DeltaByteArrayDecoder::Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset) { + ResizeableBuffer::PinGuard pin_guard(*plain_data, reader.reader.buffer_manager); reader.Plain(plain_data, defines, read_count, result_offset, result); } void DeltaByteArrayDecoder::Skip(uint8_t *defines, idx_t skip_count) { + ResizeableBuffer::PinGuard pin_guard(*plain_data, reader.reader.buffer_manager); reader.PlainSkip(*plain_data, defines, skip_count); } diff --git a/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp b/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp index 74da3df82..9a73c2b9a 100644 --- a/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp @@ -27,16 +27,19 @@ void DeltaLengthByteArrayDecoder::InitializePage() { } // read the binary packed lengths auto &block = *reader.block; - auto &allocator = reader.reader.allocator; - DeltaByteArrayDecoder::ReadDbpData(allocator, block, length_buffer, byte_array_count); + auto &buffer_manager = reader.reader.buffer_manager; + // Resize (inside ReadDbpData) must run unpinned so an evicted buffer is reallocated instead of reloaded + ResizeableBuffer::SizedBacking backing {reader.GetAllocator(), buffer_manager}; + DeltaByteArrayDecoder::ReadDbpData(backing, block, length_buffer, byte_array_count); + ResizeableBuffer::PinGuard pin_guard(length_buffer, buffer_manager); // Verify that the sum of DBP string lengths match up with the available string data idx_t total_string_length = 0; - const auto length_data = reinterpret_cast(length_buffer.ptr); + const auto length_data = reinterpret_cast(length_buffer.GetCurrentLoc()); for (idx_t i = 0; i < byte_array_count; i++) { total_string_length += length_data[i]; } - block.available(total_string_length); + block.Available(total_string_length); length_idx = 0; } @@ -58,7 +61,8 @@ template void DeltaLengthByteArrayDecoder::ReadInternal(shared_ptr &block_ref, uint8_t *const defines, const idx_t read_count, Vector &result, const idx_t result_offset) { auto &block = *block_ref; - const auto length_data = reinterpret_cast(length_buffer.ptr); + ResizeableBuffer::PinGuard pin_guard(length_buffer, reader.reader.buffer_manager); + const auto length_data = reinterpret_cast(length_buffer.GetCurrentLoc()); if (!HAS_DEFINES) { // Fast path: take this out of the loop below @@ -79,7 +83,7 @@ void DeltaLengthByteArrayDecoder::ReadInternal(shared_ptr &blo reader.Type().IsJSONType() || reader.Cast().reader.parquet_options.utf8_validation_option != StringColumnReader::Utf8ValidationOption::STRICT_UTF8; - const auto start_ptr = block.ptr; + const auto start_ptr = block.GetCurrentLoc(); auto current_ptr = start_ptr; auto result_data = FlatVector::Writer(result, read_count, result_offset); @@ -113,11 +117,12 @@ void DeltaLengthByteArrayDecoder::ReadInternal(shared_ptr &blo current_ptr += str_len; } - block.unsafe_inc(current_ptr - start_ptr); + block.UnsafeInc(NumericCast(current_ptr - start_ptr)); if (!needs_full_individual_validation) { - string_column_reader.VerifyString(char_ptr_cast(start_ptr), NumericCast(block.ptr - start_ptr)); + string_column_reader.VerifyString(char_ptr_cast(start_ptr), + NumericCast(block.GetCurrentLoc() - start_ptr)); } - StringColumnReader::ReferenceBlock(result, block_ref); + StringColumnReader::ReferenceBlock(result, block_ref, reader.reader.buffer_manager); } void DeltaLengthByteArrayDecoder::Skip(uint8_t *defines, idx_t skip_count) { @@ -131,7 +136,8 @@ void DeltaLengthByteArrayDecoder::Skip(uint8_t *defines, idx_t skip_count) { template void DeltaLengthByteArrayDecoder::SkipInternal(uint8_t *defines, idx_t skip_count) { auto &block = *reader.block; - const auto length_data = reinterpret_cast(length_buffer.ptr); + ResizeableBuffer::PinGuard pin_guard(length_buffer, reader.reader.buffer_manager); + const auto length_data = reinterpret_cast(length_buffer.GetCurrentLoc()); if (!HAS_DEFINES) { // Fast path: take this out of the loop below @@ -158,7 +164,7 @@ void DeltaLengthByteArrayDecoder::SkipInternal(uint8_t *defines, idx_t skip_coun } skip_bytes += length_data[length_idx++]; } - block.inc(skip_bytes); + block.Inc(skip_bytes); } } // namespace duckdb diff --git a/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp b/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp index 4a985408c..b27ceb417 100644 --- a/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp @@ -75,9 +75,15 @@ void DictionaryDecoder::InitializeDictionary(idx_t new_dictionary_size, optional void DictionaryDecoder::InitializePage() { // where is it otherwise?? auto &block = reader.block; - auto dict_width = block->read(); - dict_decoder = make_uniq(block->ptr, block->len, dict_width); - block->inc(block->len); + auto dict_width = block->Read(); + block_offset = block->GetOffset(); + idx_t dict_len; + auto loc = block->ConsumeRemaining(dict_len); + dict_decoder = make_uniq(loc, dict_len, dict_width); +} + +void DictionaryDecoder::Rebase() { + ColumnReader::RebaseDecoder(dict_decoder, *reader.block, block_offset); } void DictionaryDecoder::ConvertDictToSelVec(uint32_t *offsets, const SelectionVector &rows, idx_t count) { @@ -125,10 +131,9 @@ idx_t DictionaryDecoder::Read(uint8_t *defines, idx_t read_count, Vector &result } } else if (valid_count > 0) { // for the valid entries - decode the offsets - offset_buffer.reset(); - offset_buffer.resize(reader.reader.allocator, sizeof(uint32_t) * valid_count); - dict_decoder->GetBatch(offset_buffer.ptr, NumericCast(valid_count)); - ConvertDictToSelVec(reinterpret_cast(offset_buffer.ptr), valid_sel, valid_count); + offset_buffer.Resize(reader.GetAllocator(), sizeof(uint32_t) * valid_count); + dict_decoder->GetBatch(offset_buffer.GetCurrentLoc(), NumericCast(valid_count)); + ConvertDictToSelVec(reinterpret_cast(offset_buffer.GetCurrentLoc()), valid_sel, valid_count); } #ifdef DEBUG dictionary_selection_vector.Verify(read_count, dictionary_size + can_have_nulls); @@ -196,7 +201,7 @@ void DictionaryDecoder::Filter(uint8_t *defines, const idx_t read_count, Vector 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.ptr); + auto offsets = reinterpret_cast(offset_buffer.GetCurrentLoc()); D_ASSERT(offsets); approved_tuple_count = 0; for (idx_t idx = 0; idx < valid_count; idx++) { diff --git a/src/duckdb/extension/parquet/decoder/rle_decoder.cpp b/src/duckdb/extension/parquet/decoder/rle_decoder.cpp index acd73c238..cbbcda1fd 100644 --- a/src/duckdb/extension/parquet/decoder/rle_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/rle_decoder.cpp @@ -23,17 +23,21 @@ void RLEDecoder::InitializePage() { throw std::runtime_error("RLE encoding is only supported for boolean data"); } auto &block = reader.block; - block->inc(sizeof(uint32_t)); - rle_decoder = make_uniq(block->ptr, block->len, 1); + block->Inc(sizeof(uint32_t)); + block_offset = block->GetOffset(); + rle_decoder = make_uniq(block->GetCurrentLoc(), block->GetRemaining(), 1); +} + +void RLEDecoder::Rebase() { + ColumnReader::RebaseDecoder(rle_decoder, *reader.block, block_offset); } void RLEDecoder::Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset) { // RLE encoding for boolean D_ASSERT(reader.Type().id() == LogicalTypeId::BOOLEAN); idx_t valid_count = reader.GetValidCount(defines, read_count, result_offset); - decoded_data_buffer.reset(); - decoded_data_buffer.resize(reader.reader.allocator, sizeof(bool) * valid_count); - rle_decoder->GetBatch(decoded_data_buffer.ptr, valid_count); + decoded_data_buffer.Resize(reader.GetAllocator(), sizeof(bool) * valid_count); + rle_decoder->GetBatch(decoded_data_buffer.GetCurrentLoc(), valid_count); reader.PlainTemplated>(decoded_data_buffer, defines, read_count, result_offset, result); } diff --git a/src/duckdb/extension/parquet/include/column_reader.hpp b/src/duckdb/extension/parquet/include/column_reader.hpp index 66f5564ba..b1ef678f9 100644 --- a/src/duckdb/extension/parquet/include/column_reader.hpp +++ b/src/duckdb/extension/parquet/include/column_reader.hpp @@ -284,8 +284,8 @@ class ColumnReader { // we can memcpy idx_t copy_count = num_values * CONVERSION::PlainConstantSize(); if (copy_count > 0) { - memcpy(result_ptr + result_offset, plain_data.ptr, copy_count); - plain_data.unsafe_inc(copy_count); + memcpy(result_ptr + result_offset, plain_data.GetCurrentLoc(), copy_count); + plain_data.UnsafeInc(copy_count); } return; } @@ -304,9 +304,9 @@ class ColumnReader { const uint64_t num_values, idx_t row_offset = 0) { if (!HAS_DEFINES && CONVERSION::PlainConstantSize() > 0) { if (CHECKED) { - plain_data.inc(num_values * CONVERSION::PlainConstantSize()); + plain_data.Inc(num_values * CONVERSION::PlainConstantSize()); } else { - plain_data.unsafe_inc(num_values * CONVERSION::PlainConstantSize()); + plain_data.UnsafeInc(num_values * CONVERSION::PlainConstantSize()); } return; } @@ -357,6 +357,7 @@ class ColumnReader { protected: Allocator &GetAllocator(); + BufferManager &GetBufferManager(); // readers that use the default Read() need to implement those virtual void PlainSkip(ByteBuffer &plain_data, uint8_t *defines, idx_t num_values); virtual void Plain(ByteBuffer &plain_data, uint8_t *defines, idx_t num_values, idx_t result_offset, Vector &result); @@ -387,6 +388,33 @@ class ColumnReader { private: void AllocateBlock(idx_t payload_size); + //! Also rebases decoders, since pinning can move block. + void PinBlock(); + void RebaseDecoders(); + //! Callers are the decoder friend classes, which share this one rebase step. + template + static void RebaseDecoder(unique_ptr &decoder, ResizeableBuffer &block, idx_t offset) { + if (decoder) { + decoder->Rebase(block.GetPtrAt(offset)); + } + } + + class BlockPinGuard { + public: + explicit BlockPinGuard(ColumnReader &reader) : reader(reader) { + reader.PinBlock(); + } + ~BlockPinGuard() { + if (reader.block) { + reader.block->Unpin(); + } + } + BlockPinGuard(const BlockPinGuard &) = delete; + BlockPinGuard &operator=(const BlockPinGuard &) = delete; + + private: + ColumnReader &reader; + }; void PrepareRead(optional_ptr filter, optional_ptr filter_state, idx_t rows_to_skip = 0); void PreparePage(PageHeader &page_hdr); @@ -423,6 +451,9 @@ class ColumnReader { ColumnEncoding encoding = ColumnEncoding::INVALID; unique_ptr defined_decoder; unique_ptr repeated_decoder; + //! Fixed offsets used to recompute decoder's location after a re-pin. + idx_t defined_decoder_offset = 0; + idx_t repeated_decoder_offset = 0; DictionaryDecoder dictionary_decoder; DeltaBinaryPackedDecoder delta_binary_packed_decoder; RLEDecoder rle_decoder; diff --git a/src/duckdb/extension/parquet/include/decode_utils.hpp b/src/duckdb/extension/parquet/include/decode_utils.hpp index aa59f7228..6b4c46337 100644 --- a/src/duckdb/extension/parquet/include/decode_utils.hpp +++ b/src/duckdb/extension/parquet/include/decode_utils.hpp @@ -43,7 +43,7 @@ class ParquetDecodeUtils { } const auto mask = BITPACK_MASKS[width]; // check once that every byte touched from the current bit position is available - src.available((bitpack_pos + count * width + BITPACK_DLEN - 1) / BITPACK_DLEN); + src.Available((bitpack_pos + count * width + BITPACK_DLEN - 1) / BITPACK_DLEN); if (bitpack_pos == 0 && count >= BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE) { idx_t remainder = count % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; idx_t aligned_count = count - remainder; @@ -52,13 +52,13 @@ class ParquetDecodeUtils { count = remainder; } for (idx_t i = 0; i < count; i++) { - auto val = (src.unsafe_get() >> bitpack_pos) & mask; + auto val = (src.UnsafeGet() >> bitpack_pos) & mask; bitpack_pos += width; while (bitpack_pos > BITPACK_DLEN) { - src.unsafe_inc(1); - val |= (static_cast(src.unsafe_get()) - << static_cast(BITPACK_DLEN - (bitpack_pos - width))) & - mask; + src.UnsafeInc(1); + val |= + (static_cast(src.UnsafeGet()) << static_cast(BITPACK_DLEN - (bitpack_pos - width))) & + mask; bitpack_pos -= BITPACK_DLEN; } dst[i] = val; @@ -68,7 +68,7 @@ class ParquetDecodeUtils { static void Skip(ByteBuffer &src, bitpacking_width_t &bitpack_pos, idx_t count, const bitpacking_width_t width) { CheckWidth(width); // check once that every byte touched from the current bit position is available - src.available((bitpack_pos + count * width + BITPACK_DLEN - 1) / BITPACK_DLEN); + src.Available((bitpack_pos + count * width + BITPACK_DLEN - 1) / BITPACK_DLEN); if (bitpack_pos == 0 && count >= BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE) { idx_t remainder = count % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; idx_t aligned_count = count - remainder; @@ -80,7 +80,7 @@ class ParquetDecodeUtils { bitpack_pos = UnsafeNumericCast(total_bits); } else { const idx_t bytes_to_advance = (total_bits - 1) / BITPACK_DLEN; - src.unsafe_inc(bytes_to_advance); + src.UnsafeInc(bytes_to_advance); bitpack_pos = UnsafeNumericCast(total_bits - bytes_to_advance * BITPACK_DLEN); } } @@ -101,10 +101,10 @@ class ParquetDecodeUtils { width, sizeof(T) * BITPACK_DLEN); } - if (cast_pointer_to_uint64(src.ptr) % sizeof(T) == 0) { + if (cast_pointer_to_uint64(src.GetCurrentLoc()) % sizeof(T) == 0) { // Fast path: aligned - BitpackingPrimitives::UnPackBuffer(data_ptr_cast(dst), src.ptr, count, width); - src.unsafe_inc(count * width / BITPACK_DLEN); + BitpackingPrimitives::UnPackBuffer(data_ptr_cast(dst), src.GetCurrentLoc(), count, width); + src.UnsafeInc(count * width / BITPACK_DLEN); return; } @@ -115,12 +115,12 @@ class ParquetDecodeUtils { T aligned_data[BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE]; // Copy over to aligned buffer - memcpy(aligned_data, src.ptr, next_read); + memcpy(aligned_data, src.GetCurrentLoc(), next_read); // Unpack BitpackingPrimitives::UnPackBlock(data_ptr_cast(dst), data_ptr_cast(aligned_data), width, true); - src.unsafe_inc(next_read); + src.UnsafeInc(next_read); dst += BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; } } @@ -133,7 +133,7 @@ class ParquetDecodeUtils { BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE); } const auto read_size = count * width / BITPACK_DLEN; - src.available(read_size); // check if buffer has enough space available once + src.Available(read_size); // check if buffer has enough space available once BitUnpackAlignedInternal(src, dst, count, width); } @@ -144,7 +144,7 @@ class ParquetDecodeUtils { BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE); } const auto read_size = count * width / BITPACK_DLEN; - src.inc(read_size); + src.Inc(read_size); } //===--------------------------------------------------------------------===// @@ -215,9 +215,9 @@ class ParquetDecodeUtils { while (true) { uint8_t byte; if (CHECKED) { - byte = buf.read(); + byte = buf.Read(); } else { - byte = buf.unsafe_read(); + byte = buf.UnsafeRead(); } result |= T(byte & 127) << shift; if ((byte & 128) == 0) { diff --git a/src/duckdb/extension/parquet/include/decoder/byte_stream_split_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/byte_stream_split_decoder.hpp index a15fe0c8d..e43517544 100644 --- a/src/duckdb/extension/parquet/include/decoder/byte_stream_split_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/byte_stream_split_decoder.hpp @@ -26,6 +26,7 @@ class ByteStreamSplitDecoder { public: void InitializePage(); + void Rebase(); void Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset); void Skip(uint8_t *defines, idx_t skip_count); @@ -33,6 +34,7 @@ class ByteStreamSplitDecoder { ColumnReader &reader; ResizeableBuffer &decoded_data_buffer; unique_ptr bss_decoder; + idx_t block_offset = 0; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/decoder/delta_binary_packed_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/delta_binary_packed_decoder.hpp index ed20b9fdd..e582a6083 100644 --- a/src/duckdb/extension/parquet/include/decoder/delta_binary_packed_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/delta_binary_packed_decoder.hpp @@ -27,6 +27,7 @@ class DeltaBinaryPackedDecoder { public: void InitializePage(); + void Rebase(); void Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset); void Skip(uint8_t *defines, idx_t skip_count); @@ -34,6 +35,7 @@ class DeltaBinaryPackedDecoder { ColumnReader &reader; ResizeableBuffer &decoded_data_buffer; unique_ptr dbp_decoder; + idx_t block_offset = 0; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/decoder/delta_byte_array_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/delta_byte_array_decoder.hpp index 4dcebc3f4..fb52c7898 100644 --- a/src/duckdb/extension/parquet/include/decoder/delta_byte_array_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/delta_byte_array_decoder.hpp @@ -18,7 +18,7 @@ namespace duckdb { class ColumnReader; -class Allocator; +class BufferManager; class ResizeableBuffer; class Vector; @@ -32,7 +32,10 @@ class DeltaByteArrayDecoder { void Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset); void Skip(uint8_t *defines, idx_t skip_count); - static void ReadDbpData(Allocator &allocator, ResizeableBuffer &buffer, ResizeableBuffer &result_buffer, + //! BACKING is Allocator for single-call scratch or ResizeableBuffer::SizedBacking for buffers that must stay + //! evictable + template + static void ReadDbpData(BACKING &backing, ResizeableBuffer &buffer, ResizeableBuffer &result_buffer, idx_t &value_count); private: diff --git a/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp index e3fb734a7..ea3477cea 100644 --- a/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp @@ -35,6 +35,7 @@ class DictionaryDecoder { void InitializeDictionary(idx_t dictionary_size, optional_ptr filter, optional_ptr filter_state, bool has_defines); void InitializePage(); + 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); @@ -55,6 +56,7 @@ class DictionaryDecoder { ColumnReader &reader; ResizeableBuffer &offset_buffer; unique_ptr dict_decoder; + idx_t block_offset = 0; SelectionVector valid_sel; SelectionVector dictionary_selection_vector; idx_t dictionary_size; diff --git a/src/duckdb/extension/parquet/include/decoder/rle_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/rle_decoder.hpp index fb650a06f..bc1032ce3 100644 --- a/src/duckdb/extension/parquet/include/decoder/rle_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/rle_decoder.hpp @@ -26,6 +26,7 @@ class RLEDecoder { public: void InitializePage(); + void Rebase(); void Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset); void Skip(uint8_t *defines, idx_t skip_count); @@ -33,6 +34,7 @@ class RLEDecoder { ColumnReader &reader; ResizeableBuffer &decoded_data_buffer; unique_ptr rle_decoder; + idx_t block_offset = 0; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp b/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp index 53159f51d..cb45ab97a 100644 --- a/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp +++ b/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp @@ -30,10 +30,10 @@ class BssDecoder { public: /// 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_); + buffer_.Available((value_offset_ + batch_size) * type_size_); for (idx_t byte_offset = 0; byte_offset < type_size_; ++byte_offset) { - data_ptr_t input_bytes = buffer_.ptr + byte_offset * num_buffer_values_ + value_offset_; + data_ptr_t input_bytes = buffer_.GetCurrentLoc() + byte_offset * num_buffer_values_ + value_offset_; for (uint32_t i = 0; i < batch_size; ++i) { values_target_ptr[byte_offset + i * type_size_] = *(input_bytes + i); } @@ -42,10 +42,14 @@ class BssDecoder { } void Skip(uint32_t batch_size) { - buffer_.available((value_offset_ + batch_size) * type_size_); + buffer_.Available((value_offset_ + batch_size) * type_size_); value_offset_ += batch_size; } + void Rebase(data_ptr_t new_ptr) { + buffer_.Rebase(new_ptr); + } + private: ByteBuffer buffer_; idx_t type_size_; diff --git a/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp b/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp index 6f71072e3..8b31ef006 100644 --- a/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp +++ b/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp @@ -24,7 +24,7 @@ class DbpDecoder { previous_value(ParquetDecodeUtils::ZigzagToInt(ParquetDecodeUtils::VarintDecode(buffer_))), // init state to something sane is_first_value(true), read_values(0), min_delta(NumericLimits::Maximum()), - miniblock_index(number_of_miniblocks_per_block - 1), list_of_bitwidths_of_miniblocks(nullptr), + miniblock_index(number_of_miniblocks_per_block - 1), list_of_bitwidths_relative_offset(0), miniblock_offset(number_of_values_in_a_miniblock), unpacked_data_offset(BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE) { if (!(block_size_in_values % number_of_miniblocks_per_block == 0 && number_of_values_in_a_miniblock > 0 && @@ -33,8 +33,8 @@ class DbpDecoder { } } - ByteBuffer BufferPtr() const { - return buffer_; + idx_t BytesConsumed() const { + return buffer_.GetOffset(); } uint64_t TotalValues() const { @@ -70,6 +70,10 @@ class DbpDecoder { GetBatchInternal(data_ptr_cast(data.get()), number_of_values_in_a_miniblock - miniblock_offset); } + void Rebase(data_ptr_t new_ptr) { + buffer_.Rebase(new_ptr); + } + private: static idx_t DecodeNumberOfMiniblocksPerBlock(ByteBuffer &buffer) { auto res = ParquetDecodeUtils::VarintDecode(buffer); @@ -128,17 +132,17 @@ class DbpDecoder { if (++miniblock_index == number_of_miniblocks_per_block) { // min_delta = ParquetDecodeUtils::ZigzagToInt(ParquetDecodeUtils::VarintDecode(buffer_)); - buffer_.available(number_of_miniblocks_per_block); - list_of_bitwidths_of_miniblocks = buffer_.ptr; - buffer_.unsafe_inc(number_of_miniblocks_per_block); + buffer_.Available(number_of_miniblocks_per_block); + list_of_bitwidths_relative_offset = buffer_.GetOffset(); + buffer_.UnsafeInc(number_of_miniblocks_per_block); miniblock_index = 0; } } // Unpack from current miniblock - ParquetDecodeUtils::BitUnpackAligned(buffer_, unpacked_data, - BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE, - list_of_bitwidths_of_miniblocks[miniblock_index]); + ParquetDecodeUtils::BitUnpackAligned( + buffer_, unpacked_data, BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE, + Load(buffer_.GetPtrAt(list_of_bitwidths_relative_offset) + miniblock_index)); unpacked_data_offset = 0; miniblock_offset += BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; } @@ -158,7 +162,7 @@ class DbpDecoder { //! Block stuff int64_t min_delta; idx_t miniblock_index; - bitpacking_width_t *list_of_bitwidths_of_miniblocks; + idx_t list_of_bitwidths_relative_offset; idx_t miniblock_offset; uint64_t unpacked_data[BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE]; idx_t unpacked_data_offset; diff --git a/src/duckdb/extension/parquet/include/parquet_field_id.hpp b/src/duckdb/extension/parquet/include/parquet_field_id.hpp index 294587dd0..efc0cee65 100644 --- a/src/duckdb/extension/parquet/include/parquet_field_id.hpp +++ b/src/duckdb/extension/parquet/include/parquet_field_id.hpp @@ -44,7 +44,7 @@ struct FieldID { public: static void GenerateFieldIDs(ChildFieldIDs &field_ids, idx_t &field_id, const vector &names, const vector &sql_types); - static void GetFieldIDs(const Value &field_ids_value, ChildFieldIDs &field_ids, + static void GetFieldIDs(Context &context, const Value &field_ids_value, ChildFieldIDs &field_ids, unordered_set &unique_field_ids, const case_insensitive_map_t &name_to_type_map); }; diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index 1eb57608e..9113bf6f2 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -393,6 +393,7 @@ class ParquetReader : public BaseFileReader { mutable CachingFileSystem fs; Allocator &allocator; + BufferManager &buffer_manager; shared_ptr metadata; ParquetOptions parquet_options; unique_ptr root_schema; diff --git a/src/duckdb/extension/parquet/include/parquet_rle_bp_decoder.hpp b/src/duckdb/extension/parquet/include/parquet_rle_bp_decoder.hpp index cb1f363f4..6682b6473 100644 --- a/src/duckdb/extension/parquet/include/parquet_rle_bp_decoder.hpp +++ b/src/duckdb/extension/parquet/include/parquet_rle_bp_decoder.hpp @@ -107,6 +107,10 @@ class RleBpDecoder { return ComputeBitWidthFromMaxValue(value_count - 1); } + void Rebase(data_ptr_t new_ptr) { + buffer_.Rebase(new_ptr); + } + private: ByteBuffer buffer_; @@ -128,9 +132,9 @@ class RleBpDecoder { // The int is encoded as a vlq-encoded value. if (bitpack_pos != 0) { if (CHECKED) { - buffer_.inc(1); + buffer_.Inc(1); } else { - buffer_.unsafe_inc(1); + buffer_.UnsafeInc(1); } bitpack_pos = 0; } @@ -145,13 +149,13 @@ class RleBpDecoder { // (ARROW-4018) this is not big-endian compatible, lol current_value_ = 0; if (CHECKED) { - buffer_.available(byte_encoded_len); + buffer_.Available(byte_encoded_len); } for (auto i = 0; i < byte_encoded_len; i++) { - auto next_byte = Load(buffer_.ptr + i); + auto next_byte = Load(buffer_.GetCurrentLoc() + i); current_value_ |= (static_cast(next_byte) << (i * 8)); } - buffer_.unsafe_inc(byte_encoded_len); + buffer_.UnsafeInc(byte_encoded_len); // sanity check if (repeat_count_ > 0 && current_value_ > max_val) { throw std::runtime_error("Payload value bigger than allowed. Corrupted file?"); @@ -160,7 +164,7 @@ class RleBpDecoder { } void NextCounts() { - if (buffer_.check_available(byte_encoded_len + sizeof(uint32_t) + 2)) { + if (buffer_.CheckAvailable(byte_encoded_len + sizeof(uint32_t) + 2)) { NextCountsTemplated(); } else { NextCountsTemplated(); diff --git a/src/duckdb/extension/parquet/include/parquet_statistics.hpp b/src/duckdb/extension/parquet/include/parquet_statistics.hpp index adcaa0ea7..2557e20c4 100644 --- a/src/duckdb/extension/parquet/include/parquet_statistics.hpp +++ b/src/duckdb/extension/parquet/include/parquet_statistics.hpp @@ -125,7 +125,7 @@ class ParquetBloomFilter { static unique_ptr Create(Allocator &allocator, idx_t num_entries, double target); static optional_idx EstimateSize(idx_t num_entries, double target); static unique_ptr TryCreate(Allocator &allocator, idx_t num_entries, double target, - shared_ptr memory); + const shared_ptr &memory); void FilterInsert(uint64_t x); bool FilterCheck(uint64_t x); void Shrink(Allocator &allocator, idx_t new_block_count); diff --git a/src/duckdb/extension/parquet/include/reader/boolean_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/boolean_column_reader.hpp index 12b4244f0..a962b1afe 100644 --- a/src/duckdb/extension/parquet/include/reader/boolean_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/boolean_column_reader.hpp @@ -43,14 +43,13 @@ struct BooleanParquetValueConversion { template static bool PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { auto &byte_pos = reader.Cast().byte_pos; - bool ret = (*plain_data.ptr >> byte_pos) & 1; + if (CHECKED) { + plain_data.Available(1); + } + bool ret = (*plain_data.GetCurrentLoc() >> byte_pos) & 1; if (++byte_pos == 8) { byte_pos = 0; - if (CHECKED) { - plain_data.inc(1); - } else { - plain_data.unsafe_inc(1); - } + plain_data.UnsafeInc(1); } return ret; } @@ -61,7 +60,7 @@ struct BooleanParquetValueConversion { } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { - return plain_data.check_available((count + 7) / 8); + return plain_data.CheckAvailable((count + 7) / 8); } static idx_t PlainConstantSize() { diff --git a/src/duckdb/extension/parquet/include/reader/byte_array_length_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/byte_array_length_column_reader.hpp index 3138233bf..7fea22179 100644 --- a/src/duckdb/extension/parquet/include/reader/byte_array_length_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/byte_array_length_column_reader.hpp @@ -60,18 +60,18 @@ struct ByteArrayLengthValueConversion { template static int64_t PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { auto &r = reader.Cast(); - const uint32_t len = r.fixed_width_string_length == DConstants::INVALID_INDEX ? plain_data.read() + const uint32_t len = r.fixed_width_string_length == DConstants::INVALID_INDEX ? plain_data.Read() : r.fixed_width_string_length; - plain_data.available(len); - plain_data.inc(len); + plain_data.Available(len); + plain_data.Inc(len); return static_cast(len); } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { auto &r = reader.Cast(); - const uint32_t len = r.fixed_width_string_length == DConstants::INVALID_INDEX ? plain_data.read() + const uint32_t len = r.fixed_width_string_length == DConstants::INVALID_INDEX ? plain_data.Read() : r.fixed_width_string_length; - plain_data.inc(len); + plain_data.Inc(len); } static bool PlainAvailable(const ByteBuffer &, const idx_t) { return false; diff --git a/src/duckdb/extension/parquet/include/reader/callback_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/callback_column_reader.hpp index eb6a98aab..a63cb06f3 100644 --- a/src/duckdb/extension/parquet/include/reader/callback_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/callback_column_reader.hpp @@ -36,9 +36,9 @@ class CallbackColumnReader protected: void Dictionary(shared_ptr dictionary_data, idx_t num_entries) { BaseType::AllocateDict(num_entries * sizeof(DUCKDB_PHYSICAL_TYPE)); - auto dict_ptr = (DUCKDB_PHYSICAL_TYPE *)this->dict->ptr; + auto dict_ptr = (DUCKDB_PHYSICAL_TYPE *)this->dict->GetCurrentLoc(); for (idx_t i = 0; i < num_entries; i++) { - dict_ptr[i] = FUNC(dictionary_data->read()); + dict_ptr[i] = FUNC(dictionary_data->Read()); } } }; diff --git a/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp index bc3a3eba0..603756ab2 100644 --- a/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp @@ -29,20 +29,20 @@ struct DecimalParquetValueConversion { if (FIXED_LENGTH) { byte_len = reader.Schema().type_length; } else { - byte_len = plain_data.read(); + byte_len = plain_data.Read(); } - plain_data.available(byte_len); - auto res = ParquetDecimalUtils::ReadDecimalValue(const_data_ptr_cast(plain_data.ptr), - byte_len, reader.Schema()); + plain_data.Available(byte_len); + auto res = ParquetDecimalUtils::ReadDecimalValue( + const_data_ptr_cast(plain_data.GetCurrentLoc()), byte_len, reader.Schema()); - plain_data.inc(byte_len); + plain_data.Inc(byte_len); return res; } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { - uint32_t decimal_len = FIXED_LENGTH ? reader.Schema().type_length : plain_data.read(); - plain_data.inc(decimal_len); + uint32_t decimal_len = FIXED_LENGTH ? reader.Schema().type_length : plain_data.Read(); + plain_data.Inc(decimal_len); } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { diff --git a/src/duckdb/extension/parquet/include/reader/interval_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/interval_column_reader.hpp index 90c32d37f..200537fd8 100644 --- a/src/duckdb/extension/parquet/include/reader/interval_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/interval_column_reader.hpp @@ -31,24 +31,24 @@ struct IntervalValueConversion { template static interval_t PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - plain_data.available(PARQUET_INTERVAL_SIZE); + plain_data.Available(PARQUET_INTERVAL_SIZE); } - auto res = ReadParquetInterval(const_data_ptr_cast(plain_data.ptr)); - plain_data.unsafe_inc(PARQUET_INTERVAL_SIZE); + auto res = ReadParquetInterval(const_data_ptr_cast(plain_data.GetCurrentLoc())); + plain_data.UnsafeInc(PARQUET_INTERVAL_SIZE); return res; } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - plain_data.inc(PARQUET_INTERVAL_SIZE); + plain_data.Inc(PARQUET_INTERVAL_SIZE); } else { - plain_data.unsafe_inc(PARQUET_INTERVAL_SIZE); + plain_data.UnsafeInc(PARQUET_INTERVAL_SIZE); } } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { - return plain_data.check_available(count * PARQUET_INTERVAL_SIZE); + return plain_data.CheckAvailable(count * PARQUET_INTERVAL_SIZE); } static idx_t PlainConstantSize() { diff --git a/src/duckdb/extension/parquet/include/reader/string_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/string_column_reader.hpp index 48a6be4d5..493d246be 100644 --- a/src/duckdb/extension/parquet/include/reader/string_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/string_column_reader.hpp @@ -72,7 +72,7 @@ class StringColumnReader : public ColumnReader { string_t VerifyString(const char *str_data, uint32_t str_len, bool is_varchar) const; string_t VerifyString(const char *str_data, uint32_t str_len) const; - static void ReferenceBlock(Vector &result, shared_ptr &block); + static void ReferenceBlock(Vector &result, shared_ptr &block, BufferManager &buffer_manager); protected: void Plain(ByteBuffer &plain_data, uint8_t *defines, idx_t num_values, idx_t result_offset, @@ -101,19 +101,19 @@ struct StringParquetValueConversion { static string_t PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { auto &scr = reader.Cast(); uint32_t str_len = - scr.fixed_width_string_length == 0 ? plain_data.read() : scr.fixed_width_string_length; - plain_data.available(str_len); - auto plain_str = char_ptr_cast(plain_data.ptr); + scr.fixed_width_string_length == 0 ? plain_data.Read() : scr.fixed_width_string_length; + plain_data.Available(str_len); + auto plain_str = char_ptr_cast(plain_data.GetCurrentLoc()); auto ret_str = scr.VerifyString(plain_str, str_len); - plain_data.inc(str_len); + plain_data.Inc(str_len); return ret_str; } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { auto &scr = reader.Cast(); uint32_t str_len = - scr.fixed_width_string_length == 0 ? plain_data.read() : scr.fixed_width_string_length; - plain_data.inc(str_len); + scr.fixed_width_string_length == 0 ? plain_data.Read() : scr.fixed_width_string_length; + plain_data.Inc(str_len); } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { return false; diff --git a/src/duckdb/extension/parquet/include/reader/templated_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/templated_column_reader.hpp index 26f319e11..cdcba62ba 100644 --- a/src/duckdb/extension/parquet/include/reader/templated_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/templated_column_reader.hpp @@ -18,23 +18,23 @@ struct TemplatedParquetValueConversion { template static VALUE_TYPE PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - return plain_data.read(); + return plain_data.Read(); } else { - return plain_data.unsafe_read(); + return plain_data.UnsafeRead(); } } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - plain_data.inc(sizeof(VALUE_TYPE)); + plain_data.Inc(sizeof(VALUE_TYPE)); } else { - plain_data.unsafe_inc(sizeof(VALUE_TYPE)); + plain_data.UnsafeInc(sizeof(VALUE_TYPE)); } } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { - return plain_data.check_available(count * sizeof(VALUE_TYPE)); + return plain_data.CheckAvailable(count * sizeof(VALUE_TYPE)); } static idx_t PlainConstantSize() { @@ -59,7 +59,7 @@ class TemplatedColumnReader : public ColumnReader { if (!dict) { dict = make_shared_ptr(GetAllocator(), size); } else { - dict->resize(GetAllocator(), size); + dict->Resize(GetAllocator(), size); } } @@ -83,23 +83,23 @@ struct CallbackParquetValueConversion { template static DUCKDB_PHYSICAL_TYPE PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - return FUNC(plain_data.read()); + return FUNC(plain_data.Read()); } else { - return FUNC(plain_data.unsafe_read()); + return FUNC(plain_data.UnsafeRead()); } } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - plain_data.inc(sizeof(PARQUET_PHYSICAL_TYPE)); + plain_data.Inc(sizeof(PARQUET_PHYSICAL_TYPE)); } else { - plain_data.unsafe_inc(sizeof(PARQUET_PHYSICAL_TYPE)); + plain_data.UnsafeInc(sizeof(PARQUET_PHYSICAL_TYPE)); } } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { - return plain_data.check_available(count * sizeof(PARQUET_PHYSICAL_TYPE)); + return plain_data.CheckAvailable(count * sizeof(PARQUET_PHYSICAL_TYPE)); } static idx_t PlainConstantSize() { diff --git a/src/duckdb/extension/parquet/include/reader/uuid_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/uuid_column_reader.hpp index 0926e87e6..863cdd901 100644 --- a/src/duckdb/extension/parquet/include/reader/uuid_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/uuid_column_reader.hpp @@ -24,24 +24,24 @@ struct UUIDValueConversion { template static hugeint_t PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - plain_data.available(sizeof(hugeint_t)); + plain_data.Available(sizeof(hugeint_t)); } - auto res = ReadParquetUUID(const_data_ptr_cast(plain_data.ptr)); - plain_data.unsafe_inc(sizeof(hugeint_t)); + auto res = ReadParquetUUID(const_data_ptr_cast(plain_data.GetCurrentLoc())); + plain_data.UnsafeInc(sizeof(hugeint_t)); return res; } template static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { if (CHECKED) { - plain_data.inc(sizeof(hugeint_t)); + plain_data.Inc(sizeof(hugeint_t)); } else { - plain_data.unsafe_inc(sizeof(hugeint_t)); + plain_data.UnsafeInc(sizeof(hugeint_t)); } } static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { - return plain_data.check_available(count * sizeof(hugeint_t)); + return plain_data.CheckAvailable(count * sizeof(hugeint_t)); } static idx_t PlainConstantSize() { diff --git a/src/duckdb/extension/parquet/include/resizable_buffer.hpp b/src/duckdb/extension/parquet/include/resizable_buffer.hpp index 7452ddd8f..1b7de0e8d 100644 --- a/src/duckdb/extension/parquet/include/resizable_buffer.hpp +++ b/src/duckdb/extension/parquet/include/resizable_buffer.hpp @@ -13,101 +13,239 @@ #include +#include "duckdb/common/enums/memory_tag.hpp" +#include "duckdb/storage/buffer_manager.hpp" +#include "duckdb/storage/storage_info.hpp" + namespace duckdb { class ByteBuffer { // on to the 10 thousandth impl public: ByteBuffer() {}; - ByteBuffer(data_ptr_t ptr, uint64_t len) : ptr(ptr), len(len) {}; - - data_ptr_t ptr = nullptr; - uint64_t len = 0; + ByteBuffer(const data_ptr_t ptr, const idx_t len) : ptr(ptr), len(len) {}; public: - void inc(const uint64_t increment) { - available(increment); - unsafe_inc(increment); + data_ptr_t GetCurrentLoc() const { + return ptr + offset; + } + + idx_t GetOffset() const { + return offset; + } + + idx_t GetLength() const { + return len; + } + + idx_t GetRemaining() const { + return len - offset; + } + + data_ptr_t ConsumeRemaining(idx_t &length_out) { + length_out = GetRemaining(); + auto loc = GetCurrentLoc(); + UnsafeInc(length_out); + return loc; + } + + data_ptr_t GetPtrAt(const idx_t rel_offset) const { + return ptr + rel_offset; + } + + void Inc(const idx_t increment) { + Available(increment); + UnsafeInc(increment); } - void unsafe_inc(const uint64_t increment) { - len -= increment; - ptr += increment; + void UnsafeInc(const idx_t increment) { + offset += increment; } template - T read() { - available(sizeof(T)); - return unsafe_read(); + T Read() { + Available(sizeof(T)); + return UnsafeRead(); } template - T unsafe_read() { - T val = unsafe_get(); - unsafe_inc(sizeof(T)); + T UnsafeRead() { + T val = UnsafeGet(); + UnsafeInc(sizeof(T)); return val; } template - T get() { - available(sizeof(T)); - return unsafe_get(); + T Get() { + Available(sizeof(T)); + return UnsafeGet(); } template - T unsafe_get() { - return Load(ptr); + T UnsafeGet() { + return Load(ptr + offset); } - void copy_to(char *dest, const uint64_t len) const { - available(len); - unsafe_copy_to(dest, len); + void CopyTo(char *dest, const idx_t copy_len) const { + Available(copy_len); + UnsafeCopyTo(dest, copy_len); } - void unsafe_copy_to(char *dest, const uint64_t len) const { - std::memcpy(dest, ptr, len); + void UnsafeCopyTo(char *dest, const idx_t copy_len) const { + std::memcpy(dest, ptr + offset, copy_len); } - void zero() const { - std::memset(ptr, 0, len); + void Zero() const { + std::memset(ptr + offset, 0, len - offset); } - void available(const uint64_t req_len) const { - if (!check_available(req_len)) { - throw std::runtime_error("Out of buffer"); + void Available(const idx_t req_len) const { + if (!CheckAvailable(req_len)) { + ThrowOutOfBuffer(); } } - bool check_available(const uint64_t req_len) const { - return req_len <= len; + // Out of line so the throw does not stop Available from inlining. + [[noreturn]] static void ThrowOutOfBuffer(); + + bool CheckAvailable(const idx_t req_len) const { + return req_len <= len - offset; + } + + void Rebase(const data_ptr_t new_ptr) { + ptr = new_ptr; } + + //! Shrink the readable length without touching the allocation. + void Truncate(const idx_t new_len) { + D_ASSERT(new_len <= len); + len = new_len; + } + +protected: + data_ptr_t ptr = nullptr; + + idx_t offset = 0; + idx_t len = 0; }; class ResizeableBuffer : public ByteBuffer { public: ResizeableBuffer() { } - ResizeableBuffer(Allocator &allocator, const uint64_t new_size) { - resize(allocator, new_size); + + ResizeableBuffer(Allocator &allocator, const idx_t new_size) { + Resize(allocator, new_size); } - void resize(Allocator &allocator, const uint64_t new_size) { - len = new_size; - if (new_size == 0) { - return; + + void Resize(Allocator &allocator, const idx_t new_size) { + if (block_handle) { + ReleaseAll(); } - if (new_size > alloc_len) { - alloc_len = NextPowerOfTwo(new_size); + if (PrepareResize(new_size)) { allocated_data.Reset(); // Have to reset before allocating new buffer (otherwise we use ~2x the memory) allocated_data = allocator.Allocate(alloc_len); ptr = allocated_data.get(); } } - void reset() { - ptr = allocated_data.get(); - len = alloc_len; + + //! Managed-block registration costs more than a smaller buffer can repay in evictability. + static constexpr idx_t EVICTABLE_SIZE_THRESHOLD = 131072; + + struct SizedBacking { + Allocator &allocator; + BufferManager &buffer_manager; + }; + + void Resize(SizedBacking &backing, const idx_t new_size) { + if (new_size < EVICTABLE_SIZE_THRESHOLD) { + Resize(backing.allocator, new_size); + } else { + Resize(backing.buffer_manager, new_size); + } + } + + void Resize(Allocator &allocator, BufferManager &buffer_manager, const idx_t new_size) { + SizedBacking backing {allocator, buffer_manager}; + Resize(backing, new_size); + } + + void Pin(BufferManager &buffer_manager) { + if (block_handle && !handle.IsValid()) { + handle = buffer_manager.Pin(block_handle); + ptr = handle.GetDataMutable(); + } + } + + void Unpin() { + if (block_handle) { + handle.Destroy(); + ptr = nullptr; + } + } + + //! RAII pin, like std::lock_guard: construct it as a named local to keep the buffer pinned for that scope. + class PinGuard { + public: + PinGuard(ResizeableBuffer &buffer, BufferManager &buffer_manager) : buffer(buffer) { + buffer.Pin(buffer_manager); + } + ~PinGuard() { + buffer.Unpin(); + } + PinGuard(const PinGuard &) = delete; + PinGuard &operator=(const PinGuard &) = delete; + + private: + ResizeableBuffer &buffer; + }; + + shared_ptr &GetBlockHandle() { + return block_handle; } private: + //! Private so every caller goes through the size threshold instead of registering a managed block directly. + void Resize(BufferManager &buffer_manager, const idx_t new_size) { + if (allocated_data.get()) { + ReleaseAll(); + } + // Unpinned reuse is overwritten anyway; allocate fresh instead of reloading a spilled block. + if (PrepareResize(new_size) || (new_size > 0 && block_handle && !handle.IsValid())) { + // Keep header+payload a power of two so BlockAllocator's cache can recycle it instead of purging to the OS. + alloc_len = + NextPowerOfTwo(new_size + Storage::DEFAULT_BLOCK_HEADER_SIZE) - Storage::DEFAULT_BLOCK_HEADER_SIZE; + handle.Destroy(); + block_handle.reset(); // release before allocating, so old and new aren't counted at once + handle = buffer_manager.Allocate(MemoryTag::PARQUET_READER, alloc_len, false); + block_handle = handle.GetBlockHandle(); + ptr = handle.GetDataMutable(); + } + } + + //! A shared buffer can switch backing modes when the page encoding changes. + void ReleaseAll() { + handle.Destroy(); + block_handle.reset(); + allocated_data.Reset(); + ptr = nullptr; + alloc_len = 0; + } + + //! Sets the new length and reports whether a larger allocation is needed. + bool PrepareResize(const idx_t new_size) { + len = new_size; + offset = 0; + if (new_size <= alloc_len || new_size == 0) { + return false; + } + alloc_len = NextPowerOfTwo(new_size); + return true; + } + AllocatedData allocated_data; + shared_ptr block_handle; + BufferHandle handle; + idx_t alloc_len = 0; }; diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index b56dfd409..cfa5e4650 100644 --- a/src/duckdb/extension/parquet/parquet_extension.cpp +++ b/src/duckdb/extension/parquet/parquet_extension.cpp @@ -228,7 +228,8 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun } name_to_type_map.emplace(names[col_idx], sql_types[col_idx]); } - FieldID::GetFieldIDs(option_values[0], bind_data->field_ids, unique_field_ids, name_to_type_map); + FieldID::GetFieldIDs(context.GetContext(), option_values[0], bind_data->field_ids, unique_field_ids, + name_to_type_map); } } else if (option_name == "shredding") { if (option_values[0].type().id() == LogicalTypeId::VARCHAR && diff --git a/src/duckdb/extension/parquet/parquet_field_id.cpp b/src/duckdb/extension/parquet/parquet_field_id.cpp index 38b5a2754..1d16446b6 100644 --- a/src/duckdb/extension/parquet/parquet_field_id.cpp +++ b/src/duckdb/extension/parquet/parquet_field_id.cpp @@ -76,7 +76,7 @@ void FieldID::GenerateFieldIDs(ChildFieldIDs &field_ids, idx_t &field_id, const } } -void FieldID::GetFieldIDs(const Value &field_ids_value, ChildFieldIDs &field_ids, +void FieldID::GetFieldIDs(Context &context, const Value &field_ids_value, ChildFieldIDs &field_ids, unordered_set &unique_field_ids, const case_insensitive_map_t &name_to_type_map) { const auto &struct_type = field_ids_value.type(); @@ -132,7 +132,7 @@ void FieldID::GetFieldIDs(const Value &field_ids_value, ChildFieldIDs &field_ids FieldID field_id; if (field_id_value) { - Value field_id_integer_value = field_id_value->DefaultCastAs(LogicalType::INTEGER); + Value field_id_integer_value = field_id_value->CastAs(context, LogicalType::INTEGER); if (field_id_integer_value.IsNull() || IntegerValue::Get(field_id_integer_value) < 0) { throw BinderException("Invalid field_id %s found in FIELD_IDS: field ids must be non-negative integers", field_id_value->ToString()); @@ -154,7 +154,7 @@ void FieldID::GetFieldIDs(const Value &field_ids_value, ChildFieldIDs &field_ids col_name, LogicalTypeIdToString(col_type.id())); } - GetFieldIDs(*child_field_ids_value, inserted.first->second.child_field_ids, unique_field_ids, + GetFieldIDs(context, *child_field_ids_value, inserted.first->second.child_field_ids, unique_field_ids, GetChildNameToTypeMap(col_type)); } } diff --git a/src/duckdb/extension/parquet/parquet_geometry.cpp b/src/duckdb/extension/parquet/parquet_geometry.cpp index 4c917b6a3..d2ec6ffb9 100644 --- a/src/duckdb/extension/parquet/parquet_geometry.cpp +++ b/src/duckdb/extension/parquet/parquet_geometry.cpp @@ -390,7 +390,7 @@ unique_ptr GeometryColumnReader::Create(const ParquetReader &reade auto func = StGeomfromwkbFun::GetFunction(); func.SetName("ST_GeomFromWKB"); auto read_expr = func.Bind(context, std::move(args)); - auto type_expr = BoundCastExpression::AddDefaultCastToType(std::move(read_expr), schema.type); + auto type_expr = BoundCastExpression::AddCastToType(context, std::move(read_expr), schema.type); vector> expression_children; expression_children.push_back(std::move(string_reader)); return make_uniq(context, std::move(expression_children), std::move(type_expr), schema); diff --git a/src/duckdb/extension/parquet/parquet_metadata.cpp b/src/duckdb/extension/parquet/parquet_metadata.cpp index fc770d65d..9ff7a4afc 100644 --- a/src/duckdb/extension/parquet/parquet_metadata.cpp +++ b/src/duckdb/extension/parquet/parquet_metadata.cpp @@ -490,6 +490,10 @@ void ParquetRowGroupMetadataProcessor::ReadRow(vector> &output idx_t row_group_idx = row_idx / column_schemas.size(); auto &row_group = meta_data->row_groups[row_group_idx]; + if (row_group.columns.size() != column_schemas.size()) { + throw DataCorruptionException("Parquet row group %llu column count mismatch (expected %llu, found %llu)", + row_group_idx, column_schemas.size(), row_group.columns.size()); + } auto &column = row_group.columns[col_idx]; auto &column_schema = column_schemas[col_idx]; @@ -895,7 +899,6 @@ class ParquetBloomProbeProcessor : public ParquetMetadataFileProcessor { optional_idx probe_column_idx; unique_ptr> protocol; - optional_ptr allocator; unique_ptr filter; optional hash_strategy; }; @@ -933,7 +936,6 @@ void ParquetBloomProbeProcessor::InitializeInternal(ClientContext &context, Parq auto transport = duckdb_base_std::make_shared(context, reader.GetHandle(), false); protocol = make_uniq>(std::move(transport)); - allocator = &BufferAllocator::Get(context); auto column_type = reader.GetColumns()[probe_column_idx.GetIndex()].type; filter = ExpressionFilter::CreateComparisonFilter(ExpressionType::COMPARE_EQUAL, probe_constant.CastAs(context, column_type)); @@ -955,8 +957,8 @@ void ParquetBloomProbeProcessor::ReadRow(vector> &output, idx_ auto &column_schema = reader.root_schema->children[probe_column_idx.GetIndex()]; auto bloom_excludes = - hash_strategy && ParquetStatisticsUtils::BloomFilterExcludes(*filter, column.meta_data, *protocol, *allocator, - column_schema, *hash_strategy); + hash_strategy && ParquetStatisticsUtils::BloomFilterExcludes(*filter, column.meta_data, *protocol, + reader.allocator, column_schema, *hash_strategy); output[0].get().Append(Value(reader.file.path)); output[1].get().Append(Value::BIGINT(NumericCast(row_idx))); diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 769c089c3..0d1801dd7 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -79,6 +79,7 @@ #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/storage/buffer_manager.hpp" namespace duckdb { @@ -334,14 +335,15 @@ LoadMetadata(ClientContext &context, Allocator &allocator, CachingFileHandle &fi } ResizeableBuffer buf; - buf.resize(allocator, 8); - buf.zero(); + buf.Resize(allocator, 8); + buf.Zero(); transport.Prefetch(file_size - prefetch_size, prefetch_size); transport.SetLocation(file_size - 8); - transport.read(buf.ptr, 8); + transport.read(buf.GetCurrentLoc(), 8); - ParseParquetFooter(buf.ptr, file_handle.GetPath(), file_size, encryption_config, footer_len, footer_encrypted); + ParseParquetFooter(buf.GetCurrentLoc(), file_handle.GetPath(), file_size, encryption_config, footer_len, + footer_encrypted); auto metadata_pos = file_size - (footer_len + 8); transport.SetLocation(metadata_pos); @@ -1441,8 +1443,8 @@ ParquetReader::ParquetReader(ClientContext &context_p, OpenFileInfo file_p, Parq shared_ptr metadata_p, unordered_map projection_expressions_p) : BaseFileReader(std::move(file_p)), fs(CachingFileSystem::Get(context_p)), - allocator(BufferAllocator::Get(context_p)), parquet_options(std::move(parquet_options_p)), - projection_expressions(std::move(projection_expressions_p)) { + allocator(BufferAllocator::Get(context_p)), buffer_manager(BufferManager::GetBufferManager(context_p)), + parquet_options(std::move(parquet_options_p)), projection_expressions(std::move(projection_expressions_p)) { auto flags = FileFlags::FILE_FLAGS_READ; flags.SetRequestSizing(RequestSizing::BY_READER); file_handle = fs.OpenFile(context_p, file, flags); @@ -1552,7 +1554,8 @@ unique_ptr ParquetUnionData::GetStatistics(ClientContext &contex ParquetReader::ParquetReader(ClientContext &context_p, ParquetOptions parquet_options_p, shared_ptr metadata_p) : BaseFileReader(string()), fs(CachingFileSystem::Get(context_p)), allocator(BufferAllocator::Get(context_p)), - metadata(std::move(metadata_p)), parquet_options(std::move(parquet_options_p)), rows_read(0) { + buffer_manager(BufferManager::GetBufferManager(context_p)), metadata(std::move(metadata_p)), + parquet_options(std::move(parquet_options_p)), rows_read(0) { can_use_metadata_statistics = CanUseParquetMetadataStatistics(context_p, metadata, parquet_options); interval_bloom_filter_version = ParquetStatisticsUtils::GetIntervalBloomFilterVersion(*GetFileMetadata()); InitializeSchema(context_p); @@ -2545,8 +2548,8 @@ void ParquetReader::InitializeScan(ClientContext &context, ParquetReaderScanStat } } - state.define_buf.resize(allocator, STANDARD_VECTOR_SIZE); - state.repeat_buf.resize(allocator, STANDARD_VECTOR_SIZE); + state.define_buf.Resize(allocator, STANDARD_VECTOR_SIZE); + state.repeat_buf.Resize(allocator, STANDARD_VECTOR_SIZE); } shared_ptr ParquetReader::CreateMetadataReader(ClientContext &context, ParquetOptions parquet_options, @@ -3078,11 +3081,11 @@ AsyncResult ParquetReader::Process(ClientContext &context, ParquetReaderScanStat auto &deletion_filter = this->deletion_filter; - state.define_buf.zero(); - state.repeat_buf.zero(); + state.define_buf.Zero(); + state.repeat_buf.Zero(); - auto define_ptr = (uint8_t *)state.define_buf.ptr; - auto repeat_ptr = (uint8_t *)state.repeat_buf.ptr; + auto define_ptr = (uint8_t *)state.define_buf.GetCurrentLoc(); + auto repeat_ptr = (uint8_t *)state.repeat_buf.GetCurrentLoc(); if (filters || deletion_filter) { auto res = ProcessFilters(state, result, scan_count, define_ptr, repeat_ptr, log_prefetch); diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 2b1b15f24..8d5d419b6 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -1248,7 +1248,7 @@ bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filte } auto new_buffer = make_uniq(allocator, bloom_filter_data_size); - transport.read(new_buffer->ptr, UnsafeNumericCast(bloom_filter_data_size)); + transport.read(new_buffer->GetCurrentLoc(), UnsafeNumericCast(bloom_filter_data_size)); ParquetBloomFilter bloom_filter(std::move(new_buffer)); return ApplyBloomFilter(duckdb_filter, bloom_filter, schema, hash_strategy); } @@ -1293,7 +1293,7 @@ static optional_idx BloomFilterSize(idx_t num_entries, double target) { static unique_ptr AllocateBloomFilter(Allocator &allocator, idx_t size) { auto buffer = make_uniq(allocator, size); - buffer->zero(); + buffer->Zero(); return buffer; } @@ -1310,7 +1310,7 @@ unique_ptr ParquetBloomFilter::Create(Allocator &allocator, } unique_ptr ParquetBloomFilter::TryCreate(Allocator &allocator, idx_t num_entries, double target, - shared_ptr memory) { + const shared_ptr &memory) { if (!num_entries) { return nullptr; } @@ -1348,21 +1348,21 @@ void ParquetBloomFilter::ReleaseReservation() { } ParquetBloomFilter::ParquetBloomFilter(unique_ptr data_p) { - D_ASSERT(data_p->len % sizeof(ParquetBloomBlock) == 0); + D_ASSERT(data_p->GetLength() % sizeof(ParquetBloomBlock) == 0); data = std::move(data_p); - block_count = data->len / sizeof(ParquetBloomBlock); - D_ASSERT(data->len % sizeof(ParquetBloomBlock) == 0); + block_count = data->GetLength() / sizeof(ParquetBloomBlock); + D_ASSERT(data->GetLength() % sizeof(ParquetBloomBlock) == 0); } void ParquetBloomFilter::FilterInsert(uint64_t x) { - auto blocks = reinterpret_cast(data->ptr); + auto blocks = reinterpret_cast(data->GetCurrentLoc()); uint64_t i = ((x >> 32) * block_count) >> 32; auto &b = blocks[i]; ParquetBloomBlock::BlockInsert(b, x); } bool ParquetBloomFilter::FilterCheck(uint64_t x) { - auto blocks = reinterpret_cast(data->ptr); + auto blocks = reinterpret_cast(data->GetCurrentLoc()); auto i = ((x >> 32) * block_count) >> 32; return ParquetBloomBlock::BlockCheck(blocks[i], x); } @@ -1377,19 +1377,20 @@ static uint8_t PopCnt64(uint64_t n) { } double ParquetBloomFilter::OneRatio() { - auto bloom_ptr = reinterpret_cast(data->ptr); + auto bloom_ptr = reinterpret_cast(data->GetCurrentLoc()); idx_t one_count = 0; - for (idx_t b_idx = 0; b_idx < data->len / sizeof(uint64_t); ++b_idx) { + for (idx_t b_idx = 0; b_idx < data->GetLength() / sizeof(uint64_t); ++b_idx) { one_count += PopCnt64(bloom_ptr[b_idx]); } - return LossyNumericCast(one_count) / (LossyNumericCast(data->len) * 8.0); + return LossyNumericCast(one_count) / (LossyNumericCast(data->GetLength()) * 8.0); } void ParquetBloomFilter::Shrink(Allocator &allocator, idx_t new_block_count) { D_ASSERT(new_block_count > 0 && block_count % new_block_count == 0); auto folded = AllocateBloomFilter(allocator, new_block_count * sizeof(ParquetBloomBlock)); - array_ptr source(reinterpret_cast(data->ptr), block_count); - array_ptr target(reinterpret_cast(folded->ptr), new_block_count); + array_ptr source(reinterpret_cast(data->GetCurrentLoc()), block_count); + array_ptr target(reinterpret_cast(folded->GetCurrentLoc()), + new_block_count); const auto factor = block_count / new_block_count; for (idx_t i = 0; i < new_block_count; i++) { auto &merged = target[i]; @@ -1418,8 +1419,8 @@ void ParquetBloomFilter::FoldToTarget(Allocator &allocator, double target) { Shrink(allocator, new_block_count); } if (memory) { - memory->Release(reserved_bytes - data->len); - reserved_bytes = data->len; + memory->Release(reserved_bytes - data->GetLength()); + reserved_bytes = data->GetLength(); } } diff --git a/src/duckdb/extension/parquet/parquet_writer.cpp b/src/duckdb/extension/parquet/parquet_writer.cpp index 0533e108d..23e2a9623 100644 --- a/src/duckdb/extension/parquet/parquet_writer.cpp +++ b/src/duckdb/extension/parquet/parquet_writer.cpp @@ -118,11 +118,11 @@ class ParquetBloomFilterWriteBuffer : public AsyncWriteBuffer { } data_ptr_t Ptr() override { - return bloom_filter->Get()->ptr; + return bloom_filter->Get()->GetCurrentLoc(); } idx_t Size() const override { - return bloom_filter->Get()->len; + return bloom_filter->Get()->GetLength(); } private: @@ -1485,7 +1485,7 @@ void ParquetWriter::FlushBloomFilters() { D_ASSERT(!options.encryption_config); // write nonsense bloom filter header duckdb_parquet::BloomFilterHeader filter_header; - const auto bloom_filter_size = bloom_filter_entry.bloom_filter->Get()->len; + const auto bloom_filter_size = bloom_filter_entry.bloom_filter->Get()->GetLength(); filter_header.numBytes = NumericCast(bloom_filter_size); filter_header.algorithm.__set_BLOCK(duckdb_parquet::SplitBlockAlgorithm()); filter_header.compression.__set_UNCOMPRESSED(duckdb_parquet::Uncompressed()); diff --git a/src/duckdb/extension/parquet/read_single_parquet_file.cpp b/src/duckdb/extension/parquet/read_single_parquet_file.cpp index eb8d29273..b78bece80 100644 --- a/src/duckdb/extension/parquet/read_single_parquet_file.cpp +++ b/src/duckdb/extension/parquet/read_single_parquet_file.cpp @@ -115,14 +115,14 @@ static unique_ptr ReadSingleParquetFileBind(ClientContext &context result->file = TableFunctionFileBindInput::GetFile(input); // the named parameters of this function are those of the multi-file parquet reader - ParquetMultiFileInfo interface; + ParquetMultiFileInfo file_info; MultiFileOptions file_options; if (file_input.multi_file_options) { file_options = *file_input.multi_file_options; } ParquetFileReaderOptions options(context); for (auto &kv : input.named_parameters) { - interface.ParseOption(context, kv.first, kv.second, file_options, options); + file_info.ParseOption(context, kv.first, kv.second, file_options, options); } result->options = std::move(options.options); @@ -432,9 +432,13 @@ static vector ReadSingleParquetFileRowIdColumns(ClientContext &context } //! The statistics of a column of this file, read from its metadata -static unique_ptr -ReadSingleParquetFileStatistics(ClientContext &context, const FunctionData *bind_data_p, column_t column_index) { - auto &parquet_data = bind_data_p->Cast(); +static unique_ptr ReadSingleParquetFileStatistics(ClientContext &context, + TableFunctionGetStatisticsInput &input) { + auto &parquet_data = input.bind_data->Cast(); + if (!input.column_index.HasPrimaryIndex() || input.column_index.HasChildren()) { + return nullptr; + } + const auto column_index = input.column_index.GetPrimaryIndex(); if (IsVirtualColumn(column_index)) { return ParquetReader::ReadVirtualColumnStatistics(context, parquet_data.options, parquet_data.metadata, column_index); @@ -566,7 +570,7 @@ TableFunction ParquetScanFunction::GetSingleFileFunction() { ReadSingleParquetFileInitGlobal, ReadSingleParquetFileInitLocal); read_parquet.table_scan_progress = ReadSingleParquetFileProgress; read_parquet.cardinality = ReadSingleParquetFileCardinality; - read_parquet.statistics = ReadSingleParquetFileStatistics; + read_parquet.statistics_extended = ReadSingleParquetFileStatistics; read_parquet.get_virtual_columns = ReadSingleParquetFileVirtualColumns; read_parquet.get_partition_stats = ReadSingleParquetFilePartitionStats; read_parquet.get_metrics = ReadSingleParquetFileGetMetrics; diff --git a/src/duckdb/extension/parquet/reader/list_column_reader.cpp b/src/duckdb/extension/parquet/reader/list_column_reader.cpp index 36f13e837..3779826fe 100644 --- a/src/duckdb/extension/parquet/reader/list_column_reader.cpp +++ b/src/duckdb/extension/parquet/reader/list_column_reader.cpp @@ -105,8 +105,8 @@ idx_t ListColumnReader::ReadInternal(ColumnReaderInput &input, optional_ptr child_column_reader_p) : ColumnReader(reader, schema), child_column_reader(std::move(child_column_reader_p)), read_cache(reader.allocator, ListType::GetChildType(Type())), read_vector(read_cache), overflow_child_count(0) { - child_defines.resize(reader.allocator, STANDARD_VECTOR_SIZE); - child_repeats.resize(reader.allocator, STANDARD_VECTOR_SIZE); - child_defines_ptr = (uint8_t *)child_defines.ptr; - child_repeats_ptr = (uint8_t *)child_repeats.ptr; + child_defines.Resize(reader.allocator, STANDARD_VECTOR_SIZE); + child_repeats.Resize(reader.allocator, STANDARD_VECTOR_SIZE); + child_defines_ptr = (uint8_t *)child_defines.GetCurrentLoc(); + child_repeats_ptr = (uint8_t *)child_repeats.GetCurrentLoc(); if (child_column_reader) { child_column_reader->SetParent(*this); } diff --git a/src/duckdb/extension/parquet/reader/string_column_reader.cpp b/src/duckdb/extension/parquet/reader/string_column_reader.cpp index 33f3d727b..53ee3431f 100644 --- a/src/duckdb/extension/parquet/reader/string_column_reader.cpp +++ b/src/duckdb/extension/parquet/reader/string_column_reader.cpp @@ -113,20 +113,28 @@ string_t StringColumnReader::VerifyString(const char *str_data, uint32_t str_len class ParquetStringVectorBuffer : public AuxiliaryDataHolder { public: - explicit ParquetStringVectorBuffer(shared_ptr buffer_p) : buffer(std::move(buffer_p)) { + explicit ParquetStringVectorBuffer(shared_ptr buffer_p, BufferHandle handle_p) + : buffer(std::move(buffer_p)), handle(std::move(handle_p)) { } private: shared_ptr buffer; + BufferHandle handle; }; -void StringColumnReader::ReferenceBlock(Vector &result, shared_ptr &block) { - StringVector::AddAuxiliaryData(result, make_uniq(block)); +void StringColumnReader::ReferenceBlock(Vector &result, shared_ptr &block, + BufferManager &buffer_manager) { + auto &block_handle = block->GetBlockHandle(); + BufferHandle buffer_handle; + if (block_handle) { + buffer_handle = buffer_manager.Pin(block_handle); + } + StringVector::AddAuxiliaryData(result, make_uniq(block, std::move(buffer_handle))); } void StringColumnReader::Plain(shared_ptr &plain_data, uint8_t *defines, idx_t num_values, idx_t result_offset, Vector &result) { - ReferenceBlock(result, plain_data); + ReferenceBlock(result, plain_data, GetBufferManager()); current_plain_result = &result; PlainTemplated(*plain_data, defines, num_values, result_offset, result); current_plain_result = nullptr; @@ -134,7 +142,7 @@ void StringColumnReader::Plain(shared_ptr &plain_data, uint8_t void StringColumnReader::PlainSelect(shared_ptr &plain_data, uint8_t *defines, idx_t num_values, Vector &result, const SelectionVector &sel, idx_t count) { - ReferenceBlock(result, plain_data); + ReferenceBlock(result, plain_data, GetBufferManager()); current_plain_result = &result; PlainSelectTemplated(*plain_data, defines, num_values, result, sel, count); current_plain_result = nullptr; diff --git a/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp b/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp index 72148fd64..7a10a0c45 100644 --- a/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp +++ b/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp @@ -435,13 +435,13 @@ void PrimitiveColumnWriter::SetParquetStatistics(PrimitiveColumnWriterState &sta // this code is not going to win any beauty contests, but well auto min = state.stats_state->GetMin(); if (!min.empty()) { - column_chunk.meta_data.statistics.min = std::move(min); + column_chunk.meta_data.statistics.min = min; column_chunk.meta_data.statistics.__isset.min = true; column_chunk.meta_data.__isset.statistics = true; } auto max = state.stats_state->GetMax(); if (!max.empty()) { - column_chunk.meta_data.statistics.max = std::move(max); + column_chunk.meta_data.statistics.max = max; column_chunk.meta_data.statistics.__isset.max = true; column_chunk.meta_data.__isset.statistics = true; } @@ -561,7 +561,7 @@ void PrimitiveColumnWriter::FinalizeWrite(ColumnWriterState &state_p) { writer.BufferPageIndex(state.col_idx, std::move(page_index)); } if (state.bloom_filter && !HasDictionary(state) && - state.bloom_filter->Get()->len * MIN_COMPRESSED_TO_FILTER_RATIO > + state.bloom_filter->Get()->GetLength() * MIN_COMPRESSED_TO_FILTER_RATIO > NumericCast(column_chunk.meta_data.total_compressed_size)) { state.bloom_filter.reset(); } diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index b363415c0..dfbb229df 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-alpha54418"; + descriptor->api_version = "v2.1.0-alpha55910"; 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-alpha54418"; + descriptor->api_version = "v2.1.0-alpha55910"; 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-alpha54418"; + descriptor->api_version = "v2.1.0-alpha55910"; 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-alpha54418"; + descriptor->api_version = "v2.1.0-alpha55910"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry.cpp index d54d28510..b835d5af4 100644 --- a/src/duckdb/src/catalog/catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry.cpp @@ -116,6 +116,10 @@ void CatalogEntry::Verify(Catalog &catalog_p) { void CatalogEntry::Rollback(CatalogEntry &prev_entry) { } +bool CatalogEntry::InvalidatesDependents(const CatalogEntry &previous) const { + return false; +} + void CatalogEntry::OnDrop() { } diff --git a/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp index 6deaabcd1..e3106ced3 100644 --- a/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp @@ -2,6 +2,10 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/table_macro_catalog_entry.hpp" #include "duckdb/function/scalar_macro_function.hpp" +#include "duckdb/parser/parsed_data/alter_macro_info.hpp" +#include "duckdb/storage/storage_manager.hpp" +#include "duckdb/main/attached_database.hpp" +#include "duckdb/common/storage_compatibility.hpp" namespace duckdb { @@ -61,10 +65,74 @@ unique_ptr MacroCatalogEntry::GetInfo() const { return std::move(info); } +optional_idx MacroCatalogEntry::FindMember(const vector &signature) const { + // the signature names a declared overload exactly: a type matches an equal declared type and + // ANY matches an untyped slot, which the create-time conflict rules keep unique + for (idx_t i = 0; i < macros.size(); i++) { + if (macros[i]->MatchesSignature(signature)) { + return i; + } + } + return optional_idx(); +} + string MacroCatalogEntry::ToSQL() const { auto create_info = GetInfo(); create_info->StripCatalogQualification(); return create_info->ToString(); } +bool MacroCatalogEntry::InvalidatesDependents(const CatalogEntry &previous) const { + return previous.type == type && previous.Cast().macros.size() > macros.size(); +} + +unique_ptr MacroCatalogEntry::AlterEntry(CatalogTransaction transaction, AlterInfo &info) { + if (info.type != AlterType::ALTER_MACRO) { + return CatalogEntry::AlterEntry(transaction, info); + } + auto ¯o_info = info.Cast(); + if (macro_info.alter_macro_type != AlterMacroType::REMOVE_OVERLOAD) { + throw InternalException("Unsupported ALTER MACRO type"); + } + auto &remove_info = macro_info.Cast(); + // releases before v2.1.0 do not know the ALTER_MACRO WAL record, like the RETURNS declarations + auto &attached = ParentCatalog().GetAttached(); + if (!temporary && attached.HasStorageManager() && !attached.IsTemporary()) { + auto &storage_manager = attached.GetStorageManager(); + const auto since = StorageCompatibility::FromString("v2.1.0").storage_version; + if (!storage_manager.InMemory() && storage_manager.GetStorageVersion() < since) { + string msg = "Dropping a single overload is only supported for storage versions v2.1.0 and higher.\n"; + msg += "Use an in-memory database, ATTACH with (STORAGE_VERSION v2.1.0), or a TEMP macro"; + throw CatalogException(msg); + } + } + auto member_idx = FindMember(remove_info.signature); + if (!member_idx.IsValid()) { + if (remove_info.if_not_found == OnEntryNotFound::RETURN_NULL) { + // IF EXISTS at member granularity: nothing to drop, siblings are unaffected + return nullptr; + } + string signature_text; + for (auto &sig_type : remove_info.signature) { + if (!signature_text.empty()) { + signature_text += ", "; + } + signature_text += sig_type.ToString(); + } + throw CatalogException("Function %s has no overload with signature (%s)", name, signature_text); + } + if (macros.size() == 1) { + // an alter keeps the entry, like ALTER TABLE DROP COLUMN cannot drop the last column + throw CatalogException("Cannot drop the last overload of %s: drop the macro itself instead", name); + } + auto new_info_base = GetInfo(); + auto &new_info = new_info_base->Cast(); + new_info.macros.erase(new_info.macros.begin() + NumericCast(member_idx.GetIndex())); + new_info.temporary = temporary; + // the entry keeps its registered dependencies: AlterObject carries them over when the alter brings no new list + auto function = MacroCatalogEntry::Create(ParentCatalog(), schema, new_info); + function->internal = internal; + return std::move(function); +} + } // namespace duckdb diff --git a/src/duckdb/src/catalog/catalog_set.cpp b/src/duckdb/src/catalog/catalog_set.cpp index 1a039ba26..1e7757323 100644 --- a/src/duckdb/src/catalog/catalog_set.cpp +++ b/src/duckdb/src/catalog/catalog_set.cpp @@ -464,7 +464,8 @@ bool CatalogSet::DropEntry(ClientContext &context, const Identifier &name, bool } //! Verify that the object referenced by the dependency still exists when we commit the dependency -void CatalogSet::VerifyExistenceOfDependency(transaction_t commit_id, CatalogEntry &entry) { +void CatalogSet::VerifyExistenceOfDependency(transaction_t commit_id, VisibilityBound visibility_bound, + CatalogEntry &entry) { auto &duck_catalog = GetCatalog(); // Make sure that we don't see any uncommitted changes @@ -473,18 +474,19 @@ void CatalogSet::VerifyExistenceOfDependency(transaction_t commit_id, CatalogEnt // This will allow us to see all committed changes made before this COMMIT happened CatalogTransaction commit_transaction(duck_catalog.GetDatabase(), transaction_id, VisibilityBound::Through(commit_id)); + // Earlier writes in this transaction have already received their commit timestamp. + CatalogTransaction snapshot_transaction(duck_catalog.GetDatabase(), commit_id, visibility_bound); D_ASSERT(entry.type == CatalogType::DEPENDENCY_ENTRY); auto &dep = entry.Cast(); - duck_catalog.GetDependencyManager()->VerifyExistence(commit_transaction, dep); + duck_catalog.GetDependencyManager()->VerifyExistence(commit_transaction, snapshot_transaction, dep); } //! Verify that no dependencies creations were committed since our transaction started, that reference the entry we're //! dropping -void CatalogSet::CommitDrop(transaction_t commit_id, VisibilityBound visibility_bound, CatalogEntry &entry) { +void CatalogSet::VerifyCommitDrop(transaction_t commit_id, VisibilityBound visibility_bound, CatalogEntry &entry) { auto &duck_catalog = GetCatalog(); - entry.OnDrop(); // Make sure that we don't see any uncommitted changes auto transaction_id = MAX_TRANSACTION_ID; D_ASSERT(IsCommitted(commit_id)); @@ -495,6 +497,11 @@ void CatalogSet::CommitDrop(transaction_t commit_id, VisibilityBound visibility_ duck_catalog.GetDependencyManager()->VerifyCommitDrop(commit_transaction, visibility_bound, entry); } +void CatalogSet::CommitDrop(transaction_t commit_id, VisibilityBound visibility_bound, CatalogEntry &entry) { + entry.OnDrop(); + VerifyCommitDrop(commit_id, visibility_bound, entry); +} + DuckCatalog &CatalogSet::GetCatalog() { return catalog; } diff --git a/src/duckdb/src/catalog/dependency_manager.cpp b/src/duckdb/src/catalog/dependency_manager.cpp index 9749f9172..829bcbc93 100644 --- a/src/duckdb/src/catalog/dependency_manager.cpp +++ b/src/duckdb/src/catalog/dependency_manager.cpp @@ -537,7 +537,8 @@ string DependencyManager::CollectDependents(CatalogTransaction transaction, cata return result; } -void DependencyManager::VerifyExistence(CatalogTransaction transaction, DependencyEntry &object) { +void DependencyManager::VerifyExistence(CatalogTransaction transaction, CatalogTransaction snapshot_transaction, + DependencyEntry &object) { auto &subject = object.Subject(); CatalogEntryInfo info; @@ -574,6 +575,17 @@ void DependencyManager::VerifyExistence(CatalogTransaction transaction, Dependen "Could not commit creation of dependency, subject %s was dropped and re-created by another transaction", object.EntryInfo().name); } + // An alter preserves the oid. If the subject changed after this transaction's snapshot, the entry decides + // whether the change breaks what the dependent was bound against. + if (!subject.flags.IsOwnership() && lookup_result.result && + lookup_result.result->timestamp >= snapshot_transaction.view.visibility_bound) { + auto bound_entry = LookupEntry(snapshot_transaction, info); + if (bound_entry && lookup_result.result->InvalidatesDependents(*bound_entry)) { + throw DependencyException("Could not commit creation of dependency, subject %s was altered incompatibly " + "by another transaction", + object.EntryInfo().name); + } + } } void DependencyManager::VerifyCommitDrop(CatalogTransaction transaction, VisibilityBound visibility_bound, diff --git a/src/duckdb/src/common/adbc/adbc.cpp b/src/duckdb/src/common/adbc/adbc.cpp index 8e9d6abb6..643918a6b 100644 --- a/src/duckdb/src/common/adbc/adbc.cpp +++ b/src/duckdb/src/common/adbc/adbc.cpp @@ -17,6 +17,7 @@ #include "duckdb/main/client_context.hpp" #include "duckdb/main/connection.hpp" #include "duckdb/main/valid_checker.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/common/adbc/options.h" #include "duckdb/common/adbc/single_batch_array_stream.hpp" #include "duckdb/function/table/arrow.hpp" @@ -1556,8 +1557,10 @@ AdbcStatusCode ConnectionInit(struct AdbcConnection *connection, struct AdbcData // Track query progress for ADBC without printing a progress bar. auto &client_config = duckdb::ClientConfig::GetConfig(*conn->context); if (!client_config.system_progress_bar_disable_reason) { - client_config.enable_progress_bar = true; - client_config.print_progress_bar = false; + duckdb::Settings::Set(*conn->context, duckdb::SetScope::SESSION, + duckdb::Value::BOOLEAN(true)); + duckdb::Settings::Set(*conn->context, duckdb::SetScope::SESSION, + duckdb::Value::BOOLEAN(false)); } // We might have options to set return InternalSetOption(*conn_wrapper, error); diff --git a/src/duckdb/src/common/bignum.cpp b/src/duckdb/src/common/bignum.cpp index 3471024a5..db441855b 100644 --- a/src/duckdb/src/common/bignum.cpp +++ b/src/duckdb/src/common/bignum.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/bignum.hpp" #include "duckdb/common/bignum_limbs.hpp" #include "duckdb/common/types/bignum.hpp" @@ -495,13 +496,10 @@ constexpr bignum_twodigit_t DIGIT_MASK = BASE - 1; constexpr idx_t INTERRUPT_CHECK_INTERVAL = idx_t(1) << 20; void AccountWork(BignumArithmeticState &state, idx_t work) { - if (!state.context) { - return; - } state.work_since_interrupt_check += work; if (state.work_since_interrupt_check >= INTERRUPT_CHECK_INTERVAL) { state.work_since_interrupt_check = 0; - state.context->InterruptCheck(); + state.context.InterruptCheck(); } } diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 6a4e389ee..41a812a93 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -74,7 +74,6 @@ #include "duckdb/common/enums/result_lifetime.hpp" #include "duckdb/common/enums/result_ordering.hpp" #include "duckdb/common/enums/row_group_append_mode.hpp" -#include "duckdb/common/enums/row_id_handling.hpp" #include "duckdb/common/enums/set_operation_type.hpp" #include "duckdb/common/enums/set_scope.hpp" #include "duckdb/common/enums/set_type.hpp" @@ -158,7 +157,7 @@ #include "duckdb/function/table_function.hpp" #include "duckdb/function/window/match_recognize_matcher.hpp" #include "duckdb/function/window/window_merge_sort_tree.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/logging/logging.hpp" #include "duckdb/main/appender.hpp" #include "duckdb/main/attached_database.hpp" @@ -199,6 +198,7 @@ #include "duckdb/parser/literal.hpp" #include "duckdb/parser/parsed_data/alter_database_info.hpp" #include "duckdb/parser/parsed_data/alter_info.hpp" +#include "duckdb/parser/parsed_data/alter_macro_info.hpp" #include "duckdb/parser/parsed_data/alter_scalar_function_info.hpp" #include "duckdb/parser/parsed_data/alter_schema_info.hpp" #include "duckdb/parser/parsed_data/alter_table_function_info.hpp" @@ -233,6 +233,7 @@ #include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/logical_operator_repeatability.hpp" #include "duckdb/planner/logical_plan_verification_result.hpp" +#include "duckdb/planner/planner.hpp" #include "duckdb/planner/table_filter.hpp" #include "duckdb/storage/buffer/block_handle.hpp" #include "duckdb/storage/buffer/buffer_pool_reservation.hpp" @@ -586,6 +587,24 @@ AlterForeignKeyType EnumUtil::FromString(const char *value) return static_cast(StringUtil::StringToEnum(GetAlterForeignKeyTypeValues(), 2, "AlterForeignKeyType", value)); } +const StringUtil::EnumStringLiteral *GetAlterMacroTypeValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(AlterMacroType::INVALID), "INVALID" }, + { static_cast(AlterMacroType::REMOVE_OVERLOAD), "REMOVE_OVERLOAD" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(AlterMacroType value) { + return StringUtil::EnumToString(GetAlterMacroTypeValues(), 2, "AlterMacroType", static_cast(value)); +} + +template<> +AlterMacroType EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetAlterMacroTypeValues(), 2, "AlterMacroType", value)); +} + const StringUtil::EnumStringLiteral *GetAlterScalarFunctionTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(AlterScalarFunctionType::INVALID), "INVALID" }, @@ -688,19 +707,20 @@ const StringUtil::EnumStringLiteral *GetAlterTypeValues() { { static_cast(AlterType::SET_COMMENT), "SET_COMMENT" }, { static_cast(AlterType::SET_COLUMN_COMMENT), "SET_COLUMN_COMMENT" }, { static_cast(AlterType::ALTER_DATABASE), "ALTER_DATABASE" }, - { static_cast(AlterType::ALTER_SCHEMA), "ALTER_SCHEMA" } + { static_cast(AlterType::ALTER_SCHEMA), "ALTER_SCHEMA" }, + { static_cast(AlterType::ALTER_MACRO), "ALTER_MACRO" } }; return values; } template<> const char* EnumUtil::ToChars(AlterType value) { - return StringUtil::EnumToString(GetAlterTypeValues(), 11, "AlterType", static_cast(value)); + return StringUtil::EnumToString(GetAlterTypeValues(), 12, "AlterType", static_cast(value)); } template<> AlterType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetAlterTypeValues(), 11, "AlterType", value)); + return static_cast(StringUtil::StringToEnum(GetAlterTypeValues(), 12, "AlterType", value)); } const StringUtil::EnumStringLiteral *GetAlterViewTypeValues() { @@ -2538,21 +2558,22 @@ ExtensionLoadResult EnumUtil::FromString(const char *value) const StringUtil::EnumStringLiteral *GetExtensionRepositoryAccessValues() { static constexpr StringUtil::EnumStringLiteral values[] { - { static_cast(ExtensionRepositoryAccess::UNDECIDED), "UNDECIDED" }, + { static_cast(ExtensionRepositoryAccess::HOSTS), "HOSTS" }, { static_cast(ExtensionRepositoryAccess::ALLOWED), "ALLOWED" }, - { static_cast(ExtensionRepositoryAccess::FORBIDDEN), "FORBIDDEN" } + { static_cast(ExtensionRepositoryAccess::FORBIDDEN), "FORBIDDEN" }, + { static_cast(ExtensionRepositoryAccess::HOSTS_ONLY), "HOSTS_ONLY" } }; return values; } template<> const char* EnumUtil::ToChars(ExtensionRepositoryAccess value) { - return StringUtil::EnumToString(GetExtensionRepositoryAccessValues(), 3, "ExtensionRepositoryAccess", static_cast(value)); + return StringUtil::EnumToString(GetExtensionRepositoryAccessValues(), 4, "ExtensionRepositoryAccess", static_cast(value)); } template<> ExtensionRepositoryAccess EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetExtensionRepositoryAccessValues(), 3, "ExtensionRepositoryAccess", value)); + return static_cast(StringUtil::StringToEnum(GetExtensionRepositoryAccessValues(), 4, "ExtensionRepositoryAccess", value)); } const StringUtil::EnumStringLiteral *GetExtensionRepositoryTypeValues() { @@ -3832,7 +3853,6 @@ const StringUtil::EnumStringLiteral *GetLogicalOperatorTypeValues() { { static_cast(LogicalOperatorType::LOGICAL_CREATE_TRIGGER), "LOGICAL_CREATE_TRIGGER" }, { static_cast(LogicalOperatorType::LOGICAL_EXPLAIN), "LOGICAL_EXPLAIN" }, { static_cast(LogicalOperatorType::LOGICAL_PREPARE), "LOGICAL_PREPARE" }, - { static_cast(LogicalOperatorType::LOGICAL_EXECUTE), "LOGICAL_EXECUTE" }, { static_cast(LogicalOperatorType::LOGICAL_EXPORT), "LOGICAL_EXPORT" }, { static_cast(LogicalOperatorType::LOGICAL_VACUUM), "LOGICAL_VACUUM" }, { static_cast(LogicalOperatorType::LOGICAL_SET), "LOGICAL_SET" }, @@ -3850,12 +3870,12 @@ const StringUtil::EnumStringLiteral *GetLogicalOperatorTypeValues() { template<> const char* EnumUtil::ToChars(LogicalOperatorType value) { - return StringUtil::EnumToString(GetLogicalOperatorTypeValues(), 68, "LogicalOperatorType", static_cast(value)); + return StringUtil::EnumToString(GetLogicalOperatorTypeValues(), 67, "LogicalOperatorType", static_cast(value)); } template<> LogicalOperatorType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetLogicalOperatorTypeValues(), 68, "LogicalOperatorType", value)); + return static_cast(StringUtil::StringToEnum(GetLogicalOperatorTypeValues(), 67, "LogicalOperatorType", value)); } const StringUtil::EnumStringLiteral *GetLogicalPlanVerificationIssueCodeValues() { @@ -4647,19 +4667,20 @@ const StringUtil::EnumStringLiteral *GetOptimizerTypeValues() { { static_cast(OptimizerType::REDUNDANT_ORDER), "REDUNDANT_ORDER" }, { 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::SCALAR_AGGREGATE_MERGE), "SCALAR_AGGREGATE_MERGE" }, + { static_cast(OptimizerType::DUPLICATE_ELIMINATED_DOMAIN), "DUPLICATE_ELIMINATED_DOMAIN" } }; return values; } template<> const char* EnumUtil::ToChars(OptimizerType value) { - return StringUtil::EnumToString(GetOptimizerTypeValues(), 52, "OptimizerType", static_cast(value)); + return StringUtil::EnumToString(GetOptimizerTypeValues(), 53, "OptimizerType", static_cast(value)); } template<> OptimizerType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 52, "OptimizerType", value)); + return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 53, "OptimizerType", value)); } const StringUtil::EnumStringLiteral *GetOrderByColumnTypeValues() { @@ -5052,7 +5073,6 @@ const StringUtil::EnumStringLiteral *GetPhysicalOperatorTypeValues() { { static_cast(PhysicalOperatorType::EXPLAIN), "EXPLAIN" }, { static_cast(PhysicalOperatorType::EXPLAIN_ANALYZE), "EXPLAIN_ANALYZE" }, { static_cast(PhysicalOperatorType::EMPTY_RESULT), "EMPTY_RESULT" }, - { static_cast(PhysicalOperatorType::EXECUTE), "EXECUTE" }, { static_cast(PhysicalOperatorType::PREPARE), "PREPARE" }, { static_cast(PhysicalOperatorType::VACUUM), "VACUUM" }, { static_cast(PhysicalOperatorType::EXPORT), "EXPORT" }, @@ -5078,12 +5098,12 @@ const StringUtil::EnumStringLiteral *GetPhysicalOperatorTypeValues() { template<> const char* EnumUtil::ToChars(PhysicalOperatorType value) { - return StringUtil::EnumToString(GetPhysicalOperatorTypeValues(), 90, "PhysicalOperatorType", static_cast(value)); + return StringUtil::EnumToString(GetPhysicalOperatorTypeValues(), 89, "PhysicalOperatorType", static_cast(value)); } template<> PhysicalOperatorType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetPhysicalOperatorTypeValues(), 90, "PhysicalOperatorType", value)); + return static_cast(StringUtil::StringToEnum(GetPhysicalOperatorTypeValues(), 89, "PhysicalOperatorType", value)); } const StringUtil::EnumStringLiteral *GetPhysicalTableScanExecutionStrategyValues() { @@ -5275,6 +5295,24 @@ PipelineScheduleStageType EnumUtil::FromString(const return static_cast(StringUtil::StringToEnum(GetPipelineScheduleStageTypeValues(), 5, "PipelineScheduleStageType", value)); } +const StringUtil::EnumStringLiteral *GetPlanningModeValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(PlanningMode::FULL), "FULL" }, + { static_cast(PlanningMode::BIND_ONLY), "BIND_ONLY" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(PlanningMode value) { + return StringUtil::EnumToString(GetPlanningModeValues(), 2, "PlanningMode", static_cast(value)); +} + +template<> +PlanningMode EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetPlanningModeValues(), 2, "PlanningMode", value)); +} + const StringUtil::EnumStringLiteral *GetPragmaTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(PragmaType::PRAGMA_STATEMENT), "PRAGMA_STATEMENT" }, @@ -5911,25 +5949,6 @@ RowGroupAppendMode EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetRowGroupAppendModeValues(), 3, "RowGroupAppendMode", value)); } -const StringUtil::EnumStringLiteral *GetRowIdHandlingValues() { - static constexpr StringUtil::EnumStringLiteral values[] { - { static_cast(RowIdHandling::ASSUME_UNIQUE), "ASSUME_UNIQUE" }, - { static_cast(RowIdHandling::KEEP_FIRST), "KEEP_FIRST" }, - { static_cast(RowIdHandling::ERROR), "ERROR" } - }; - return values; -} - -template<> -const char* EnumUtil::ToChars(RowIdHandling value) { - return StringUtil::EnumToString(GetRowIdHandlingValues(), 3, "RowIdHandling", static_cast(value)); -} - -template<> -RowIdHandling EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetRowIdHandlingValues(), 3, "RowIdHandling", value)); -} - const StringUtil::EnumStringLiteral *GetSampleMethodValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(SampleMethod::SYSTEM_SAMPLE), "System" }, diff --git a/src/duckdb/src/common/enums/date_part_specifier.cpp b/src/duckdb/src/common/enums/date_part_specifier.cpp index 032a82165..0f3a1a226 100644 --- a/src/duckdb/src/common/enums/date_part_specifier.cpp +++ b/src/duckdb/src/common/enums/date_part_specifier.cpp @@ -1,76 +1,185 @@ #include "duckdb/common/enums/date_part_specifier.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/exception/conversion_exception.hpp" +#include "duckdb/common/types/string_type.hpp" namespace duckdb { -bool TryGetDatePartSpecifier(const string &specifier_p, DatePartSpecifier &result) { - auto specifier = StringUtil::Lower(specifier_p); - if (specifier == "year" || specifier == "yr" || specifier == "y" || specifier == "years" || specifier == "yrs") { - result = DatePartSpecifier::YEAR; - } else if (specifier == "month" || specifier == "mon" || specifier == "months" || specifier == "mons") { - result = DatePartSpecifier::MONTH; - } else if (specifier == "day" || specifier == "days" || specifier == "d" || specifier == "dayofmonth") { - result = DatePartSpecifier::DAY; - } else if (specifier == "decade" || specifier == "dec" || specifier == "decades" || specifier == "decs") { - result = DatePartSpecifier::DECADE; - } else if (specifier == "century" || specifier == "cent" || specifier == "centuries" || specifier == "c") { - result = DatePartSpecifier::CENTURY; - } else if (specifier == "millennium" || specifier == "mil" || specifier == "millenniums" || - specifier == "millennia" || specifier == "mils" || specifier == "millenium") { - result = DatePartSpecifier::MILLENNIUM; - } else if (specifier == "microseconds" || specifier == "microsecond" || specifier == "us" || specifier == "usec" || - specifier == "usecs" || specifier == "usecond" || specifier == "useconds") { - result = DatePartSpecifier::MICROSECONDS; - } else if (specifier == "milliseconds" || specifier == "millisecond" || specifier == "ms" || specifier == "msec" || - specifier == "msecs" || specifier == "msecond" || specifier == "mseconds") { - result = DatePartSpecifier::MILLISECONDS; - } else if (specifier == "second" || specifier == "sec" || specifier == "seconds" || specifier == "secs" || - specifier == "s") { - result = DatePartSpecifier::SECOND; - } else if (specifier == "minute" || specifier == "min" || specifier == "minutes" || specifier == "mins" || - specifier == "m") { - result = DatePartSpecifier::MINUTE; - } else if (specifier == "hour" || specifier == "hr" || specifier == "hours" || specifier == "hrs" || - specifier == "h") { - result = DatePartSpecifier::HOUR; - } else if (specifier == "epoch") { - // seconds since 1970-01-01 - result = DatePartSpecifier::EPOCH; - } else if (specifier == "dow" || specifier == "dayofweek" || specifier == "weekday") { - // day of the week (Sunday = 0, Saturday = 6) - result = DatePartSpecifier::DOW; - } else if (specifier == "isodow") { - // isodow (Monday = 1, Sunday = 7) - result = DatePartSpecifier::ISODOW; - } else if (specifier == "week" || specifier == "weeks" || specifier == "w" || specifier == "weekofyear") { - // ISO week number - result = DatePartSpecifier::WEEK; - } else if (specifier == "doy" || specifier == "dayofyear") { - // day of the year (1-365/366) - result = DatePartSpecifier::DOY; - } else if (specifier == "quarter" || specifier == "quarters") { - // quarter of the year (1-4) - result = DatePartSpecifier::QUARTER; - } else if (specifier == "yearweek") { - // Combined isoyear and isoweek YYYYWW - result = DatePartSpecifier::YEARWEEK; - } else if (specifier == "isoyear") { - // ISO year (first week of the year may be in previous year) - result = DatePartSpecifier::ISOYEAR; - } else if (specifier == "era") { - result = DatePartSpecifier::ERA; - } else if (specifier == "timezone") { - result = DatePartSpecifier::TIMEZONE; - } else if (specifier == "timezone_hour") { - result = DatePartSpecifier::TIMEZONE_HOUR; - } else if (specifier == "timezone_minute") { - result = DatePartSpecifier::TIMEZONE_MINUTE; - } else if (specifier == "julian" || specifier == "jd") { - result = DatePartSpecifier::JULIAN_DAY; - } else { +namespace { + +struct DatePartEntry { + const char *name; + DatePartSpecifier value; +}; + +static constexpr uint8_t DATE_PART_ASSO_VALUES[256] = { + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 8, 101, 1, 5, 0, 101, 101, 30, 5, 27, 27, 22, 21, + 25, 26, 11, 12, 16, 0, 45, 39, 101, 64, 101, 2, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101}; + +static constexpr DatePartEntry DATE_PART_ENTRIES[101] = {{nullptr, DatePartSpecifier::INVALID}, + {"s", DatePartSpecifier::SECOND}, + {"c", DatePartSpecifier::CENTURY}, + {"y", DatePartSpecifier::YEAR}, + {"sec", DatePartSpecifier::SECOND}, + {"secs", DatePartSpecifier::SECOND}, + {"d", DatePartSpecifier::DAY}, + {"second", DatePartSpecifier::SECOND}, + {"seconds", DatePartSpecifier::SECOND}, + {"dec", DatePartSpecifier::DECADE}, + {"decs", DatePartSpecifier::DECADE}, + {nullptr, DatePartSpecifier::INVALID}, + {"decade", DatePartSpecifier::DECADE}, + {"decades", DatePartSpecifier::DECADE}, + {"year", DatePartSpecifier::YEAR}, + {"years", DatePartSpecifier::YEAR}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {"day", DatePartSpecifier::DAY}, + {"days", DatePartSpecifier::DAY}, + {"yr", DatePartSpecifier::YEAR}, + {"yrs", DatePartSpecifier::YEAR}, + {"m", DatePartSpecifier::MINUTE}, + {"ms", DatePartSpecifier::MILLISECONDS}, + {"dayofweek", DatePartSpecifier::DOW}, + {"msec", DatePartSpecifier::MILLISECONDS}, + {"msecs", DatePartSpecifier::MILLISECONDS}, + {"era", DatePartSpecifier::ERA}, + {"msecond", DatePartSpecifier::MILLISECONDS}, + {"mseconds", DatePartSpecifier::MILLISECONDS}, + {"cent", DatePartSpecifier::CENTURY}, + {"h", DatePartSpecifier::HOUR}, + {"dayofyear", DatePartSpecifier::DOY}, + {"century", DatePartSpecifier::CENTURY}, + {"jd", DatePartSpecifier::JULIAN_DAY}, + {"centuries", DatePartSpecifier::CENTURY}, + {"doy", DatePartSpecifier::DOY}, + {"isodow", DatePartSpecifier::ISODOW}, + {"isoyear", DatePartSpecifier::ISOYEAR}, + {"microsecond", DatePartSpecifier::MICROSECONDS}, + {"microseconds", DatePartSpecifier::MICROSECONDS}, + {"us", DatePartSpecifier::MICROSECONDS}, + {"epoch", DatePartSpecifier::EPOCH}, + {"usec", DatePartSpecifier::MICROSECONDS}, + {"usecs", DatePartSpecifier::MICROSECONDS}, + {"yearweek", DatePartSpecifier::YEARWEEK}, + {"usecond", DatePartSpecifier::MICROSECONDS}, + {"useconds", DatePartSpecifier::MICROSECONDS}, + {"hr", DatePartSpecifier::HOUR}, + {"hrs", DatePartSpecifier::HOUR}, + {"dayofmonth", DatePartSpecifier::DAY}, + {"mil", DatePartSpecifier::MILLENNIUM}, + {"mils", DatePartSpecifier::MILLENNIUM}, + {nullptr, DatePartSpecifier::INVALID}, + {"min", DatePartSpecifier::MINUTE}, + {"mins", DatePartSpecifier::MINUTE}, + {nullptr, DatePartSpecifier::INVALID}, + {"minute", DatePartSpecifier::MINUTE}, + {"minutes", DatePartSpecifier::MINUTE}, + {nullptr, DatePartSpecifier::INVALID}, + {"millisecond", DatePartSpecifier::MILLISECONDS}, + {"milliseconds", DatePartSpecifier::MILLISECONDS}, + {"millennia", DatePartSpecifier::MILLENNIUM}, + {"millennium", DatePartSpecifier::MILLENNIUM}, + {"millenniums", DatePartSpecifier::MILLENNIUM}, + {"w", DatePartSpecifier::WEEK}, + {"quarter", DatePartSpecifier::QUARTER}, + {"quarters", DatePartSpecifier::QUARTER}, + {"week", DatePartSpecifier::WEEK}, + {"weeks", DatePartSpecifier::WEEK}, + {nullptr, DatePartSpecifier::INVALID}, + {"weekday", DatePartSpecifier::DOW}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {"weekofyear", DatePartSpecifier::WEEK}, + {"mon", DatePartSpecifier::MONTH}, + {"mons", DatePartSpecifier::MONTH}, + {"month", DatePartSpecifier::MONTH}, + {"months", DatePartSpecifier::MONTH}, + {"timezone", DatePartSpecifier::TIMEZONE}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {"timezone_hour", DatePartSpecifier::TIMEZONE_HOUR}, + {nullptr, DatePartSpecifier::INVALID}, + {"timezone_minute", DatePartSpecifier::TIMEZONE_MINUTE}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {nullptr, DatePartSpecifier::INVALID}, + {"julian", DatePartSpecifier::JULIAN_DAY}, + {nullptr, DatePartSpecifier::INVALID}, + {"millenium", DatePartSpecifier::MILLENNIUM}, + {nullptr, DatePartSpecifier::INVALID}, + {"dow", DatePartSpecifier::DOW}, + {"hour", DatePartSpecifier::HOUR}, + {"hours", DatePartSpecifier::HOUR}}; + +static uint8_t DatePartHashChar(char c) { + return DATE_PART_ASSO_VALUES[StringUtil::ASCII_TO_LOWER_MAP[static_cast(c)]]; +} + +static bool DatePartEquals(string_t input, const char *expected) { + const auto input_data = input.GetData(); + const auto input_size = input.GetSize(); + for (idx_t i = 0; i < input_size; i++) { + if (expected[i] == '\0') { + return false; + } + if (StringUtil::ASCII_TO_LOWER_MAP[static_cast(input_data[i])] != + StringUtil::ASCII_TO_LOWER_MAP[static_cast(expected[i])]) { + return false; + } + } + return expected[input_size] == '\0'; +} + +} // namespace + +bool TryGetDatePartSpecifier(const string &specifier, DatePartSpecifier &result) { + return TryGetDatePartSpecifier(string_t(specifier), result); +} + +bool TryGetDatePartSpecifier(string_t specifier, DatePartSpecifier &result) { + const auto specifier_data = specifier.GetData(); + const auto specifier_size = specifier.GetSize(); + if (specifier_size == 0 || specifier_size > 15) { return false; } + + uint32_t hash = static_cast(specifier_size); + if (specifier_size >= 8) { + hash += DatePartHashChar(specifier_data[7]); + } + if (specifier_size >= 3) { + hash += DatePartHashChar(specifier_data[2]); + } + if (specifier_size >= 2) { + hash += DatePartHashChar(specifier_data[1]); + } + hash += DatePartHashChar(specifier_data[0]); + if (hash > 100) { + return false; + } + + const auto &entry = DATE_PART_ENTRIES[hash]; + if (entry.name == nullptr || !DatePartEquals(specifier, entry.name)) { + return false; + } + result = entry.value; return true; } @@ -82,4 +191,12 @@ DatePartSpecifier GetDatePartSpecifier(const string &specifier) { return result; } +DatePartSpecifier GetDatePartSpecifier(string_t specifier) { + DatePartSpecifier result; + if (!TryGetDatePartSpecifier(specifier, result)) { + throw ConversionException("extract specifier \"%s\" not recognized", specifier.GetString()); + } + return result; +} + } // namespace duckdb diff --git a/src/duckdb/src/common/enums/logical_operator_type.cpp b/src/duckdb/src/common/enums/logical_operator_type.cpp index 7bf1d1078..197e678ce 100644 --- a/src/duckdb/src/common/enums/logical_operator_type.cpp +++ b/src/duckdb/src/common/enums/logical_operator_type.cpp @@ -88,8 +88,6 @@ string LogicalOperatorToString(LogicalOperatorType type) { return "CREATE_MACRO"; case LogicalOperatorType::LOGICAL_EXPLAIN: return "EXPLAIN"; - case LogicalOperatorType::LOGICAL_EXECUTE: - return "EXECUTE"; case LogicalOperatorType::LOGICAL_VACUUM: return "VACUUM"; case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: diff --git a/src/duckdb/src/common/enums/optimizer_type.cpp b/src/duckdb/src/common/enums/optimizer_type.cpp index c6b797f5e..ab72cddb4 100644 --- a/src/duckdb/src/common/enums/optimizer_type.cpp +++ b/src/duckdb/src/common/enums/optimizer_type.cpp @@ -58,6 +58,7 @@ static const DefaultOptimizerType internal_optimizer_types[] = { {"scalar_fn_pushdown", OptimizerType::SCALAR_FN_PUSHDOWN}, {"distinct_aggregate_rewrite", OptimizerType::DISTINCT_AGGREGATE_REWRITE}, {"aggregate_reuse", OptimizerType::AGGREGATE_REUSE}, + {"duplicate_eliminated_domain", OptimizerType::DUPLICATE_ELIMINATED_DOMAIN}, {"projection_placement", OptimizerType::PROJECTION_PLACEMENT}, {"redundant_order_keys", OptimizerType::REDUNDANT_ORDER_KEYS}, {"disjunctive_join_rewriter", OptimizerType::DISJUNCTIVE_JOIN_REWRITER}, diff --git a/src/duckdb/src/common/enums/physical_operator_type.cpp b/src/duckdb/src/common/enums/physical_operator_type.cpp index 7fbb5384e..5180e64d8 100644 --- a/src/duckdb/src/common/enums/physical_operator_type.cpp +++ b/src/duckdb/src/common/enums/physical_operator_type.cpp @@ -101,8 +101,6 @@ string PhysicalOperatorToString(PhysicalOperatorType type) { return "EXPLAIN"; case PhysicalOperatorType::EXPLAIN_ANALYZE: return "EXPLAIN_ANALYZE"; - case PhysicalOperatorType::EXECUTE: - return "EXECUTE"; case PhysicalOperatorType::VACUUM: return "VACUUM"; case PhysicalOperatorType::RECURSIVE_CTE: diff --git a/src/duckdb/src/common/error_data.cpp b/src/duckdb/src/common/error_data.cpp index acc4395cc..2c8d344d4 100644 --- a/src/duckdb/src/common/error_data.cpp +++ b/src/duckdb/src/common/error_data.cpp @@ -104,12 +104,23 @@ void ErrorData::Merge(const ErrorData &other) { return; } if (Exception::InvalidatesDatabase(other.Type()) || other.type == ExceptionType::INTERNAL) { - // inherit severe types + // inherit severe types; the result is scoped only if every severe error was handled by its database + auto was_severe = Exception::InvalidatesDatabase(type) || type == ExceptionType::INTERNAL; + auto other_entry = other.extra_info.find(Exception::INVALIDATED_DATABASE_KEY); + if (other_entry == other.extra_info.end()) { + extra_info.erase(Exception::INVALIDATED_DATABASE_KEY); + } else if (!was_severe) { + extra_info[Exception::INVALIDATED_DATABASE_KEY] = other_entry->second; + } type = other.type; } final_message += "\n\n" + other.Message(); } +void ErrorData::SetExtraInfo(const string &key, const string &value) { + extra_info[key] = value; +} + bool ErrorData::operator==(const ErrorData &other) const { if (initialized != other.initialized) { return false; diff --git a/src/duckdb/src/common/exception.cpp b/src/duckdb/src/common/exception.cpp index 34985ce1a..00ffdfc17 100644 --- a/src/duckdb/src/common/exception.cpp +++ b/src/duckdb/src/common/exception.cpp @@ -73,6 +73,8 @@ bool Exception::InvalidatesTransaction(ExceptionType exception_type) { } } +constexpr const char *Exception::INVALIDATED_DATABASE_KEY; + bool Exception::InvalidatesDatabase(ExceptionType exception_type) { switch (exception_type) { case ExceptionType::FATAL: diff --git a/src/duckdb/src/common/hive_partitioning.cpp b/src/duckdb/src/common/hive_partitioning.cpp index c103ab2e9..8c35102c5 100644 --- a/src/duckdb/src/common/hive_partitioning.cpp +++ b/src/duckdb/src/common/hive_partitioning.cpp @@ -240,21 +240,21 @@ void HivePartitioning::ApplyFiltersToFileList(ClientContext &context, vectorCopy(); bool representable = true; - ExpressionIterator::VisitExpressionMutable( - retained, [&](auto &column, unique_ptr &) { + retained = ExpressionIterator::PreorderReplace( + std::move(retained), [&](const BoundColumnRefExpression &column) -> unique_ptr { auto binding = column.Binding(); if (column.Depth() != 0 || binding.table_index != table_index || binding.column_index.GetIndex() >= info.column_indexes.size()) { representable = false; - return; + return nullptr; } auto &index = info.column_indexes[binding.column_index.GetIndex()]; if (index.IsVirtualColumn() || index.IsPushdownExtract() || index.HasType()) { representable = false; - return; + return nullptr; } - column.BindingMutable() = ColumnBinding(TableIndex(ExtraOperatorInfo::FILE_FILTER_TABLE_INDEX), - ProjectionIndex(index.GetPrimaryIndex())); + return column.WithBinding(ColumnBinding(TableIndex(ExtraOperatorInfo::FILE_FILTER_TABLE_INDEX), + ProjectionIndex(index.GetPrimaryIndex()))); }); if (!representable) { info.extra_info.file_filter_expressions.reset(); diff --git a/src/duckdb/src/common/logical_type_info.cpp b/src/duckdb/src/common/logical_type_info.cpp index de83239cc..6f4b1e97a 100644 --- a/src/duckdb/src/common/logical_type_info.cpp +++ b/src/duckdb/src/common/logical_type_info.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/common/string_map_set.hpp" +#include "duckdb/parser/expression/cast_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/type_expression.hpp" @@ -246,6 +247,28 @@ void UnboundTypeInfo::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault>(203, "user_type_modifiers", user_type_mods); } +// v1.x stores type parameters as typed values: the size of FLOAT[3] is a BIGINT, which reads back as +// CAST(3 AS BIGINT). The width of an integer parameter does not matter, so keep the literal, as the parser produces it. +static void UnwrapIntegerParameterCasts(ParsedExpression &expr) { + if (expr.GetExpressionClass() != ExpressionClass::TYPE) { + return; + } + for (auto ¶m : expr.Cast().GetChildren()) { + if (param->GetExpressionClass() == ExpressionClass::CAST) { + auto &cast = param->Cast(); + auto &child = cast.Child(); + if (child.GetExpressionClass() == ExpressionClass::CONSTANT && + child.Cast().GetLiteral().kind == LiteralKind::INTEGER && + UnboundType::TryDefaultBind(cast.TargetType()).IsIntegral()) { + auto alias = param->GetAlias(); + param = std::move(cast.ChildMutable()); + param->SetAlias(std::move(alias)); + } + } + UnwrapIntegerParameterCasts(*param); + } +} + unique_ptr UnboundTypeInfo::Deserialize(Deserializer &deserializer) { auto result = duckdb::unique_ptr(new UnboundTypeInfo()); @@ -269,6 +292,7 @@ unique_ptr UnboundTypeInfo::Deserialize(Deserializer &deseriali result->expr = make_uniq( QualifiedName(Identifier(catalog), Identifier(schema), Identifier(name)), std::move(user_type_mods)); } + UnwrapIntegerParameterCasts(*result->expr); return std::move(result); } 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 9c06ed759..d3d03b8e6 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 @@ -1123,8 +1123,8 @@ static unique_ptr TryCastFilterExpression(Context &context, const Ex if (!child.expr) { return nullptr; } - auto result = make_uniq(op.GetExpressionType(), op.GetReturnType()); - result->GetChildrenMutable().push_back(std::move(child.expr)); + auto result = + make_uniq(op.GetExpressionType(), op.GetReturnType(), std::move(child.expr)); return std::move(result); } case ExpressionType::COMPARE_IN: { @@ -1135,8 +1135,8 @@ static unique_ptr TryCastFilterExpression(Context &context, const Ex if (!lhs.expr || !lhs.type) { return nullptr; } - auto result = make_uniq(op.GetExpressionType(), op.GetReturnType()); - result->GetChildrenMutable().push_back(std::move(lhs.expr)); + auto result = + make_uniq(op.GetExpressionType(), op.GetReturnType(), std::move(lhs.expr)); for (idx_t i = 1; i < op.GetChildren().size(); i++) { if (op.GetChildren()[i]->GetExpressionType() != ExpressionType::VALUE_CONSTANT) { return nullptr; @@ -1171,21 +1171,18 @@ static unique_ptr TryCastTableFilter(Context &context, const TableF } static idx_t StartIndexAtZero(unique_ptr &root_expr) { - map>> reference_map; - - //! First gather all references, sorted by their index - ExpressionIterator::VisitExpressionMutable( - root_expr, [&reference_map](BoundReferenceExpression &ref, unique_ptr &expr) { - reference_map[ref.Index()].push_back(ref); - }); - idx_t new_index = 0; + //! First gather all referenced indexes, sorted + map index_map; + ExpressionIterator::VisitExpression( + *root_expr, [&index_map](const BoundReferenceExpression &ref) { index_map[ref.Index()] = 0; }); //! Then assign all the references a new index, starting at 0 - for (auto &[_, references] : reference_map) { - auto index = new_index++; - for (auto &ref : references) { - ref.get().IndexMutable() = index; - } + idx_t new_index = 0; + for (auto &entry : index_map) { + entry.second = new_index++; } + root_expr = ExpressionIterator::PreorderReplace( + std::move(root_expr), + [&index_map](const BoundReferenceExpression &ref) { return ref.WithIndex(index_map.at(ref.Index())); }); return new_index; } 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 e9c9e1bd5..b405e84b8 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 @@ -166,7 +166,8 @@ unique_ptr TableFunctionUnionData::GetStatistics(ClientContext & } for (idx_t col_idx = 0; col_idx < names.size(); col_idx++) { if (Identifier(names[col_idx]) == name) { - return statistics(context, bind_data.get(), col_idx); + TableFunctionGetStatisticsInput input(bind_data.get(), ColumnIndex(col_idx)); + return statistics(context, input); } } return nullptr; @@ -177,7 +178,8 @@ unique_ptr TableFunctionUnionData::GetVirtualColumnStatistics(Cl if (!statistics || !bind_data) { return nullptr; } - return statistics(context, bind_data.get(), virtual_column_id); + TableFunctionGetStatisticsInput input(bind_data.get(), ColumnIndex(virtual_column_id)); + return statistics(context, input); } shared_ptr TableFunctionFileReader::GetUnionData(idx_t file_idx) { @@ -186,7 +188,7 @@ shared_ptr TableFunctionFileReader::GetUnionData(idx_t file_idx) result->types = types; result->cardinality = cardinality; result->bind_data = bind_data; - result->statistics = function.statistics; + result->statistics = function.statistics_extended; if (file_idx == 0) { // keep the first reader around so we don't need to bind it again result->reader = shared_from_this(); @@ -195,12 +197,13 @@ shared_ptr TableFunctionFileReader::GetUnionData(idx_t file_idx) } unique_ptr TableFunctionFileReader::GetStatistics(ClientContext &context, const Identifier &name) { - if (!function.statistics || !bind_data) { + if (!function.statistics_extended || !bind_data) { return nullptr; } for (idx_t col_idx = 0; col_idx < names.size(); col_idx++) { if (names[col_idx] == name) { - return function.statistics(context, bind_data.get(), col_idx); + TableFunctionGetStatisticsInput input(bind_data.get(), ColumnIndex(col_idx)); + return function.statistics_extended(context, input); } } return nullptr; @@ -208,10 +211,11 @@ unique_ptr TableFunctionFileReader::GetStatistics(ClientContext unique_ptr TableFunctionFileReader::GetVirtualColumnStatistics(ClientContext &context, column_t virtual_column_id) { - if (!function.statistics || !bind_data) { + if (!function.statistics_extended || !bind_data) { return nullptr; } - return function.statistics(context, bind_data.get(), virtual_column_id); + TableFunctionGetStatisticsInput input(bind_data.get(), ColumnIndex(virtual_column_id)); + return function.statistics_extended(context, input); } void TableFunctionFileReader::AddVirtualColumn(column_t virtual_column_id) { @@ -744,12 +748,12 @@ static constexpr idx_t MIN_ESTIMATED_BYTES_PER_ROW = 10; //! The row count the caller gives for the whole scan, read_parquet's explicit_cardinality (0 means not given). Looked //! up by name, by convention: read_parquet is the only wrapped function that declares it -static optional_idx ExplicitCardinality(const TableFunctionMultiFileData &data) { +static optional_idx ExplicitCardinality(Context &context, const TableFunctionMultiFileData &data) { auto entry = data.options.named_parameters.find(Identifier("explicit_cardinality")); if (entry == data.options.named_parameters.end() || entry->second.IsNull()) { return optional_idx(); } - auto cardinality = entry->second.DefaultCastAs(LogicalType::UBIGINT).GetValue(); + auto cardinality = entry->second.CastAs(context, LogicalType::UBIGINT).GetValue(); if (cardinality == 0) { return optional_idx(); } @@ -764,7 +768,7 @@ unique_ptr TableFunctionMultiFileWrapper::GetCardinality(ClientC } auto &data = bind_data.bind_data->Cast(); auto result = make_uniq(); - auto explicit_cardinality = ExplicitCardinality(data); + auto explicit_cardinality = ExplicitCardinality(context.GetContext(), data); if (explicit_cardinality.IsValid()) { result->has_estimated_cardinality = true; result->estimated_cardinality = explicit_cardinality.GetIndex(); @@ -952,7 +956,12 @@ TableFunction TableFunctionMultiFileWrapper::CreateFunction(TableFunction single // the metrics of the scan include those the wrapped function keeps per file result.get_metrics = TableFunctionMultiFileGetMetrics; } - if (single_file_function.statistics) { + if (single_file_function.statistics && !single_file_function.statistics_extended) { + throw InternalException("Table function %s defines statistics, but a function wrapped in a multi file function " + "needs statistics_extended", + single_file_function.name); + } + if (single_file_function.statistics_extended) { // the statistics of the scan are those of its files, combined result.statistics_extended = TableFunctionMultiFileFunction::MultiFileScanStatsExtended; } diff --git a/src/duckdb/src/common/sort/sort_strategy.cpp b/src/duckdb/src/common/sort/sort_strategy.cpp index a11011a83..a30e64dff 100644 --- a/src/duckdb/src/common/sort/sort_strategy.cpp +++ b/src/duckdb/src/common/sort/sort_strategy.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/sorting/hashed_sort.hpp" #include "duckdb/common/sorting/natural_sort.hpp" #include "duckdb/common/sorting/partitioned_sort.hpp" +#include "duckdb/common/types/row/tuple_data_collection.hpp" namespace duckdb { diff --git a/src/duckdb/src/common/string_util.cpp b/src/duckdb/src/common/string_util.cpp index f73f039be..ff9d96457 100644 --- a/src/duckdb/src/common/string_util.cpp +++ b/src/duckdb/src/common/string_util.cpp @@ -995,6 +995,17 @@ string StringUtil::ReplaceFileName(const string &file_path, const string &file_n return file_path.substr(0, pos + 1) + file_name; } +string StringUtil::GetURIAuthority(const string &str) { + auto scheme_end = str.find("://"); + bool has_uri_scheme = scheme_end != string::npos && scheme_end > 0 && str.find_first_of("/\\") == scheme_end + 1; + if (!has_uri_scheme) { + return {}; + } + auto authority_start = scheme_end + 3; + auto authority_end = str.find_first_of("/\\?#", authority_start); + return str.substr(authority_start, authority_end == string::npos ? string::npos : authority_end - authority_start); +} + struct URLEncodeLength { using RESULT_TYPE = idx_t; diff --git a/src/duckdb/src/common/thread_util.cpp b/src/duckdb/src/common/thread_util.cpp index 37afc0f24..3ab97c849 100644 --- a/src/duckdb/src/common/thread_util.cpp +++ b/src/duckdb/src/common/thread_util.cpp @@ -5,17 +5,18 @@ #include "duckdb/common/helper.hpp" #include "duckdb/common/time_point.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { #ifndef DUCKDB_NO_THREADS -void ThreadUtil::SleepMs(idx_t sleep_ms, optional_ptr context) { +void ThreadUtil::SleepMs(idx_t sleep_ms, optional_ptr context) { auto start_time = TimePoint::Tick(); static constexpr idx_t DEFAULT_SLEEP_INTERVAL_MS = 100; while (true) { - if (context && context->IsInterrupted()) { - throw InterruptException(); + if (context) { + context->InterruptCheck(); } auto elapsed_ms = static_cast(start_time.ElapsedMillis()); if (elapsed_ms >= sleep_ms) { @@ -42,7 +43,7 @@ string ThreadUtil::GetThreadIdString() { #else -void ThreadUtil::SleepMs(idx_t sleep_ms, optional_ptr) { +void ThreadUtil::SleepMs(idx_t sleep_ms, optional_ptr) { throw InvalidInputException("ThreadUtil::SleepMs requires DuckDB to be compiled with thread support"); } diff --git a/src/duckdb/src/common/tree_renderer.cpp b/src/duckdb/src/common/tree_renderer.cpp index 2634c6714..c02d50dd7 100644 --- a/src/duckdb/src/common/tree_renderer.cpp +++ b/src/duckdb/src/common/tree_renderer.cpp @@ -11,6 +11,7 @@ #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" namespace duckdb { @@ -89,6 +90,34 @@ unique_ptr TreeRenderer::CreateRenderer(const ProfilerPrintFormat return CreateRenderer(format.ToString()); } +unordered_map TreeRenderer::GetRendererSettings(ClientContext &context) { + unordered_map result; + for (auto &entry : Settings::Get(context)) { + result.emplace(entry.first, Value(entry.second)); + } + return result; +} + +void TreeRenderer::SetRendererSettings(ClientContext &context, const unordered_map &settings) { + Settings::Set(context, SetScope::SESSION, RendererSettingsToValue(settings)); +} + +Value TreeRenderer::RendererSettingsToValue(const unordered_map &settings) { + // sort the settings by name so that the rendered value is deterministic + vector setting_names; + for (auto &entry : settings) { + setting_names.push_back(entry.first); + } + std::sort(setting_names.begin(), setting_names.end()); + vector keys; + vector values; + for (auto &name : setting_names) { + keys.emplace_back(name); + values.push_back(settings.at(name).DefaultCastAs(LogicalType::VARCHAR)); + } + return Value::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR, std::move(keys), std::move(values)); +} + unique_ptr TreeRenderer::CreateRenderer(ClientContext &context, const string &name) { // registered renderers take precedence over the built-in formats auto extension = ProfilerExtension::Find(context, name); @@ -97,7 +126,7 @@ unique_ptr TreeRenderer::CreateRenderer(ClientContext &context, co } auto renderer = CreateRenderer(name); if (renderer) { - renderer->Configure(ClientConfig::GetConfig(context).profiling_renderer_settings); + renderer->Configure(GetRendererSettings(context)); } return renderer; } diff --git a/src/duckdb/src/common/types.cpp b/src/duckdb/src/common/types.cpp index d1642e855..dada262ca 100644 --- a/src/duckdb/src/common/types.cpp +++ b/src/duckdb/src/common/types.cpp @@ -4,6 +4,7 @@ #include "duckdb/catalog/catalog_entry/type_catalog_entry.hpp" #include "duckdb/catalog/catalog_search_path.hpp" #include "duckdb/catalog/default/default_types.hpp" +#include "duckdb/common/array.hpp" #include "duckdb/common/enum_util.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/logical_type_info.hpp" @@ -212,11 +213,32 @@ const LogicalTypeInfo *LogicalType::TryGetBuiltinTypeInfo(LogicalTypeId id) noex return builtins->infos[static_cast(id)]; } +static unique_ptr CreateVariantTypeInfo() { + child_list_t children; + //! keys + children.emplace_back("keys", LogicalType::LIST(LogicalTypeId::VARCHAR)); + //! children + children.emplace_back("children", + LogicalType::LIST(LogicalType::STRUCT( + {{"keys_index", LogicalType::UINTEGER}, {"values_index", LogicalType::UINTEGER}}))); + //! values + children.emplace_back("values", LogicalType::LIST(LogicalType::STRUCT( + {{"type_id", LogicalType::UTINYINT}, {"byte_offset", LogicalType::UINTEGER}}))); + //! data + children.emplace_back("data", LogicalType::BLOB); + + return make_uniq(std::move(children)); +} + const LogicalTypeInfo &LogicalType::GetBuiltinTypeInfo(LogicalTypeId id) { auto info = TryGetBuiltinTypeInfo(id); if (!info) { throw InternalException("Invalid LogicalType %d", static_cast(id)); } + if (id == LogicalTypeId::VARIANT) { + static const auto variant_type = CreateImmortal(LogicalTypeId::VARIANT, CreateVariantTypeInfo()); + return variant_type.GetTypeInfo(); + } return *info; } @@ -227,10 +249,9 @@ LogicalType::LogicalType(LogicalTypeId id) : type_info_(GetBuiltinTypeInfo(id)) } const LogicalTypeInfo &LogicalType::AdoptNewTypeInfo(LogicalTypeId id, unique_ptr type_info) { - // validates the id - and ensures the builtin infos exist before any type does - auto &builtin_type_info = GetBuiltinTypeInfo(id); + // Only resolve built-in info when none was supplied, to avoid recursive initialization. if (!type_info) { - return builtin_type_info; + return GetBuiltinTypeInfo(id); } if (!TryGetPhysicalType(id, *type_info, type_info->physical_type)) { throw InternalException("Invalid LogicalType %d", static_cast(id)); @@ -1475,6 +1496,9 @@ LogicalType LogicalType::Deserialize(Deserializer &deserializer) { throw SerializationException("Failed to deserialize type: invalid DECIMAL(%d, %d)", decimal_info.width, decimal_info.scale); } + if (id == LogicalTypeId::DECIMAL && type_info->alias.empty() && !type_info->extension_info) { + return DECIMAL(decimal_info.width, decimal_info.scale); + } } LogicalType result(id, std::move(type_info)); if (info_type != LogicalTypeInfoType::INVALID_TYPE_INFO && info_type != LogicalTypeInfoType::GENERIC_TYPE_INFO && @@ -1493,12 +1517,13 @@ LogicalType LogicalType::Deserialize(Deserializer &deserializer) { // Extra Type Info //===--------------------------------------------------------------------===// LogicalType LogicalType::Copy() const { - if (type_info_.get().type == LogicalTypeInfoType::INVALID_TYPE_INFO || - type_info_.get().type == LogicalTypeInfoType::ENUM_TYPE_INFO) { + auto &info = type_info_.get(); + if (info.immortal || info.type == LogicalTypeInfoType::INVALID_TYPE_INFO || + info.type == LogicalTypeInfoType::ENUM_TYPE_INFO) { // enum type info is kept shared to avoid rebuilding the dictionary lookup map return *this; } - return LogicalType(id(), type_info_.get().Copy()); + return LogicalType(id(), info.Copy()); } //! Copies the type info so it can be modified before being adopted by a new type @@ -1560,10 +1585,33 @@ uint32_t DecimalType::MaxWidth() { return DecimalWidth::max; } +static constexpr idx_t DecimalTypeInfoIndex(idx_t width, idx_t scale) { + return (width - 1) * (width + 2) / 2 + scale; +} + LogicalType LogicalType::DECIMAL(uint32_t width, uint32_t scale) { D_ASSERT(width >= scale); - auto type_info = make_uniq(width, scale); - return LogicalType(LogicalTypeId::DECIMAL, std::move(type_info)); + if (!Decimal::IsValidWidthScale(width, scale)) { + return LogicalType(LogicalTypeId::DECIMAL, make_uniq(width, scale)); + } + static constexpr idx_t TYPE_COUNT = + DecimalTypeInfoIndex(Decimal::MAX_WIDTH_DECIMAL, Decimal::MAX_WIDTH_DECIMAL) + 1; + static const auto decimal_types = []() { + // Finish allocation before immortalizing any info so failed initialization releases partial allocations. + array, TYPE_COUNT> infos; + for (uint32_t width = 1; width <= Decimal::MAX_WIDTH_DECIMAL; width++) { + for (uint32_t scale = 0; scale <= width; scale++) { + infos[DecimalTypeInfoIndex(width, scale)] = make_uniq(width, scale); + } + } + array, TYPE_COUNT> result; + for (idx_t i = 0; i < TYPE_COUNT; i++) { + auto type = CreateImmortal(LogicalTypeId::DECIMAL, std::move(infos[i])); + result[i] = type.GetTypeInfo(); + } + return result; + }(); + return LogicalType(*decimal_types[DecimalTypeInfoIndex(width, scale)]); } //===--------------------------------------------------------------------===// @@ -2038,26 +2086,8 @@ const string &TemplateType::GetName(const LogicalType &type) { // Variant Type //===--------------------------------------------------------------------===// -static unique_ptr CreateVariantTypeInfo() { - child_list_t children; - //! keys - children.emplace_back("keys", LogicalType::LIST(LogicalTypeId::VARCHAR)); - //! children - children.emplace_back("children", - LogicalType::LIST(LogicalType::STRUCT( - {{"keys_index", LogicalType::UINTEGER}, {"values_index", LogicalType::UINTEGER}}))); - //! values - children.emplace_back("values", LogicalType::LIST(LogicalType::STRUCT( - {{"type_id", LogicalType::UTINYINT}, {"byte_offset", LogicalType::UINTEGER}}))); - //! data - children.emplace_back("data", LogicalType::BLOB); - - return make_uniq(std::move(children)); -} - LogicalType LogicalType::VARIANT() { - static const auto variant_type = CreateImmortal(LogicalTypeId::VARIANT, CreateVariantTypeInfo()); - return variant_type; + return LogicalType(LogicalTypeId::VARIANT); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/common/types/value.cpp b/src/duckdb/src/common/types/value.cpp index b8d1b5ff7..91532a68b 100644 --- a/src/duckdb/src/common/types/value.cpp +++ b/src/duckdb/src/common/types/value.cpp @@ -2173,7 +2173,7 @@ optional Value::TryCastAs(Context &context, const LogicalType &target_typ optional Value::DefaultTryCastAs(const LogicalType &target_type, string *error_message, bool strict) const { CastFunctionSet set; - GetCastFunctionInput get_input; + auto get_input = GetCastFunctionInput::Default(); return TryCastAs(set, get_input, target_type, error_message, strict); } @@ -2202,7 +2202,7 @@ Value Value::CastAs(Context &context, const LogicalType &target_type, bool stric Value Value::DefaultCastAs(const LogicalType &target_type, bool strict) const { CastFunctionSet set; - GetCastFunctionInput get_input; + auto get_input = GetCastFunctionInput::Default(); return CastAs(set, get_input, target_type, strict); } @@ -2716,7 +2716,7 @@ bool Value::ValuesAreEqual(ClientContext &context, const Value &result_value, co } bool Value::DefaultValuesAreEqual(const Value &result_value, const Value &value) { CastFunctionSet set; - GetCastFunctionInput get_input; + auto get_input = GetCastFunctionInput::Default(); return Value::ValuesAreEqual(set, get_input, result_value, value); } diff --git a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp index fd97289ce..68fc16a73 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp @@ -303,6 +303,7 @@ static idx_t AnalyzePrimitiveValueData(const UnifiedVariantVectorData &variant, case VariantLogicalType::TIMESTAMP_MICROS: case VariantLogicalType::TIMESTAMP_NANOS: case VariantLogicalType::TIMESTAMP_MICROS_TZ: + case VariantLogicalType::TIMESTAMP_NANOS_TZ: total_size += sizeof(uint64_t); break; case VariantLogicalType::UINT8: @@ -581,6 +582,10 @@ static void WritePrimitiveValueData(const UnifiedVariantVectorData &variant, idx WritePrimitiveTypeHeader(value_data); CopySimplePrimitiveData(variant, value_data, row, values_index); break; + case VariantLogicalType::TIMESTAMP_NANOS_TZ: + WritePrimitiveTypeHeader(value_data); + CopySimplePrimitiveData(variant, value_data, row, values_index); + break; case VariantLogicalType::DECIMAL: { auto decimal_data = VariantUtils::DecodeDecimalData(variant, row, values_index); 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 3aca09623..95a443da9 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp @@ -387,7 +387,11 @@ void ParquetVariantIterator::BeginRow(idx_t row) { const VariantMetadata &ParquetVariantIterator::GetMetadata() const { if (!current_metadata) { - current_metadata = make_uniq(metadata[current_row].GetValueUnsafe()); + auto metadata_entry = metadata[current_row]; + if (!metadata_entry.IsValid()) { + throw DataCorruptionException("VARIANT metadata cannot be NULL"); + } + current_metadata = make_uniq(metadata_entry.GetValue()); } return *current_metadata; } diff --git a/src/duckdb/src/common/vector_operations/vector_cast.cpp b/src/duckdb/src/common/vector_operations/vector_cast.cpp index cb1c3b898..a5ddf8f01 100644 --- a/src/duckdb/src/common/vector_operations/vector_cast.cpp +++ b/src/duckdb/src/common/vector_operations/vector_cast.cpp @@ -2,6 +2,8 @@ #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/function/scalar_function.hpp" namespace duckdb { @@ -11,7 +13,7 @@ bool VectorOperations::TryCast(CastFunctionSet &set, GetCastFunctionInput &input auto cast_function = set.GetCastFunction(source.GetType(), result.GetType(), input); unique_ptr local_state; if (cast_function.HasInitLocalState()) { - CastLocalStateParameters lparameters(input.context, cast_function.GetCastData()); + CastLocalStateParameters lparameters(input.client_context, cast_function.GetCastData()); local_state = cast_function.InitLocalState(lparameters); } CastParameters parameters(cast_function.GetCastData().get(), strict, error_message, local_state.get(), @@ -21,7 +23,7 @@ bool VectorOperations::TryCast(CastFunctionSet &set, GetCastFunctionInput &input bool VectorOperations::DefaultTryCast(Vector &source, Vector &result, idx_t count, string *error_message, bool strict) { CastFunctionSet set; - GetCastFunctionInput input; + auto input = GetCastFunctionInput::Default(); return VectorOperations::TryCast(set, input, source, result, count, error_message, strict); } @@ -29,14 +31,6 @@ void VectorOperations::DefaultCast(Vector &source, Vector &result, idx_t count, VectorOperations::DefaultTryCast(source, result, count, nullptr, strict); } -bool VectorOperations::TryCast(ClientContext &context, Vector &source, Vector &result, idx_t count, - string *error_message, bool strict, const bool nullify_parent) { - auto &config = DBConfig::GetConfig(context); - auto &set = config.GetCastFunctions(); - GetCastFunctionInput get_input(context); - return VectorOperations::TryCast(set, get_input, source, result, count, error_message, strict, nullify_parent); -} - bool VectorOperations::TryCast(Context &context, Vector &source, Vector &result, idx_t count, string *error_message, bool strict, const bool nullify_parent) { GetCastFunctionInput get_input(context); @@ -48,6 +42,12 @@ void VectorOperations::Cast(Context &context, Vector &source, Vector &result, id VectorOperations::TryCast(context, source, result, count, nullptr, strict); } +bool VectorOperations::TryCast(ClientContext &context, Vector &source, Vector &result, idx_t count, + string *error_message, bool strict, const bool nullify_parent) { + return VectorOperations::TryCast(context.GetContext(), source, result, count, error_message, strict, + nullify_parent); +} + void VectorOperations::Cast(ClientContext &context, Vector &source, Vector &result, idx_t count, bool strict) { VectorOperations::TryCast(context, source, result, count, nullptr, strict); } diff --git a/src/duckdb/src/execution/expression_executor.cpp b/src/duckdb/src/execution/expression_executor.cpp index d8ac438f6..6aa9b0ce7 100644 --- a/src/duckdb/src/execution/expression_executor.cpp +++ b/src/duckdb/src/execution/expression_executor.cpp @@ -1,5 +1,9 @@ #include "duckdb/execution/expression_executor.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" +#include "duckdb/main/database.hpp" + #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" @@ -13,22 +17,20 @@ namespace duckdb { -ExpressionExecutor::ExpressionExecutor(ClientContext &context) : context(&context) { +ExpressionExecutor::ExpressionExecutor(Context &context_p) : context(context_p) { debug_vector_verification = Settings::Get(context); } -ExpressionExecutor::ExpressionExecutor(ClientContext &context, const Expression *expression) - : ExpressionExecutor(context) { +ExpressionExecutor::ExpressionExecutor(Context &context, const Expression *expression) : ExpressionExecutor(context) { D_ASSERT(expression); AddExpression(*expression); } -ExpressionExecutor::ExpressionExecutor(ClientContext &context, const Expression &expression) - : ExpressionExecutor(context) { +ExpressionExecutor::ExpressionExecutor(Context &context, const Expression &expression) : ExpressionExecutor(context) { AddExpression(expression); } -ExpressionExecutor::ExpressionExecutor(ClientContext &context, const vector> &exprs) +ExpressionExecutor::ExpressionExecutor(Context &context, const vector> &exprs) : ExpressionExecutor(context) { D_ASSERT(exprs.size() > 0); for (auto &expr : exprs) { @@ -36,33 +38,59 @@ ExpressionExecutor::ExpressionExecutor(ClientContext &context, const vector> &exprs) : context(nullptr) { +ExpressionExecutor::ExpressionExecutor(ClientContext &context) : ExpressionExecutor(context.GetContext()) { +} + +ExpressionExecutor::ExpressionExecutor(ClientContext &context, const Expression *expression) + : ExpressionExecutor(context.GetContext(), expression) { +} + +ExpressionExecutor::ExpressionExecutor(ClientContext &context, const Expression &expression) + : ExpressionExecutor(context.GetContext(), expression) { +} + +ExpressionExecutor::ExpressionExecutor(ClientContext &context, const vector> &exprs) + : ExpressionExecutor(context.GetContext(), exprs) { +} + +ExpressionExecutor::ExpressionExecutor(DatabaseInstance &db) : ExpressionExecutor(db.GetContext()) { +} + +ExpressionExecutor::ExpressionExecutor(DatabaseInstance &db, const Expression &expression) : ExpressionExecutor(db) { + AddExpression(expression); +} + +ExpressionExecutor::ExpressionExecutor(DatabaseInstance &db, const vector> &exprs) + : ExpressionExecutor(db) { D_ASSERT(exprs.size() > 0); for (auto &expr : exprs) { AddExpression(*expr); } } -ExpressionExecutor::ExpressionExecutor() : context(nullptr) { +Context &ExpressionExecutor::GetContext() { + return context; } -bool ExpressionExecutor::HasContext() { - return context; +bool ExpressionExecutor::HasClientContext() { + return context.IsClient(); } -ClientContext &ExpressionExecutor::GetContext() { - if (!context) { - throw InternalException("Calling ExpressionExecutor::GetContext on an expression executor without a context"); +ClientContext &ExpressionExecutor::GetClientContext() { + auto client_context = context.TryGetClientContext(); + if (!client_context) { + throw InternalException( + "Calling ExpressionExecutor::GetClientContext on an expression executor without a client context"); } - return *context; + return *client_context; } -optional_ptr ExpressionExecutor::GetContextPtr() { - return context; +optional_ptr ExpressionExecutor::TryGetClientContext() { + return context.TryGetClientContext(); } Allocator &ExpressionExecutor::GetAllocator() { - return context ? Allocator::Get(*context) : Allocator::DefaultAllocator(); + return Allocator::Get(context.GetDatabase()); } void ExpressionExecutor::AddExpression(const Expression &expr) { @@ -92,7 +120,7 @@ void ExpressionExecutor::Execute(DataChunk *input, DataChunk &result) { ExecuteExpression(i, result.data[i]); } result.SetChildCardinality(input ? input->size() : 1); - result.Verify(context); + result.Verify(context.GetDatabase()); } void ExpressionExecutor::ExecuteExpression(DataChunk &input, Vector &result) { @@ -146,6 +174,10 @@ void ExpressionExecutor::ExecuteExpression(idx_t expr_idx, Vector &result, const } Value ExpressionExecutor::EvaluateScalar(ClientContext &context, const Expression &expr, bool allow_unfoldable) { + return EvaluateScalar(context.GetContext(), expr, allow_unfoldable); +} + +Value ExpressionExecutor::EvaluateScalar(Context &context, const Expression &expr, bool allow_unfoldable) { D_ASSERT(allow_unfoldable || expr.IsFoldable()); D_ASSERT(expr.IsScalar()); // use an ExpressionExecutor to execute the expression @@ -161,6 +193,10 @@ Value ExpressionExecutor::EvaluateScalar(ClientContext &context, const Expressio } bool ExpressionExecutor::TryEvaluateScalar(ClientContext &context, const Expression &expr, Value &result) { + return TryEvaluateScalar(context.GetContext(), expr, result); +} + +bool ExpressionExecutor::TryEvaluateScalar(Context &context, const Expression &expr, Value &result) { try { result = EvaluateScalar(context, expr); return true; @@ -201,21 +237,13 @@ void ExpressionExecutor::Verify(const Expression &expr, Vector &vector, idx_t co Vector intermediate(LogicalType::VARIANT(), cast_count); //! First cast to VARIANT - if (HasContext()) { - VectorOperations::Cast(GetContext(), vector, intermediate, cast_count, true); - } else { - VectorOperations::DefaultCast(vector, intermediate, cast_count, true); - } + VectorOperations::Cast(GetContext(), vector, intermediate, cast_count, true); intermediate.Verify(); //! FIXME: this is probably also where we want to test 'variant_normalize' Vector result(vector.GetType(), cast_count); //! Then cast back into the original type - if (HasContext()) { - VectorOperations::Cast(GetContext(), intermediate, result, cast_count, true); - } else { - VectorOperations::DefaultCast(intermediate, result, cast_count, true); - } + VectorOperations::Cast(GetContext(), intermediate, result, cast_count, true); if (input_is_constant) { result.SetVectorType(VectorType::CONSTANT_VECTOR); FlatVector::SetSize(result, count_t(count)); diff --git a/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp b/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp index 2f2ba803c..2f92d07fd 100644 --- a/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp @@ -12,9 +12,7 @@ namespace duckdb { struct ConjunctionState : public ExpressionState { ConjunctionState(const Expression &expr, ExpressionExecutorState &root) : ExpressionState(expr, root) { adaptive_filter = make_uniq(expr); - if (HasContext()) { - adaptive_filter->SetLogger(GetContext().GetContext().GetLoggerPtr()); - } + adaptive_filter->SetLogger(GetContext().GetLoggerPtr()); } unique_ptr adaptive_filter; }; diff --git a/src/duckdb/src/execution/expression_executor/execute_function.cpp b/src/duckdb/src/execution/expression_executor/execute_function.cpp index 444650e8b..01bb01e05 100644 --- a/src/duckdb/src/execution/expression_executor/execute_function.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_function.cpp @@ -263,7 +263,7 @@ void ExpressionExecutor::Execute(const BoundFunctionExpression &expr, Expression } else { arguments.SetChildCardinality(count); } - arguments.Verify(context); + arguments.Verify(context.GetDatabase()); auto dictionary_executed = expr.Function().HasFunctionCallback() && !all_constant && execute_function_state.TryExecuteDictionaryExpression(expr, arguments, *state, result); @@ -321,7 +321,7 @@ idx_t ExpressionExecutor::Select(const BoundFunctionExpression &expr, Expression } else { arguments.SetChildCardinality(count); } - arguments.Verify(context); + arguments.Verify(context.GetDatabase()); if (all_constant) { Vector result(LogicalType::BOOLEAN); if (expr.Function().HasFunctionCallback()) { diff --git a/src/duckdb/src/execution/expression_executor_state.cpp b/src/duckdb/src/execution/expression_executor_state.cpp index eebbbd46d..f10720111 100644 --- a/src/duckdb/src/execution/expression_executor_state.cpp +++ b/src/duckdb/src/execution/expression_executor_state.cpp @@ -23,7 +23,7 @@ void ExpressionState::Finalize() { if (types.empty()) { return; } - auto &allocator = HasContext() ? BufferAllocator::Get(GetContext()) : GetAllocator(); + auto &allocator = BufferAllocator::Get(GetContext()); intermediate_chunk.Initialize(allocator, types, initialize); } @@ -31,16 +31,20 @@ Allocator &ExpressionState::GetAllocator() { return root.executor->GetAllocator(); } -bool ExpressionState::HasContext() { - return root.executor->HasContext(); +Context &ExpressionState::GetContext() { + return root.executor->GetContext(); +} + +bool ExpressionState::HasClientContext() { + return root.executor->HasClientContext(); } -ClientContext &ExpressionState::GetContext() { - if (!HasContext()) { +ClientContext &ExpressionState::GetClientContext() { + if (!HasClientContext()) { throw BinderException("Cannot use %s in this context", (expr.Cast()).Function().GetName()); } - return root.executor->GetContext(); + return root.executor->GetClientContext(); } ExpressionState::ExpressionState(const Expression &expr, ExpressionExecutorState &root) : expr(expr), root(root) { diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index a6f258713..adb87de0d 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -681,14 +681,8 @@ ErrorData ART::InsertKeys(ArenaAllocator &arena, unsafe_vector &keys, un ErrorData ART::Append(IndexLock &l, DataChunk &chunk, Vector &row_ids) { l.AssertHeld(*this); - // Execute all column expressions before inserting the data chunk. - DataChunk expr_chunk; - expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types); - ExecuteExpressions(chunk, expr_chunk); - - // Now insert the data chunk. IndexAppendInfo info; - return Insert(l, expr_chunk, row_ids, info); + return Append(l, chunk, row_ids, info); } ErrorData ART::Append(IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info) { @@ -696,7 +690,12 @@ ErrorData ART::Append(IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppe // Execute all column expressions before inserting the data chunk. DataChunk expr_chunk; expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types); - ExecuteExpressions(chunk, expr_chunk); + try { + ExecuteExpressions(chunk, expr_chunk); + } catch (std::exception &ex) { + // nothing was inserted yet: return the error instead of throwing + return ErrorData(ex); + } // Now insert the data chunk. return Insert(l, expr_chunk, row_ids, info); diff --git a/src/duckdb/src/execution/index/art/base_leaf.cpp b/src/duckdb/src/execution/index/art/base_leaf.cpp index 7f30cac18..e10a61bc9 100644 --- a/src/duckdb/src/execution/index/art/base_leaf.cpp +++ b/src/duckdb/src/execution/index/art/base_leaf.cpp @@ -69,10 +69,11 @@ void Node7Leaf::InsertByte(ART &art, NodePtr &node_ptr, const uint8_t byte) { Node15Leaf::InsertByte(art, node_ptr, byte); } -void Node7Leaf::DeleteByte(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const uint8_t byte, const ARTKey &row_id) { +void Node7Leaf::DeleteByte(ART &art, NodePtrHandle node_ptr_handle, NodePtr &parent_ptr, const uint8_t byte, + const ARTKey &row_id) { idx_t remainder; { - auto n7_handle = DeleteByteInternal(art, node_ptr, byte); + auto n7_handle = DeleteByteInternal(art, node_ptr_handle.Get(), byte); auto &n7 = n7_handle.Get(); if (n7.count != 1) { @@ -80,7 +81,7 @@ void Node7Leaf::DeleteByte(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, con } // Compress one-way nodes. - D_ASSERT(node_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); + D_ASSERT(node_ptr_handle.Get().GetGateStatus() == GateStatus::GATE_NOT_SET); // Get the remaining row ID. remainder = UnsafeNumericCast(row_id.GetRowId()) & AND_LAST_BYTE; @@ -88,13 +89,15 @@ void Node7Leaf::DeleteByte(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, con } // Free the prefix (nodes) and inline the remainder. if (parent_ptr.GetType() == NType::PREFIX) { + // The freed prefix chain stores the node's NodePtr: release its pin first. + node_ptr_handle.Release(); NodePtr::FreeTree(art, parent_ptr); Leaf::New(parent_ptr, UnsafeNumericCast(remainder)); return; } // Free the Node7Leaf and inline the remainder. - NodePtr::FreeNode(art, node_ptr); - Leaf::New(node_ptr, UnsafeNumericCast(remainder)); + NodePtr::FreeNode(art, node_ptr_handle.Get()); + Leaf::New(node_ptr_handle.Get(), UnsafeNumericCast(remainder)); } void Node7Leaf::ShrinkNode15Leaf(ART &art, NodePtr &node7_leaf_ptr, NodePtr &node15_leaf_ptr) { diff --git a/src/duckdb/src/execution/index/art/base_node.cpp b/src/duckdb/src/execution/index/art/base_node.cpp index 1ea9af303..5f0541393 100644 --- a/src/duckdb/src/execution/index/art/base_node.cpp +++ b/src/duckdb/src/execution/index/art/base_node.cpp @@ -2,7 +2,7 @@ #include "duckdb/execution/index/art/leaf.hpp" #include "duckdb/execution/index/art/node48.hpp" -#include "duckdb/execution/index/art/prefix.hpp" +#include "duckdb/execution/index/art/prefix_handle.hpp" namespace duckdb { @@ -75,12 +75,13 @@ void Node4::InsertChild(ART &art, NodePtr &node_ptr, const uint8_t byte, const N Node16::InsertChild(art, node_ptr, byte, child_ptr); } -void Node4::DeleteChild(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const uint8_t byte, const GateStatus status) { +void Node4::DeleteChild(ART &art, NodePtrHandle node_ptr_handle, NodePtr &parent_ptr, const uint8_t byte, + const GateStatus status) { NodePtr child_ptr; uint8_t remaining_byte; { - auto handle = DeleteChildInternal(art, node_ptr, byte); + auto handle = DeleteChildInternal(art, node_ptr_handle.Get(), byte); auto &n = handle.Get(); if (n.count != 1) { @@ -92,11 +93,12 @@ void Node4::DeleteChild(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const remaining_byte = n.key[0]; } - auto prev_node4_status = node_ptr.GetGateStatus(); - NodePtr::FreeNode(art, node_ptr); + auto prev_node4_status = node_ptr_handle.Get().GetGateStatus(); + NodePtr::FreeNode(art, node_ptr_handle.Get()); // Propagate both the prev_node_4 status and the general gate status (if the gate was earlier on), // since the concatenation logic depends on both. - Prefix::Concat(art, parent_ptr, node_ptr, child_ptr, remaining_byte, prev_node4_status, status); + PrefixHandle::Concat(art, parent_ptr, std::move(node_ptr_handle), child_ptr, remaining_byte, prev_node4_status, + status); } void Node4::ShrinkNode16(ART &art, NodePtr &node4_ptr, NodePtr &node16_ptr) { diff --git a/src/duckdb/src/execution/index/art/node.cpp b/src/duckdb/src/execution/index/art/node.cpp index 19e6ae1c2..b8f83dc3e 100644 --- a/src/duckdb/src/execution/index/art/node.cpp +++ b/src/duckdb/src/execution/index/art/node.cpp @@ -177,26 +177,26 @@ void NodePtr::InsertChild(ART &art, NodePtr &node_ptr, const uint8_t byte, const // Delete //===--------------------------------------------------------------------===// -void NodePtr::DeleteChild(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const uint8_t byte, const GateStatus status, - const ARTKey &row_id) { - D_ASSERT(node_ptr.HasMetadata()); +void NodePtr::DeleteChild(ART &art, NodePtrHandle node_ptr_handle, NodePtr &parent_ptr, const uint8_t byte, + const GateStatus status, const ARTKey &row_id) { + D_ASSERT(node_ptr_handle.Get().HasMetadata()); - auto type = node_ptr.GetType(); + auto type = node_ptr_handle.Get().GetType(); switch (type) { case NType::NODE_4: - return Node4::DeleteChild(art, node_ptr, parent_ptr, byte, status); + return Node4::DeleteChild(art, std::move(node_ptr_handle), parent_ptr, byte, status); case NType::NODE_16: - return Node16::DeleteChild(art, node_ptr, byte); + return Node16::DeleteChild(art, node_ptr_handle.Get(), byte); case NType::NODE_48: - return Node48::DeleteChild(art, node_ptr, byte); + return Node48::DeleteChild(art, node_ptr_handle.Get(), byte); case NType::NODE_256: - return Node256::DeleteChild(art, node_ptr, byte); + return Node256::DeleteChild(art, node_ptr_handle.Get(), byte); case NType::NODE_7_LEAF: - return Node7Leaf::DeleteByte(art, node_ptr, parent_ptr, byte, row_id); + return Node7Leaf::DeleteByte(art, std::move(node_ptr_handle), parent_ptr, byte, row_id); case NType::NODE_15_LEAF: - return Node15Leaf::DeleteByte(art, node_ptr, byte); + return Node15Leaf::DeleteByte(art, node_ptr_handle.Get(), byte); case NType::NODE_256_LEAF: - return Node256Leaf::DeleteByte(art, node_ptr, byte); + return Node256Leaf::DeleteByte(art, node_ptr_handle.Get(), byte); default: throw InternalException("Invalid node type for DeleteChild: %d.", type); } @@ -318,15 +318,16 @@ bool NodePtr::HasByte(const ART &art, const uint8_t byte) const { D_ASSERT(HasMetadata()); auto type = GetType(); + ConstNodeHandle handle(art, *this); switch (type) { case NType::NODE_7_LEAF: - return Ref(art, *this, NType::NODE_7_LEAF).HasByte(byte); + return handle.Get().HasByte(byte); case NType::NODE_15_LEAF: - return Ref(art, *this, NType::NODE_15_LEAF).HasByte(byte); + return handle.Get().HasByte(byte); case NType::NODE_256_LEAF: - return Ref(art, *this, NType::NODE_256_LEAF).HasByte(byte); + return handle.Get().HasByte(byte); default: - throw InternalException("Invalid node type for GetNextByte: %d.", type); + throw InternalException("Invalid node type for HasByte: %d.", type); } } diff --git a/src/duckdb/src/execution/index/art/node_handle.cpp b/src/duckdb/src/execution/index/art/node_handle.cpp index bf806d286..b05dc72b8 100644 --- a/src/duckdb/src/execution/index/art/node_handle.cpp +++ b/src/duckdb/src/execution/index/art/node_handle.cpp @@ -1,6 +1,8 @@ #include "duckdb/execution/index/art/node_handle.hpp" +#include "duckdb/common/exception.hpp" #include "duckdb/execution/index/art/node.hpp" +#include "duckdb/execution/index/art/prefix_handle.hpp" namespace duckdb { @@ -30,4 +32,58 @@ ConstNodeHandle::ConstNodeHandle(const ART &art, const NodePtr node_ptr) : handle(NodePtr::GetAllocator(art, node_ptr.GetType()).GetHandle(node_ptr)), type(node_ptr.GetType()) { } +NodePtrHandle::NodePtrHandle(NodePtr &node_ptr_p, optional handle_p) + : node_ptr(node_ptr_p), handle(std::move(handle_p)) { +} + +NodePtrHandle::NodePtrHandle(NodePtrHandle &&other) noexcept + : node_ptr(other.node_ptr), handle(std::move(other.handle)) { + other.Release(); +} + +NodePtrHandle &NodePtrHandle::operator=(NodePtrHandle &&other) noexcept { + if (this != &other) { + node_ptr = other.node_ptr; + handle = std::move(other.handle); + other.Release(); + } + return *this; +} + +NodePtrHandle NodePtrHandle::Unpinned(NodePtr &node_ptr) { + return NodePtrHandle(node_ptr, nullopt); +} + +NodePtrHandle NodePtrHandle::PrefixChild(const ART &art, NodeHandle &&prefix_handle) { + D_ASSERT(prefix_handle.GetType() == NType::PREFIX); + auto &child_ptr = PrefixHandle::ChildRef(art, prefix_handle); + return NodePtrHandle(child_ptr, std::move(prefix_handle)); +} + +optional NodePtrHandle::Child(NodeHandle &&node_handle, const uint8_t byte) { + auto child_ptr = NodePtr::GetChildMutable(node_handle, byte); + if (!child_ptr) { + return nullopt; + } + return NodePtrHandle(*child_ptr, std::move(node_handle)); +} + +NodePtr &NodePtrHandle::Get() { + return *node_ptr; +} + +void NodePtrHandle::Release() { + node_ptr = nullptr; + handle.reset(); +} + +NodeHandle NodePtrHandle::TakePin() && { + if (!handle) { + throw InternalException("NodePtrHandle::TakePin requires a pinned handle"); + } + NodeHandle pin(std::move(*handle)); + Release(); + return pin; +} + } // namespace duckdb diff --git a/src/duckdb/src/execution/index/art/prefix.cpp b/src/duckdb/src/execution/index/art/prefix.cpp index 2dd1a35a5..4feaeab20 100644 --- a/src/duckdb/src/execution/index/art/prefix.cpp +++ b/src/duckdb/src/execution/index/art/prefix.cpp @@ -68,34 +68,6 @@ void Prefix::New(ART &art, reference &node_ptr_ref, const ARTKey &key, } } -void Prefix::Concat(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, uint8_t byte, - const GateStatus node4_status, const GateStatus status) { - // We have four situations from which we enter here: - // 1: PREFIX (parent) - Node4 (prev_node4) - PREFIX (child) - INLINED_LEAF, or - // 2: PREFIX (parent) - Node4 (prev_node4) - INLINED_LEAF (child), or - // 3: INTERNAL_NODE (parent) - Node4 (prev_node4) - PREFIX (child) - INLINED_LEAF, or - // 4: INTERNAL_NODE (parent) - Node4 (prev_node4) - INLINED_LEAF (child). - - D_ASSERT(!parent_ptr.IsAnyLeaf()); - D_ASSERT(child_ptr.HasMetadata()); - - // The Node4 was a gate. - if (node4_status == GateStatus::GATE_SET) { - D_ASSERT(parent_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); - D_ASSERT(child_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); - ConcatNode4WasGate(art, node4_ptr, child_ptr, byte); - return; - } - - // The child is a gate. - if (child_ptr.GetGateStatus() == GateStatus::GATE_SET) { - D_ASSERT(node4_status == GateStatus::GATE_NOT_SET); - ConcatChildIsGate(art, parent_ptr, node4_ptr, child_ptr, byte); - return; - } - ConcatInternal(art, parent_ptr, node4_ptr, child_ptr, byte, status); -} - void Prefix::Reduce(ART &art, NodePtr &node_ptr, const idx_t pos) { D_ASSERT(node_ptr.HasMetadata()); D_ASSERT(pos < art.PrefixCount()); @@ -153,120 +125,6 @@ void Prefix::Append(ART &art, NodePtr other_ptr) { } } -Prefix Prefix::GetTail(ART &art, const NodePtr &node_ptr) { - Prefix prefix(art, node_ptr, true); - while (prefix.child_slot->GetType() == PREFIX) { - prefix = Prefix(art, *prefix.child_slot, true); - } - return prefix; -} - -void Prefix::ConcatInternal(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, uint8_t byte, - const GateStatus status) { - if (child_ptr.GetType() == NType::LEAF_INLINED) { - if (status == GateStatus::GATE_SET) { - if (parent_ptr.GetType() == NType::PREFIX) { - // The parent only contained the Node4, so we can now inline 'all the way up', - // and the gate is no longer nested. - while (parent_ptr.GetType() == NType::PREFIX) { - Prefix prefix(art, parent_ptr, true); - auto temp_ptr = *prefix.child_slot; - NodePtr::FreeNode(art, parent_ptr); - parent_ptr = temp_ptr; - } - parent_ptr = child_ptr; - return; - } - // The parent is any node inside the gate. - // Inside gates, inlined row IDs are not prefixed, - // so we directly inline into the previous Node4. - node4_ptr = child_ptr; - return; - } - - // Not inside a gate. - if (parent_ptr.GetType() == NType::PREFIX) { - // Append the byte to the prefix, and then inline the child. - auto tail = GetTail(art, parent_ptr); - tail = tail.Append(art, byte); - *tail.child_slot = child_ptr; - return; - } - - auto prefix = NewInternal(art, node4_ptr, &byte, 1, 0); - *prefix.child_slot = child_ptr; - return; - } - - // The child is not inlined. - if (parent_ptr.GetType() == NType::PREFIX) { - // Append the byte to the prefix. - auto tail = GetTail(art, parent_ptr); - tail = tail.Append(art, byte); - - // Append the child to the prefix. - if (child_ptr.GetType() == NType::PREFIX) { - tail.Append(art, child_ptr); - return; - } - *tail.child_slot = child_ptr; - return; - } - - // The child is not inlined, and the parent is not a prefix. - auto prefix = NewInternal(art, node4_ptr, &byte, 1, 0); - if (child_ptr.GetType() == NType::PREFIX) { - prefix.Append(art, child_ptr); - return; - } - *prefix.child_slot = child_ptr; -} - -void Prefix::ConcatNode4WasGate(ART &art, NodePtr &node4_ptr, const NodePtr child_ptr, uint8_t byte) { - D_ASSERT(child_ptr.HasMetadata()); - - if (child_ptr.GetType() == NType::LEAF_INLINED) { - // Inside gates, inlined row IDs are not prefixed. - // The child is inlined, so we inline into the previous Node4. - // There is no longer a nested leaf. - node4_ptr = child_ptr; - return; - } - - if (child_ptr.GetType() == PREFIX) { - // At least one more row ID in this gate and the child is a prefix. - // We create a new prefix of length one containing the remaining byte. - // Then, we append the child prefix. - auto prefix = NewInternal(art, node4_ptr, &byte, 1, 0); - prefix.child_slot->Clear(); - prefix.Append(art, child_ptr); - node4_ptr.SetGateStatus(GateStatus::GATE_SET); - return; - } - // At least one more row ID in this gate and the child is not a prefix. - // We create a new prefix of length one containing the remaining byte. - // then, we append the child. - auto prefix = NewInternal(art, node4_ptr, &byte, 1, 0); - *prefix.child_slot = child_ptr; - node4_ptr.SetGateStatus(GateStatus::GATE_SET); -} - -void Prefix::ConcatChildIsGate(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, - uint8_t byte) { - if (parent_ptr.GetType() != PREFIX) { - // Create a new prefix at the former position of the Node4, - // and point it to the gate. - auto prefix = NewInternal(art, node4_ptr, &byte, 1, 0); - *prefix.child_slot = child_ptr; - return; - } - - // The parent is a prefix (chain), so we need to append the byte to its tail. - auto tail = GetTail(art, parent_ptr); - tail = tail.Append(art, byte); - *tail.child_slot = child_ptr; -} - Prefix Prefix::TransformToDeprecatedAppend(ART &art, FixedSizeAllocator &allocator, uint8_t byte) { if (data[DEPRECATED_COUNT] != DEPRECATED_COUNT) { data[data[DEPRECATED_COUNT]] = byte; diff --git a/src/duckdb/src/execution/index/art/prefix_handle.cpp b/src/duckdb/src/execution/index/art/prefix_handle.cpp index 58ccbb8dc..0874e19ca 100644 --- a/src/duckdb/src/execution/index/art/prefix_handle.cpp +++ b/src/duckdb/src/execution/index/art/prefix_handle.cpp @@ -78,6 +78,68 @@ void PrefixHandle::Append(ART &art, PrefixHandle prefix, NodePtr other_ptr) { prefix.Child(art) = other_ptr; } +void PrefixHandle::Concat(ART &art, NodePtr &parent_ptr, NodePtrHandle node4_ptr_handle, const NodePtr child_ptr, + const uint8_t byte, const GateStatus node4_status, const GateStatus status) { + D_ASSERT(!parent_ptr.IsAnyLeaf()); + D_ASSERT(child_ptr.HasMetadata()); + + const auto node4_was_gate = node4_status == GateStatus::GATE_SET; + if (node4_was_gate) { + D_ASSERT(parent_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); + D_ASSERT(child_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); + } + + // Inside gates, inlined row IDs are not prefixed, so the byte is dropped. + if (child_ptr.GetType() == NType::LEAF_INLINED && (node4_was_gate || status == GateStatus::GATE_SET)) { + if (!node4_was_gate && parent_ptr.GetType() == PREFIX) { + // (PREFIX (gate) -> Node4 -> INLINED_LEAF) ==> (INLINED_LEAF) + // (INNER_NODE -> PREFIX -> Node4 -> INLINED_LEAF) ==> (INNER_NODE -> INLINED_LEAF) + // The freed chain stores the Node4's NodePtr, so release its pin first. + node4_ptr_handle.Release(); + while (parent_ptr.GetType() == PREFIX) { + NodePtr next_ptr; + { + // Release the handle before freeing its node, which may destroy the buffer. + PrefixHandle prefix(NodeHandle(art, parent_ptr)); + next_ptr = prefix.Child(art); + } + NodePtr::FreeNode(art, parent_ptr); + parent_ptr = next_ptr; + } + parent_ptr = child_ptr; + return; + } + // (INNER_NODE -> Node4 -> INLINED_LEAF) ==> (INNER_NODE -> INLINED_LEAF) + // (parent -> Node4 (gate) -> INLINED_LEAF) ==> (parent -> INLINED_LEAF) + node4_ptr_handle.Get() = child_ptr; + return; + } + + // X is a child that Append attaches without merging: an inlined leaf, an inner node, a leaf node, or a gate. + // PREFIX[c] is a child prefix chain, which Append merges up to the first gate. + // Bytes that do not fit into a prefix continue in a new prefix. + if (!node4_was_gate && parent_ptr.GetType() == PREFIX) { + // (PREFIX[a] -> Node4 -> X) ==> (PREFIX[a, byte] -> X) + // (PREFIX[a] -> Node4 -> PREFIX[c] -> X) ==> (PREFIX[a, byte, c] -> X) + // (PREFIX[full] -> Node4 -> X) ==> (PREFIX[full] -> PREFIX[byte] -> X) + // (PREFIX[full] -> Node4 -> PREFIX[c] -> X) ==> (PREFIX[full] -> PREFIX[byte, c] -> X) + // The Node4's NodePtr is stored in the tail of the parent's prefix chain, which its handle pins. + PrefixHandle tail(std::move(node4_ptr_handle).TakePin()); + Append(art, AppendByte(art, std::move(tail), byte), child_ptr); + return; + } + // (INNER_NODE -> Node4 -> X) ==> (INNER_NODE -> PREFIX[byte] -> X) + // (INNER_NODE -> Node4 -> PREFIX[c] -> X) ==> (INNER_NODE -> PREFIX[byte, c] -> X) + // (Node4 -> X) ==> (PREFIX[byte] -> X), at the root + // (Node4 -> PREFIX[c] -> X) ==> (PREFIX[byte, c] -> X), at the root + // (parent -> Node4 (gate) -> X) ==> (parent -> PREFIX[byte] (gate) -> X) + // (parent -> Node4 (gate) -> PREFIX[c] -> X) ==> (parent -> PREFIX[byte, c] (gate) -> X) + Append(art, NewInternal(art, node4_ptr_handle.Get(), &byte, 1, 0), child_ptr); + if (node4_was_gate) { + node4_ptr_handle.Get().SetGateStatus(GateStatus::GATE_SET); + } +} + NodePtr PrefixHandle::Split(ART &art, NodePtr &prefix_ptr, NodePtr &branching_node4_ptr, const uint8_t pos) { D_ASSERT(prefix_ptr.HasMetadata()); D_ASSERT(prefix_ptr.GetType() == PREFIX); diff --git a/src/duckdb/src/execution/index/bound_index.cpp b/src/duckdb/src/execution/index/bound_index.cpp index 813d092a6..377fe2f51 100644 --- a/src/duckdb/src/execution/index/bound_index.cpp +++ b/src/duckdb/src/execution/index/bound_index.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/attached_database.hpp" #include "duckdb/execution/index/bound_index.hpp" #include "duckdb/common/array.hpp" @@ -22,7 +23,7 @@ BoundIndex::BoundIndex(const Identifier &name, const string &index_type, IndexCo const vector &column_ids, TableIOManager &table_io_manager, const vector> &unbound_expressions_p, AttachedDatabase &db) : Index(column_ids, table_io_manager, db), name(name), index_type(index_type), - index_constraint_type(index_constraint_type) { + index_constraint_type(index_constraint_type), executor(db.GetDatabase()) { for (auto &expr : unbound_expressions_p) { types.push_back(expr->GetReturnType().InternalType()); logical_types.push_back(expr->GetReturnType()); @@ -269,6 +270,9 @@ void BoundIndex::ApplyBufferedReplays(const vector &table_types, Bu IndexAppendInfo append_info(IndexAppendMode::INSERT_DUPLICATES, nullptr); const auto error = Append(table_chunk, row_ids, append_info); if (error.HasError()) { + if (error.Type() != ExceptionType::CONSTRAINT) { + error.Throw(); + } throw InternalException("error while applying buffered appends: " + error.Message()); } current_row += rows_to_process; diff --git a/src/duckdb/src/execution/index/fixed_size_buffer.cpp b/src/duckdb/src/execution/index/fixed_size_buffer.cpp index f9052f29c..6712e5d69 100644 --- a/src/duckdb/src/execution/index/fixed_size_buffer.cpp +++ b/src/duckdb/src/execution/index/fixed_size_buffer.cpp @@ -104,7 +104,9 @@ shared_ptr FixedSizeBuffer::Persist(PartialBlockManager &partia auto result = make_shared_ptr(block_manager, segment_count, new_allocation_size); auto new_block_pointer = partial_block_manager.Write(*result, buffer_handle, NumericCast(new_allocation_size)); - D_ASSERT(new_block_pointer); + if (!new_block_pointer) { + throw InternalException("failed to write FixedSizeBuffer to a partial block"); + } // Checkpoint metadata is collected before shared partial blocks are flushed. result->block_pointer = *new_block_pointer; result->block_handle = block_manager.RegisterBlock(new_block_pointer->block_id, MemoryTag::BASE_TABLE); @@ -134,6 +136,7 @@ void FixedSizeBuffer::LoadFromDisk() { auto new_buffer_handle = buffer_manager.Allocate(MemoryTag::ART_INDEX, &block_manager, false); new_block_handle = new_buffer_handle.GetBlockHandle(); memcpy(new_buffer_handle.GetDataMutable(), pinned_buffer_handle.Ptr() + block_pointer.offset, allocation_size); + memset(new_buffer_handle.GetDataMutable() + allocation_size, 0, block_size - allocation_size); buffer_handle = std::move(new_buffer_handle); block_handle = std::move(new_block_handle); diff --git a/src/duckdb/src/execution/index/unbound_index.cpp b/src/duckdb/src/execution/index/unbound_index.cpp index 2e7996a8e..567fc5955 100644 --- a/src/duckdb/src/execution/index/unbound_index.cpp +++ b/src/duckdb/src/execution/index/unbound_index.cpp @@ -2,11 +2,13 @@ #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/execution/index/bound_index.hpp" +#include "duckdb/main/attached_database.hpp" #include "duckdb/parser/parsed_data/create_index_info.hpp" #include "duckdb/planner/expression_binder/index_binder.hpp" #include "duckdb/storage/block_manager.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/index_storage_info.hpp" +#include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table_io_manager.hpp" #include "duckdb/storage/checkpoint/table_index_writer.hpp" @@ -56,6 +58,10 @@ void UnboundIndex::ResetStorage() { } IndexCheckpointResult UnboundIndex::Checkpoint(PartialBlockManager &, StorageVersion) { + if (HasBufferedReplays()) { + throw InternalException("Cannot checkpoint index %s: it has buffered operations that were not applied", + GetIndexName()); + } return {storage_info, nullptr}; } @@ -79,6 +85,8 @@ unique_ptr UnboundIndex::Bind(IndexBinder &binder, const vector types; diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index 8a90f5c0b..0f85ed5b4 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -11,6 +11,7 @@ #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/mark_join_row_comparison.hpp" #include "duckdb/execution/operator/join/physical_hash_join.hpp" +#include "duckdb/execution/perfect_hash_join_table.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -25,17 +26,40 @@ using ScanStructure = JoinHashTable::ScanStructure; using ProbeSpill = JoinHashTable::ProbeSpill; using ProbeSpillLocalState = JoinHashTable::ProbeSpillLocalAppendState; +const buffer_ptr &DictionaryOwnershipCache::GetEntry(idx_t column, + const buffer_ptr &entry) { + D_ASSERT(column < column_count); + if (!entries) { + entries = make_uniq_array>(column_count); + } + auto &local_entry = entries[column]; + if (local_entry.get() != entry.get()) { + auto owner = make_shared_ptr(entry); + local_entry = buffer_ptr(owner, entry.get()); + } + return local_entry; +} + +void DictionaryOwnershipCache::Reset() { + if (!entries) { + return; + } + for (idx_t i = 0; i < column_count; i++) { + entries[i].reset(); + } +} + JoinHashTable::SharedState::SharedState() : salt_v(LogicalType::UBIGINT), keys_to_compare_sel(STANDARD_VECTOR_SIZE), keys_no_match_sel(STANDARD_VECTOR_SIZE) { } JoinHashTable::ProbeState::ProbeState() - : SharedState(), ht_offsets_and_salts_v(LogicalType::UBIGINT), hashes_dense_v(LogicalType::HASH), - non_empty_sel(STANDARD_VECTOR_SIZE) { + : SharedState(), hashes(LogicalType::HASH), ht_offsets_and_salts_v(LogicalType::UBIGINT), + hashes_dense_v(LogicalType::HASH), non_empty_sel(STANDARD_VECTOR_SIZE) { } JoinHashTable::ProbeDictionaryState::ProbeDictionaryState() - : hashes(LogicalType::HASH), new_dictionary_pointers(LogicalType::POINTER), unique_entries(STANDARD_VECTOR_SIZE), + : new_dictionary_pointers(LogicalType::POINTER), unique_entries(STANDARD_VECTOR_SIZE), match_sel(STANDARD_VECTOR_SIZE) { } @@ -106,6 +130,14 @@ void JoinHashTable::FinishInitWithLayout(shared_ptr published_l layout_ptr = std::move(published_layout); D_ASSERT(!dict_info_p || dict_info_p->columns.size() == build_types.size()); 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() + ? PerfectHashJoinTable::Type::BITMAP + : PerfectHashJoinTable::Type::ROWS; + perfect_hash_candidate = + PerfectHashJoinTable::Create(equality_types[0].InternalType(), type, null_values_are_equal[0]); + } // Initialize the row matcher that are used for filtering during the probing only if there are non-equality preds if (!non_equality_predicates.empty()) { @@ -158,6 +190,10 @@ void JoinHashTable::Merge(JoinHashTable &other) { { lock_guard guard(data_lock); data_collection->Combine(*other.data_collection); + if (perfect_hash_candidate) { + D_ASSERT(other.perfect_hash_candidate); + perfect_hash_candidate->MergeBounds(*other.perfect_hash_candidate); + } } if (join_type == JoinType::MARK) { @@ -377,15 +413,24 @@ inline bool JoinHashTable::UseSalt() const { return this->capacity > USE_SALT_THRESHOLD; } -void JoinHashTable::GetRowPointers(DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, Vector &hashes_v, - optional_ptr sel, idx_t &count, Vector &pointers_result_v, - SelectionVector &match_sel, const bool has_sel) { +void JoinHashTable::GetRowPointers(DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, + optional_ptr precomputed_hashes, optional_ptr sel, + idx_t &count, Vector &pointers_result_v, SelectionVector &match_sel, + const bool has_sel) { + if (perfect_hash_table) { + perfect_hash_table->GetRowPointers(keys.data[0], sel, count, pointers_result_v, match_sel); + return; + } + auto &hashes = precomputed_hashes ? *precomputed_hashes : state.hashes; + if (!precomputed_hashes) { + Hash(keys, sel ? *sel : *FlatVector::IncrementalSelectionVector(), count, hashes); + } auto entries = GetEntries(); if (UseSalt()) { - GetRowPointersInternal(keys, key_state, state, hashes_v, sel, count, *this, entries, pointers_result_v, + GetRowPointersInternal(keys, key_state, state, hashes, sel, count, *this, entries, pointers_result_v, match_sel, has_sel); } else { - GetRowPointersInternal(keys, key_state, state, hashes_v, sel, count, *this, entries, pointers_result_v, + GetRowPointersInternal(keys, key_state, state, hashes, sel, count, *this, entries, pointers_result_v, match_sel, has_sel); } } @@ -503,7 +548,7 @@ bool JoinHashTable::ColumnReferencedByResidual(idx_t build_col_idx) const { uint8_t JoinHashTable::GetDictSurvivingIndexWidth(idx_t build_col_idx, const Vector &incoming) const { const auto &type = build_types[build_col_idx]; - // Vector::Dictionary rejects nested types + // Keep nested payloads in the regular row layout. switch (type.InternalType()) { case PhysicalType::STRUCT: case PhysicalType::LIST: @@ -645,6 +690,9 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu if (keys.size() == 0) { return; } + if (perfect_hash_candidate) { + perfect_hash_candidate->UpdateBounds(keys.data[0]); + } // special case: correlated mark join if (join_type == JoinType::MARK && !mark_join_info.correlated_types.empty()) { auto &info = mark_join_info; @@ -772,6 +820,19 @@ static data_ptr_t LoadPointer(const const_data_ptr_t &source) { return cast_uint64_to_pointer(Load(source)); } +//! Load an entry that another thread may be inserting into at the same time. The MSVC STL implements the 8-byte +//! atomic load on 32-bit x86 with __iso_volatile_load64, which clang-cl lowers to two 32-bit moves, so a plain load +//! there can observe a half-written entry. The compare-exchange is one read-modify-write that preserves the value. +static inline ht_entry_t LoadEntryConcurrent(atomic &entry) { +#if defined(_MSC_VER) && defined(_M_IX86) + ht_entry_t expected; + entry.compare_exchange_strong(expected, expected, std::memory_order_acquire, std::memory_order_acquire); + return expected; +#else + return entry.load(std::memory_order_acquire); +#endif +} + //! If we consider to insert into an entry we expect to be empty, if it was filled in the meantime the insert will not //! happen and we need to return the pointer to the to row with which the new entry would have collided. In any other //! case we return a nullptr @@ -793,7 +854,7 @@ static inline data_ptr_t InsertRowToEntry(atomic &entry, const data_ return expected_entry.GetPointerOrNull(); } else { // At this point we know that the keys match, so we can try to insert until we succeed - ht_entry_t expected_entry = entry.load(std::memory_order_acquire); + ht_entry_t expected_entry = LoadEntryConcurrent(entry); D_ASSERT(expected_entry.IsOccupied()); do { data_ptr_t current_row_pointer = expected_entry.GetPointer(); @@ -807,7 +868,7 @@ static inline data_ptr_t InsertRowToEntry(atomic &entry, const data_ // If we are not in parallel mode, we can just do the operation without any checks data_ptr_t current_row_pointer = entry.load(std::memory_order_relaxed).GetPointerOrNull(); StorePointer(current_row_pointer, row_ptr_to_insert + pointer_offset); - entry = desired_entry; + entry.store(desired_entry, std::memory_order_relaxed); return nullptr; } } @@ -954,7 +1015,7 @@ static void InsertHashesLoop(unsafe_optional_ptr> entries, Ve bool occupied; while (true) { atomic &atomic_entry = entries.get()[ht_offset]; - entry = atomic_entry.load(std::memory_order_acquire); + entry = PARALLEL ? LoadEntryConcurrent(atomic_entry) : atomic_entry.load(std::memory_order_relaxed); occupied = entry.IsOccupied(); // condition for incrementing the ht_offset: occupied and row_salt does not match -> move to next entry @@ -1026,54 +1087,180 @@ void JoinHashTable::InsertHashes(Vector &hashes_v, TupleDataChunkState &chunk_st } } -unique_ptr JoinHashTable::InitializePrefixRangeBuildState() { - D_ASSERT(prefix_range_filter); - return prefix_range_filter->InitializeBuildState(context); +JoinHashTable::PrefixRangeBuildStates JoinHashTable::InitializePrefixRangeBuildState() { + D_ASSERT(ShouldBuildPrefixRangeFilter()); + PrefixRangeBuildStates states(prefix_range_filters.size()); + for (idx_t key_idx = 0; key_idx < prefix_range_filters.size(); key_idx++) { + if (prefix_range_filters[key_idx]) { + states[key_idx] = prefix_range_filters[key_idx]->InitializeBuildState(context); + } + } + return states; } idx_t JoinHashTable::GetPrefixRangeBuildStateSize() const { - D_ASSERT(prefix_range_filter); - return prefix_range_filter->GetBuildStateSize(); + D_ASSERT(ShouldBuildPrefixRangeFilter()); + idx_t size = 0; + for (auto &filter : prefix_range_filters) { + if (filter) { + size += filter->GetBuildStateSize(); + } + } + return size; } -void JoinHashTable::BuildPrefixRangeFilter() { - if (!ShouldBuildPrefixRangeFilter()) { +void JoinHashTable::SetBuildBloomFilter(idx_t key_idx) { + if (HasSingleEqualityKey()) { + D_ASSERT(key_idx == 0); + should_build_bloom_filter = true; return; } + should_build_key_bloom_filters.resize(equality_predicate_columns.size(), false); + should_build_key_bloom_filters[key_idx] = true; +} - auto prefix_range_state = InitializePrefixRangeBuildState(); - TupleDataChunkIterator iterator(*data_collection, TupleDataPinProperties::KEEP_EVERYTHING_PINNED, 0, - data_collection->ChunkCount(), false); - do { - const auto count = iterator.GetCurrentChunkCount(); - if (count == 0) { - continue; +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; +} + +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); } - InsertPrefixRangeChunk(iterator.GetChunkState(), count, *prefix_range_state); - } while (iterator.Next()); - MergePrefixRangeBuildState(*prefix_range_state); + } } -void JoinHashTable::InsertPrefixRangeChunk(TupleDataChunkState &chunk_state, idx_t count, - PrefixRangeFilter::BuildState &state, bool parallel) { - D_ASSERT(prefix_range_filter); - Vector build_keys(layout_ptr->GetTypes()[0], count); +bool JoinHashTable::HasPublishableBloomFilter(idx_t key_idx) const { + if (HasSingleEqualityKey()) { + D_ASSERT(key_idx == 0); + return HasPublishableBloomFilter(); + } + if (key_idx >= key_bloom_filters.size()) { + return false; + } + auto &filter = key_bloom_filters[key_idx]; + return filter && filter->IsSealed() && filter->IsUseful(); +} + +bool JoinHashTable::ShouldBuildPrefixRangeFilter() const { + if (!should_build_prefix_range_filter) { + return false; + } + for (auto &filter : prefix_range_filters) { + if (filter) { + return true; + } + } + return false; +} + +void JoinHashTable::GatherKeyColumn(TupleDataChunkState &chunk_state, idx_t count, idx_t key_idx, Vector &result) { auto &sel = *FlatVector::IncrementalSelectionVector(); - data_collection->Gather(chunk_state.row_locations, sel, count, 0, build_keys, sel, nullptr); - FlatVector::SetSize(build_keys, count_t(count)); - if (parallel) { - prefix_range_filter->InsertKeysParallel(build_keys, state); - } else { - prefix_range_filter->InsertKeys(build_keys, state); + data_collection->Gather(chunk_state.row_locations, sel, count, key_idx, result, sel, nullptr); + FlatVector::SetSize(result, count_t(count)); +} + +void JoinHashTable::InsertPrefixRangeChunk(TupleDataChunkState &chunk_state, idx_t count, + PrefixRangeBuildStates &states, KeyFilterBuildScratch &scratch, + bool parallel) { + D_ASSERT(states.size() == prefix_range_filters.size()); + scratch.keys.Reset(); + for (idx_t key_idx = 0; key_idx < prefix_range_filters.size(); key_idx++) { + auto &filter = prefix_range_filters[key_idx]; + if (!filter) { + continue; + } + auto &build_keys = scratch.keys.data[key_idx]; + GatherKeyColumn(chunk_state, count, key_idx, build_keys); + if (parallel) { + filter->InsertKeysParallel(build_keys, *states[key_idx]); + } else { + filter->InsertKeys(build_keys, *states[key_idx]); + } + } +} + +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]); + } + } +} + +JoinHashTable::KeyFilterBuildScratch::KeyFilterBuildScratch(JoinHashTable &ht) : hashes(LogicalType::HASH) { + vector types; + for (idx_t key_idx = 0; key_idx < ht.equality_predicate_columns.size(); key_idx++) { + types.push_back(ht.layout_ptr->GetTypes()[key_idx]); } + keys.Initialize(ht.context, types); } -void JoinHashTable::MergePrefixRangeBuildState(PrefixRangeFilter::BuildState &state) { - D_ASSERT(prefix_range_filter); - prefix_range_filter->MergeBuildState(state); +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]; + if (!filter || filter->IsSealed()) { + continue; + } + auto &build_keys = scratch.keys.data[key_idx]; + GatherKeyColumn(chunk_state, count, key_idx, build_keys); + VectorOperations::Hash(build_keys, scratch.hashes, count); + filter->InsertHashes(scratch.hashes, *FlatVector::IncrementalSelectionVector(), count); + } +} + +bool JoinHashTable::TryInitializePerfectHashTable() { + D_ASSERT(!perfect_hash_table); + auto candidate = std::move(perfect_hash_candidate); + if (candidate && candidate->Initialize(buffer_manager.GetBufferAllocator(), Count(), PointerTableSize(Count()))) { + perfect_hash_table = std::move(candidate); + } + string backend = "hash"; + if (perfect_hash_table) { + switch (perfect_hash_table->GetType()) { + case PerfectHashJoinTable::Type::BITMAP: + backend = "bitmap"; + break; + case PerfectHashJoinTable::Type::ROWS: + backend = "direct"; + break; + case PerfectHashJoinTable::Type::DICTIONARY: + throw InternalException("Dictionary lookup must be initialized from row pointers"); + } + } + DUCKDB_LOG(context, PhysicalOperatorLogType, op, "PhysicalHashJoin", "Lookup", {{"backend", backend}}); + 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(); + capacity = perfect_hash_table->EntryCount(); + bucket_shift = 0; + } else { + AllocateHashMap(use_radix_layout); + } + DUCKDB_LOG(context, PhysicalOperatorLogType, op, "JoinHashTable", "Build", + {{"rows", to_string(data_collection->Count())}, + {"size", to_string(data_collection->SizeInBytes() + capacity * sizeof(uint64_t))}}); +} + +void JoinHashTable::AllocateHashMap(bool use_radix_layout) { capacity = PointerTableCapacity(Count()); D_ASSERT(IsPowerOfTwo(capacity)); @@ -1087,6 +1274,15 @@ void JoinHashTable::AllocatePointerTable(bool use_radix_layout) { bloom_filter = recycled_bloom_filter ? std::move(recycled_bloom_filter) : make_shared_ptr(); bloom_filter->Initialize(context, MaxValue(Count(), 1)); } + 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); + } + } if (hash_map.get()) { // There is already a hash map @@ -1108,42 +1304,71 @@ void JoinHashTable::AllocatePointerTable(bool use_radix_layout) { const auto capacity_bits = RadixPartitioning::RadixBitsOfPowerOfTwo(capacity); bucket_shift = use_radix_layout && radix_bits > 0 && capacity_bits >= radix_bits ? RadixPartitioning::Shift(capacity_bits) : 0; - - DUCKDB_LOG(context, PhysicalOperatorLogType, op, "JoinHashTable", "Build", - {{"rows", to_string(data_collection->Count())}, - {"size", to_string(data_collection->SizeInBytes() + hash_map.GetSize())}}); } void JoinHashTable::InitializePointerTable(idx_t entry_idx_from, idx_t entry_idx_to) { + if (perfect_hash_table) { + perfect_hash_table->InitializeEntries(entry_idx_from, entry_idx_to); + return; + } // 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()); } void JoinHashTable::Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool parallel, - optional_ptr prefix_range_state, - bool prefix_range_parallel) { + optional_ptr prefix_range_states, bool prefix_range_parallel) { // Pointer table should be allocated - D_ASSERT(hash_map.get()); - - Vector hashes(LogicalType::HASH); + D_ASSERT(hash_map.get() || perfect_hash_table); TupleDataChunkIterator iterator(*data_collection, TupleDataPinProperties::KEEP_EVERYTHING_PINNED, chunk_idx_from, chunk_idx_to, false); - const auto row_locations = iterator.GetRowLocations(); + if (perfect_hash_table) { + // Perfect hash joins have a single key and no per-key Bloom filters. + D_ASSERT(key_bloom_filters.empty()); + unique_ptr key_filter_scratch; + if (prefix_range_states) { + key_filter_scratch = make_uniq(*this); + } + bool has_chains = false; + do { + auto &chunk_state = iterator.GetChunkState(); + 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, + *key_filter_scratch, prefix_range_parallel); + } + } while (iterator.Next()); + if (has_chains) { + chains_longer_than_one.store(true, std::memory_order_relaxed); + } + return; + } + const auto row_locations = iterator.GetRowLocations(); + Vector hashes(LogicalType::HASH); InsertState insert_state(*this); + unique_ptr key_filter_scratch; + if (!key_bloom_filters.empty() || prefix_range_states) { + key_filter_scratch = make_uniq(*this); + } do { const auto count = iterator.GetCurrentChunkCount(); - auto hash_data = FlatVector::Writer(hashes, count_t(count)); - for (idx_t i = 0; i < count; i++) { - hash_data.WriteValue(Load(row_locations[i] + pointer_offset)); - } TupleDataChunkState &chunk_state = iterator.GetChunkState(); + { + auto hash_data = FlatVector::Writer(hashes, count_t(count)); + for (idx_t i = 0; i < count; i++) { + hash_data.WriteValue(Load(row_locations[i] + pointer_offset)); + } + } InsertHashes(hashes, chunk_state, insert_state, parallel); - if (prefix_range_state) { - InsertPrefixRangeChunk(chunk_state, count, *prefix_range_state, prefix_range_parallel); + if (!key_bloom_filters.empty()) { + InsertKeyBloomFilterChunk(chunk_state, count, *key_filter_scratch); + } + if (prefix_range_states) { + InsertPrefixRangeChunk(chunk_state, count, *prefix_range_states, *key_filter_scratch, + prefix_range_parallel); } } while (iterator.Next()); } @@ -1185,10 +1410,40 @@ static bool LHSChunkIsConstant(const Vector &lhs_key) { return lhs_key.GetVectorType() == VectorType::CONSTANT_VECTOR; } +bool JoinHashTable::TryProbePerfectHashTable(ScanStructure &scan_structure, DataChunk &keys) { + if (!perfect_hash_table) { + return false; + } + switch (perfect_hash_table->GetType()) { + case PerfectHashJoinTable::Type::ROWS: + return false; + case PerfectHashJoinTable::Type::DICTIONARY: + if (!scan_structure.dictionary_selection) { + scan_structure.dictionary_selection = make_uniq(STANDARD_VECTOR_SIZE); + } + scan_structure.is_null = false; + scan_structure.finished = false; + scan_structure.count = perfect_hash_table->ProbeDictionary(keys.data[0], scan_structure.sel_vector, + *scan_structure.dictionary_selection); + scan_structure.local_probe_matches += scan_structure.count; + return true; + case PerfectHashJoinTable::Type::BITMAP: + scan_structure.is_null = false; + scan_structure.finished = false; + scan_structure.count = 0; + scan_structure.local_probe_matches += + perfect_hash_table->ProbeMembership(keys.data[0], scan_structure.found_match); + return true; + } + return false; +} + void JoinHashTable::Probe(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state, optional_ptr precomputed_hashes) { - // dispatch into the compressed-vector fast paths when the operator gated them on. precomputed_hashes - // is incompatible: the caller hashed the full N-row chunk; the fast paths re-hash a sliced D-row chunk. + 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]; if (LHSChunkIsConstant(lhs_key) && TryProbeConstant(scan_structure, keys, key_state, probe_state)) { @@ -1204,18 +1459,8 @@ void JoinHashTable::Probe(ScanStructure &scan_structure, DataChunk &keys, TupleD if (scan_structure.count == 0) { return; } - if (precomputed_hashes) { - GetRowPointers(keys, key_state, probe_state, *precomputed_hashes, current_sel, scan_structure.count, - scan_structure.pointers, scan_structure.sel_vector, scan_structure.has_null_value_filter); - } else { - Vector hashes(LogicalType::HASH); - // hash all the keys - Hash(keys, *current_sel, scan_structure.count, hashes); - - // now initialize the pointers of the scan structure based on the hashes - GetRowPointers(keys, key_state, probe_state, hashes, current_sel, scan_structure.count, scan_structure.pointers, - scan_structure.sel_vector, scan_structure.has_null_value_filter); - } + GetRowPointers(keys, key_state, probe_state, precomputed_hashes, current_sel, scan_structure.count, + scan_structure.pointers, scan_structure.sel_vector, scan_structure.has_null_value_filter); } bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, @@ -1314,11 +1559,8 @@ bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk TupleDataCollection::ToUnifiedFormat(dict_state.unique_key_state, unique_values); - auto &hashes = dict_state.hashes; - VectorOperations::Hash(unique_values.data[0], hashes, unique_count); - idx_t count = unique_count; - GetRowPointers(unique_values, dict_state.unique_key_state, probe_state, hashes, nullptr, 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 @@ -1392,13 +1634,9 @@ bool JoinHashTable::TryProbeConstant(ScanStructure &scan_structure, DataChunk &k TupleDataCollection::ToUnifiedFormat(dict_state.unique_key_state, unique_values); - auto &hashes = dict_state.hashes; - VectorOperations::Hash(unique_values.data[0], hashes, 1); - - // resolved_ptr is a chain-head, not a confirmed match - a real key-miss is still rejected by - // the chain walk in Next(). A NULL constant key resolves correctly via RowMatcher null equality. + // Resolve the equality chain; Next() checks any additional predicates. idx_t count = 1; - GetRowPointers(unique_values, dict_state.unique_key_state, probe_state, hashes, nullptr, count, + 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]; @@ -1434,7 +1672,7 @@ ScanStructure::ScanStructure(JoinHashTable &ht_p, TupleDataChunkState &key_state chain_match_sel_vector(STANDARD_VECTOR_SIZE), chain_no_match_sel_vector(STANDARD_VECTOR_SIZE), found_match(make_unsafe_uniq_array_uninitialized(STANDARD_VECTOR_SIZE)), ht(ht_p), finished(false), is_null(true), rhs_pointers(LogicalType::POINTER), lhs_sel_vector(STANDARD_VECTOR_SIZE), last_match_count(0), - last_sel_vector(STANDARD_VECTOR_SIZE) { + last_sel_vector(STANDARD_VECTOR_SIZE), dictionary_gather_state(ht.output_columns.size()) { if (ht.residual_predicate) { residual_executor = make_uniq(ht.context); residual_executor->AddExpression(*ht.residual_predicate); @@ -1476,6 +1714,7 @@ ScanStructure::ScanStructure(JoinHashTable &ht_p, TupleDataChunkState &key_state } void ScanStructure::Reset() { + dictionary_gather_state.Reset(); count = 0; finished = false; is_null = true; @@ -1489,9 +1728,14 @@ void ScanStructure::Next(DataChunk &keys, DataChunk &probe_data, DataChunk &resu if (finished) { return; } - switch (ht.join_type) { case JoinType::INNER: + if (ht.UsesDictionaryLookup()) { + NextDictionaryJoin(probe_data, result); + } else { + NextInnerJoin(keys, probe_data, result); + } + break; case JoinType::RIGHT: NextInnerJoin(keys, probe_data, result); break; @@ -1697,12 +1941,41 @@ void ScanStructure::GatherResult(Vector &result, const idx_t count, const idx_t *FlatVector::IncrementalSelectionVector(), nullptr); } +static bool HasNestedDictionary(const vector> &dictionaries) { + for (const auto &entry : dictionaries) { + if (entry->data.GetType().IsNested()) { + return true; + } + } + return false; +} + +static bool SelectionCoversDictionary(const data_ptr_t *row_ptrs, const SelectionVector &ptr_sel, idx_t count, + idx_t pointer_offset, idx_t dictionary_size) { + D_ASSERT(dictionary_size <= STANDARD_VECTOR_SIZE); + if (count < dictionary_size) { + return false; + } + validity_t selected_entries[ValidityMask::STANDARD_ENTRY_COUNT] = {}; + ValidityMask selected(selected_entries, STANDARD_VECTOR_SIZE); + for (idx_t i = 0; i < count; i++) { + const auto dictionary_idx = Load(row_ptrs[ptr_sel.get_index(i)] + pointer_offset); + D_ASSERT(dictionary_idx < dictionary_size); + selected.SetValid(dictionary_idx); + } + return selected.CheckAllValid(dictionary_size); +} + void JoinHashTable::GatherRHS(Vector &row_ptrs, const SelectionVector &ptr_sel, const idx_t count, DataChunk &result, - idx_t rhs_col_offset) const { + idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const { if (use_dict_emission) { const auto ptrs = FlatVector::GetData(row_ptrs); - EmitDictVectors(ptrs, ptr_sel, count, result, rhs_col_offset); - return; + // 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); + return; + } } const auto &result_sel = *FlatVector::IncrementalSelectionVector(); const auto ptrs = FlatVector::GetData(row_ptrs); @@ -1722,7 +1995,8 @@ void JoinHashTable::GatherRHS(Vector &row_ptrs, const SelectionVector &ptr_sel, 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); - vector.Dictionary(dict_column->entry, build_sel_vec, count); + const auto &entry = dictionary_state.GetEntry(col_idx, dict_column->entry); + vector.Dictionary(entry, build_sel_vec, count); continue; } } @@ -1762,6 +2036,30 @@ void ScanStructure::UpdateCompactionBuffer(idx_t base_count, SelectionVector &re VectorOperations::Copy(pointers, rhs_pointers, result_vector, result_count, 0, base_count); } +void ScanStructure::ProjectProbeColumns(DataChunk &probe_data, const SelectionVector &sel, idx_t count, + DataChunk &result, bool full_identity) { + for (idx_t i = 0; i < ht.lhs_output_in_probe.size(); i++) { + idx_t probe_col_idx = ht.lhs_output_in_probe[i]; + if (full_identity) { + result.data[i].Reference(probe_data.data[probe_col_idx]); + } else { + result.data[i].Slice(probe_data.data[probe_col_idx], sel, count); + } + } +} + +void ScanStructure::NextDictionaryJoin(DataChunk &probe_data, DataChunk &result) { + D_ASSERT(ht.join_type == JoinType::INNER && ht.use_dict_emission); + 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()); + ht.EmitDictVectors(*dictionary_selection, count, result, ht.lhs_output_in_probe.size(), + dictionary_gather_state); + } + count = 0; + finished = true; +} + void ScanStructure::NextInnerJoin(DataChunk &keys, DataChunk &probe_data, DataChunk &result) { if (ht.join_type != JoinType::RIGHT_SEMI && ht.join_type != JoinType::RIGHT_ANTI) { D_ASSERT(result.ColumnCount() == ht.lhs_output_in_probe.size() + ht.output_columns.size()); @@ -1805,16 +2103,10 @@ void ScanStructure::NextInnerJoin(DataChunk &keys, DataChunk &probe_data, DataCh // extract only OUTPUT columns from probe_data const auto full_identity = SelectionIsFullIdentity(chain_match_sel_vector, result_count, probe_data.size()); - for (idx_t i = 0; i < ht.lhs_output_in_probe.size(); i++) { - idx_t probe_col_idx = ht.lhs_output_in_probe[i]; - if (full_identity) { - result.data[i].Reference(probe_data.data[probe_col_idx]); - } else { - result.data[i].Slice(probe_data.data[probe_col_idx], chain_match_sel_vector, result_count); - } - } + ProjectProbeColumns(probe_data, chain_match_sel_vector, result_count, result, full_identity); // on the RHS, we need to fetch the data from the hash table - ht.GatherRHS(pointers, chain_match_sel_vector, result_count, result, ht.lhs_output_in_probe.size()); + ht.GatherRHS(pointers, chain_match_sel_vector, result_count, result, ht.lhs_output_in_probe.size(), + dictionary_gather_state); AdvancePointers(); return; @@ -1831,17 +2123,10 @@ void ScanStructure::NextInnerJoin(DataChunk &keys, DataChunk &probe_data, DataCh if (base_count > 0) { // extract only OUTPUT columns from probe_data using compaction buffer const auto full_identity = SelectionIsFullIdentity(lhs_sel_vector, base_count, probe_data.size()); - for (idx_t i = 0; i < ht.lhs_output_in_probe.size(); i++) { - idx_t probe_col_idx = ht.lhs_output_in_probe[i]; - if (full_identity) { - result.data[i].Reference(probe_data.data[probe_col_idx]); - } else { - result.data[i].Slice(probe_data.data[probe_col_idx], lhs_sel_vector, base_count); - } - } + ProjectProbeColumns(probe_data, lhs_sel_vector, base_count, result, full_identity); // 2) gather RHS vectors ht.GatherRHS(rhs_pointers, *FlatVector::IncrementalSelectionVector(), base_count, result, - ht.lhs_output_in_probe.size()); + ht.lhs_output_in_probe.size(), dictionary_gather_state); } } @@ -2245,17 +2530,16 @@ void ScanStructure::NextSingleJoin(DataChunk &keys, DataChunk &probe_data, DataC // advance pointers for those rows AdvancePointers(result_sel, result_count); - // now resolve the predicates - idx_t match_count = ResolvePredicates(keys, probe_data, chain_match_sel_vector, nullptr); - if (match_count > 0) { - // we found at least one duplicate row - throw - throw InvalidInputException( - "More than one row returned by a subquery used as an expression - scalar subqueries can only " - "return a single row.\n\nUse \"SET scalar_subquery_error_on_multiple_rows=false\" to revert to " - "previous behavior of returning a random row."); + while (this->count > 0) { + idx_t match_count = ResolvePredicates(keys, probe_data, chain_match_sel_vector, nullptr); + if (match_count > 0) { + throw InvalidInputException( + "More than one row returned by a subquery used as an expression - scalar subqueries can only " + "return a single row.\n\nUse \"SET scalar_subquery_error_on_multiple_rows=false\" to revert to " + "previous behavior of returning a random row."); + } + AdvancePointers(); } - - this->count = 0; } } @@ -2360,7 +2644,7 @@ void JoinHashTable::ScanFullOuter(JoinHTScanState &state, Vector &addresses, Dat } // gather the values from the RHS - GatherRHS(addresses, sel_vector, found_entries, result, left_column_count); + GatherRHS(addresses, sel_vector, found_entries, result, left_column_count, state.dictionary_gather_state); // the result may have no columns, so set the count explicitly result.SetChildCardinality(found_entries); } @@ -2389,7 +2673,7 @@ idx_t JoinHashTable::ScanKeyColumn(Vector &addresses, Vector &result, idx_t colu return 0; } D_ASSERT(result.GetType() == layout_ptr->GetTypes()[column_index]); - JoinHTScanState join_ht_state(*data_collection, 0, data_collection->ChunkCount(), + JoinHTScanState join_ht_state(*data_collection, 0, data_collection->ChunkCount(), output_columns.size(), TupleDataPinProperties::KEEP_EVERYTHING_PINNED); auto key_count = FillWithHTOffsets(join_ht_state, addresses); if (key_count == 0) { @@ -2539,6 +2823,8 @@ void JoinHashTable::Reset() { bucket_shift = 0; data_collection->Reset(); hash_map.Reset(); + perfect_hash_candidate.reset(); + perfect_hash_table.reset(); current_partitions.SetAllInvalid(RadixPartitioning::NumberOfPartitions(radix_bits)); finalized = false; } @@ -2574,6 +2860,8 @@ void JoinHashTable::ResetForNewIterationSinglePartition() { // keeps an unpublished shell consistent with the global radix bits when it is recycled. radix_bits = 0; InitializePartitionMasks(); + perfect_hash_candidate.reset(); + perfect_hash_table.reset(); if (!layout_ptr) { // layout was never published (no Sink chunk last iteration); the next first chunk will publish return; @@ -2596,7 +2884,10 @@ void JoinHashTable::ResetForNewIterationSinglePartition() { load_factor = DEFAULT_LOAD_FACTOR; bloom_filter.reset(); should_build_bloom_filter = false; - prefix_range_filter.reset(); + key_bloom_filters.clear(); + should_build_key_bloom_filters.clear(); + key_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 @@ -2778,19 +3069,42 @@ void ProbeSpill::PrepareNextProbe() { struct DictionaryEmissionActivation { //! Caps the dict_arrays allocation; 8 MiB keeps them in L3 and bounds aux_next_ptrs static constexpr idx_t MAX_BUILD_PAYLOAD_BYTES = 8ULL * 1024ULL * 1024ULL; - //! Below this, dictionary-emission setup is not amortized by probe-side savings - static constexpr idx_t MIN_PROBE_ROWS = 262144; //! Below this ratio, per-row savings are unlikely to amortize the setup cost static constexpr idx_t PROBE_BUILD_RATIO = 100; }; idx_t JoinHashTable::ComputeBuildPayloadBytes(const vector &rhs_output_types) const { - // the size of variable-size strings isn't counted here because they are already stored in the TupleDataCollection - idx_t payload_bytes_per_row = 0; + D_ASSERT(Count() > 0); + const auto limit = DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES; + idx_t payload_bytes = 0; + bool has_nested = false; for (const auto &type : rhs_output_types) { - payload_bytes_per_row += GetTypeIdSize(type.InternalType()); + 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(); + } + // 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) { + return limit + 1; + } + payload_bytes += collection_bytes; } - return Count() * payload_bytes_per_row; + return payload_bytes; +} + +bool JoinHashTable::CanUsePerfectDictionaryLookup() const { + return perfect_hash_table && join_type == JoinType::INNER && + !chains_longer_than_one.load(std::memory_order_relaxed) && non_equality_predicates.empty() && + !residual_predicate; +} + +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 { @@ -2807,27 +3121,33 @@ bool JoinHashTable::CanUseDictionaryEmission(const PhysicalHashJoin &op, bool ex if (join_type == JoinType::SINGLE) { return false; } - if (op.rhs_output_columns.col_types.empty()) { + // 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 (Count() == 0) { + if (op.rhs_output_columns.col_types.empty()) { return false; } - if (probe_cardinality < DictionaryEmissionActivation::MIN_PROBE_ROWS) { + if (Count() == 0 || Count() > NumericLimits::Maximum()) { return false; } - if (probe_cardinality < DictionaryEmissionActivation::PROBE_BUILD_RATIO * Count()) { + if (probe_cardinality < Count() || + (!CanUsePerfectDictionaryLookup() && + probe_cardinality / DictionaryEmissionActivation::PROBE_BUILD_RATIO < Count())) { return false; } - // Vector::Dictionary does not support nested types for (const auto &type : op.rhs_output_columns.col_types) { - switch (type.InternalType()) { - case PhysicalType::STRUCT: - case PhysicalType::LIST: - case PhysicalType::ARRAY: + if (type.InternalType() == PhysicalType::STRUCT) { + // STRUCT vectors apply selections to their children instead of wrapping a dictionary. + return false; + } + if (type.InternalType() == PhysicalType::ARRAY) { + // ARRAY dictionary hashing processes individual arrays instead of batching their children. + return false; + } + if (type.IsNested() && Count() > STANDARD_VECTOR_SIZE) { + // A chunk must be able to reference every nested dictionary entry. return false; - default: - break; } } if (ComputeBuildPayloadBytes(op.rhs_output_columns.col_types) > @@ -2840,16 +3160,23 @@ bool JoinHashTable::CanUseDictionaryEmission(const PhysicalHashJoin &op, bool ex } void JoinHashTable::EmitDictVectors(const data_ptr_t *row_ptrs, const SelectionVector &ptr_sel, idx_t count, - DataChunk &result, idx_t rhs_col_offset) const { + 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)); } + EmitDictVectors(build_sel_vec, 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()); for (idx_t col_idx = 0; col_idx < output_columns.size(); col_idx++) { auto &vector = result.data[rhs_col_offset + col_idx]; - vector.Dictionary(dict_arrays[col_idx], build_sel_vec, count); + vector.Dictionary(dictionary_state.GetEntry(col_idx, dict_arrays[col_idx]), build_sel, count); } } @@ -2858,32 +3185,57 @@ void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { const auto build_count = collection.Count(); // preconditions enforced by CanUseDictionaryEmission D_ASSERT(build_count > 0); + D_ASSERT(dict_arrays.empty()); // dict index is a uint32_t; assert defensively if MAX_BUILD_PAYLOAD_BYTES is ever relaxed D_ASSERT(build_count <= NumericLimits::Maximum()); // collect a row pointer per build row; the TDC holds its own BufferHandles for its lifetime, // and FinishEvent has already verified everything is pinned before calling us Vector row_pointer_vector(LogicalType::POINTER, build_count); - JoinHTScanState scan_state(collection, 0, collection.ChunkCount(), TupleDataPinProperties::KEEP_EVERYTHING_PINNED); + JoinHTScanState scan_state(collection, 0, collection.ChunkCount(), output_columns.size(), + TupleDataPinProperties::KEEP_EVERYTHING_PINNED); const auto collected = FillWithHTOffsets(scan_state, row_pointer_vector); D_ASSERT(collected == build_count); - (void)collected; + FlatVector::SetSize(row_pointer_vector, collected); const auto row_ptrs = FlatVector::GetData(row_pointer_vector); - // LEFT / OUTER joins fill unmatched probe rows with a constant-NULL vector (NextLeftJoin), so they do not - // wrap this entry on every chunk; it is only a global dictionary when every chunk goes through EmitDictVectors. - const bool dict_on_every_chunk = join_type != JoinType::LEFT && join_type != JoinType::OUTER; + // 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; + for (const auto &type : op.rhs_output_columns.col_types) { + dict_on_every_chunk &= !type.IsNested(); + } // gather RHS output columns into columnar dictionary arrays const auto &sel = *FlatVector::IncrementalSelectionVector(); + idx_t dictionary_bytes = 0; + 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); + if (dict_entry->data.GetAllocationSize() > + DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES - dictionary_bytes) { + return; + } const auto output_col_idx = output_columns[col_idx]; - collection.Gather(row_pointer_vector, sel, build_count, output_col_idx, dict_entry->data, sel, nullptr); - dict_arrays.emplace_back(std::move(dict_entry)); + if (type.IsNested()) { + D_ASSERT(build_count <= STANDARD_VECTOR_SIZE); + Vector gathered(type, build_count); + FlatVector::SetSize(gathered, build_count); + collection.Gather(row_pointer_vector, sel, build_count, output_col_idx, gathered, sel, nullptr); + // Own nested string heaps independently of the scratch vector. + 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); + } + const auto allocation_size = dict_entry->data.GetAllocationSize(); + if (allocation_size > DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES - dictionary_bytes) { + return; + } + 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 @@ -2907,6 +3259,11 @@ void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { } use_dict_emission = true; + // Nested output can fall back to native gathering, which needs the original row pointers. + if (CanUsePerfectDictionaryLookup() && !HasNestedDictionary(dict_arrays)) { + perfect_hash_table->ConvertToDictionary(pointer_offset); + DUCKDB_LOG(context, PhysicalOperatorLogType, op, "PhysicalHashJoin", "DictionaryLookup", {}); + } } } // 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 12896a69d..4f7733573 100644 --- a/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp +++ b/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp @@ -17,8 +17,8 @@ AggregateObject::AggregateObject(BoundAggregateFunction function, FunctionData * } AggregateObject::AggregateObject(BoundAggregateExpression &aggr) - : AggregateObject(aggr.Function(), aggr.BindInfoMutable().get(), aggr.GetChildren().size(), - AlignValue(aggr.Function().GetStateSize(aggr.BindInfoMutable().get())), aggr.GetAggregateType(), + : AggregateObject(aggr.Function(), aggr.BindInfo().get(), aggr.GetChildren().size(), + AlignValue(aggr.Function().GetStateSize(aggr.BindInfo().get())), aggr.GetAggregateType(), aggr.GetReturnType().InternalType(), aggr.GetFilter().get()) { } diff --git a/src/duckdb/src/execution/operator/aggregate/distinct_aggregate_data.cpp b/src/duckdb/src/execution/operator/aggregate/distinct_aggregate_data.cpp index f5cfb40f2..23e6407ff 100644 --- a/src/duckdb/src/execution/operator/aggregate/distinct_aggregate_data.cpp +++ b/src/duckdb/src/execution/operator/aggregate/distinct_aggregate_data.cpp @@ -126,7 +126,7 @@ struct FindMatchingAggregate { if (other.GetChildren().size() != aggr.GetChildren().size()) { return false; } - if (!Expression::Equals(aggr.GetFilterMutable(), other.GetFilterMutable())) { + if (!Expression::Equals(aggr.GetFilter(), other.GetFilter())) { return false; } for (idx_t i = 0; i < aggr.GetChildren().size(); i++) { diff --git a/src/duckdb/src/execution/operator/aggregate/grouped_aggregate_data.cpp b/src/duckdb/src/execution/operator/aggregate/grouped_aggregate_data.cpp index bd464d56d..6345d5124 100644 --- a/src/duckdb/src/execution/operator/aggregate/grouped_aggregate_data.cpp +++ b/src/duckdb/src/execution/operator/aggregate/grouped_aggregate_data.cpp @@ -47,14 +47,15 @@ unordered_map GroupedAggregateData::AddFilterColumns(const vector< if (!aggr.GetFilter()) { continue; } - auto &filter_ref = aggr.GetFilterMutable()->Cast(); + auto &filter = aggr.GetFilterMutable(); + auto &filter_ref = filter->Cast(); auto entry = payload_columns.find(filter_ref.Index()); if (entry == payload_columns.end()) { entry = payload_columns.emplace(filter_ref.Index(), payload_types.size()).first; filter_columns.emplace(payload_types.size(), filter_ref.Index()); payload_types.push_back(filter_ref.GetReturnType()); } - filter_ref.IndexMutable() = entry->second; + filter = filter_ref.WithIndex(entry->second); } return filter_columns; } diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/scanner_boundary.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/scanner_boundary.cpp index b2b4e4963..86176634e 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/scanner_boundary.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/scanner_boundary.cpp @@ -36,7 +36,7 @@ void CSVIterator::Print() const { idx_t CSVIterator::BytesPerThread(const CSVReaderOptions &reader_options) { const idx_t buffer_size = reader_options.buffer_size_option.GetValue(); const idx_t max_row_size = reader_options.maximum_line_size.GetValue(); - const idx_t bytes_per_thread = buffer_size / CSVBuffer::ROWS_PER_BUFFER * ROWS_PER_THREAD; + const idx_t bytes_per_thread = buffer_size / ROWS_PER_BUFFER * ROWS_PER_THREAD; if (bytes_per_thread < max_row_size) { // If we are setting up the buffer size directly, we must make sure each thread will read the full buffer. return max_row_size; 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 606cf9290..7b18e03e8 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 @@ -108,8 +108,17 @@ StringValueResult::StringValueResult(CSVStates &states, CSVStateMachine &state_m } } + // only values stored as strings reach the check, the directly cast types never do; a scan that reads its first + // column only to count rows validates a few bytes per row, less than the tracking would cost + const bool counts_rows_only = csv_file_scan && csv_file_scan->reads_first_column_to_count_rows; + for (idx_t i = 0; i < logical_types.size() && !counts_rows_only; i++) { + validates_utf8 = + validates_utf8 || (parse_types[i].validate_utf8 && parse_types[i].type_id == LogicalTypeId::VARCHAR); + } // Initialize Parse Chunk parse_chunk.Initialize(buffer_allocator, logical_types, result_size); + // one slot more, the cast error search of Flush can stop one past the last row + line_positions_per_row.resize(result_size + 1); for (auto &col : parse_chunk.data) { vector_ptr.push_back(FlatVector::GetDataMutable(col)); validity_mask.push_back(&FlatVector::ValidityMutable(col)); @@ -262,11 +271,9 @@ void StringValueResult::AddValueToVector(const char *value_ptr, idx_t size, bool return; } - if (projecting_columns) { - if (!projected_columns[cur_col_id]) { - cur_col_id++; - return; - } + if (CanSkipValue(*this)) { + cur_col_id++; + return; } if (((quoted && state_machine.options.allow_quoted_nulls) || !quoted)) { @@ -485,7 +492,7 @@ void StringValueResult::AddValueToVector(const char *value_ptr, idx_t size, bool default: { // By default, we add a string // We only evaluate if a string is utf8 valid, if it's actually a varchar - if (parse_types[chunk_col_id].validate_utf8 && + if (parse_types[chunk_col_id].validate_utf8 && !ascii_value && !Utf8Proc::IsValid(value_ptr, UnsafeNumericCast(size))) { bool force_error = !state_machine.options.ignore_errors.GetValue() && sniffing; // Invalid unicode, we must error @@ -681,6 +688,24 @@ void StringValueResult::AddValue(StringValueResult &result, const idx_t buffer_p result.last_position.buffer_pos = buffer_pos + 1; } +void StringValueResult::SkipValueInternal() { + D_ASSERT(CanSkipValue(*this)); + if (quoted && !unquoted) { + current_errors.Insert(UNTERMINATED_QUOTES, cur_col_id, chunk_col_id, last_position); + } + cur_col_id++; + quoted = false; + escaped = false; +} + +void StringValueResult::SkipValue(StringValueResult &result, const idx_t buffer_pos) { + if (result.last_position.buffer_pos > buffer_pos) { + return; + } + result.SkipValueInternal(); + result.last_position.buffer_pos = buffer_pos + 1; +} + void StringValueResult::HandleUnicodeError(idx_t col_idx, LinePosition &error_position) { bool first_nl = false; auto borked_line = current_line_position.ReconstructCurrentLine(first_nl, buffer_handles, PrintErrorLine()); @@ -855,6 +880,13 @@ void StringValueResult::InvalidateUnwrittenColumns(idx_t first_unwritten_col) { } } +void StringValueResult::StoreLinePosition() { + // a removed row leaves number_of_rows at -1, nothing reads a position for it + if (number_of_rows >= 0) { + line_positions_per_row[static_cast(number_of_rows)] = current_line_position; + } +} + bool StringValueResult::AddRowInternal() { LinePosition current_line_start = {iterator.pos.buffer_idx, iterator.pos.buffer_pos, buffer_size}; idx_t current_line_size = current_line_start - current_line_position.end; @@ -875,7 +907,7 @@ bool StringValueResult::AddRowInternal() { D_ASSERT(buffer_handles.find(current_line_position.begin.buffer_idx) != buffer_handles.end()); D_ASSERT(buffer_handles.find(current_line_position.end.buffer_idx) != buffer_handles.end()); - line_positions_per_row[static_cast(number_of_rows)] = current_line_position; + StoreLinePosition(); number_of_rows++; if (static_cast(number_of_rows) >= result_size) { // We have a full chunk @@ -936,7 +968,7 @@ bool StringValueResult::AddRowInternal() { } D_ASSERT(buffer_handles.find(current_line_position.begin.buffer_idx) != buffer_handles.end()); D_ASSERT(buffer_handles.find(current_line_position.end.buffer_idx) != buffer_handles.end()); - line_positions_per_row[static_cast(number_of_rows)] = current_line_position; + StoreLinePosition(); cur_col_id = 0; chunk_col_id = 0; number_of_rows++; @@ -947,6 +979,15 @@ bool StringValueResult::AddRowInternal() { return false; } +void StringValueResult::SetLastPositionAfterNewline(const idx_t buffer_pos) { + if (state_machine.dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON && + states.states[1] != CSVState::RECORD_SEPARATOR) { + last_position.buffer_pos = buffer_pos + 2; + } else { + last_position.buffer_pos = buffer_pos + 1; + } +} + bool StringValueResult::AddRow(StringValueResult &result, const idx_t buffer_pos) { if (result.last_position.buffer_pos <= buffer_pos) { // We add the value @@ -961,22 +1002,21 @@ bool StringValueResult::AddRow(StringValueResult &result, const idx_t buffer_pos result.AddValueToVector(value_ptr, size); } } - if (result.state_machine.dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON) { - if (result.states.states[1] == CSVState::RECORD_SEPARATOR) { - // Even though this is marked as a carry on, this is a hippie mixie - result.last_position.buffer_pos = buffer_pos + 1; - } else { - result.last_position.buffer_pos = buffer_pos + 2; - } - } else { - result.last_position.buffer_pos = buffer_pos + 1; - } + result.SetLastPositionAfterNewline(buffer_pos); } // We add the value return result.AddRowInternal(); } +bool StringValueResult::AddRowWithoutValue(StringValueResult &result, const idx_t buffer_pos) { + if (result.last_position.buffer_pos <= buffer_pos) { + result.SkipValueInternal(); + result.SetLastPositionAfterNewline(buffer_pos); + } + return result.AddRowInternal(); +} + void StringValueResult::InvalidState(StringValueResult &result) { if (result.quoted) { result.current_errors.Insert(UNTERMINATED_QUOTES, result.cur_col_id, result.chunk_col_id, result.last_position); @@ -1525,6 +1565,11 @@ void StringValueScanner::ProcessOverBufferValue() { } j++; } + if (cur_buffer_handle->is_last_buffer && iterator.pos.buffer_pos >= cur_buffer_handle->actual_size && + states.IsQuotedCurrent() && state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) { + // the file ended inside a quoted value: record that before the value itself is added + result.current_errors.Insert(UNTERMINATED_QUOTES, result.cur_col_id, result.chunk_col_id, result.last_position); + } bool skip_value = false; if (result.projecting_columns) { if (result.cur_col_id < result.number_of_columns && !result.projected_columns[result.cur_col_id]) { @@ -1685,6 +1730,16 @@ StringValueScanner::MoveBufferResult StringValueScanner::TryMoveToNextBuffer() { if (states.EmptyLine() || states.NewRow() || result.added_last_line || states.IsCurrentNewRow() || states.IsNotSet()) { if (result.cur_col_id == result.number_of_columns && !result.IsStateCurrent(CSVState::INVALID)) { + // the last value was already added: this row ends at the end of the file + LinePosition line_end = {iterator.pos.buffer_idx, previous_buffer_handle->actual_size, result.buffer_size}; + result.current_line_position.begin = result.current_line_position.end; + result.current_line_position.end = line_end; + // handle the errors recorded for the row before counting it, as AddRowInternal does + const auto chunk_col_id_before = result.chunk_col_id; + if (result.current_errors.HandleErrors(result)) { + result.InvalidateUnwrittenColumns(chunk_col_id_before); + } + result.line_positions_per_row[static_cast(result.number_of_rows)] = result.current_line_position; result.number_of_rows++; } result.cur_col_id = 0; @@ -2020,26 +2075,22 @@ void StringValueScanner::FinishBoundaryScan(const bool moved) { } const bool found_error = result.current_errors.HasErrorType(UNTERMINATED_QUOTES) || result.current_errors.HasErrorType(INVALID_STATE); - auto chunk_col_id_before = result.chunk_col_id; - if (result.current_errors.HandleErrors(result)) { - result.InvalidateUnwrittenColumns(chunk_col_id_before); - result.number_of_rows++; - } if (states.IsQuotedCurrent() && !found_error) { - if (state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) { - // If we finish the execution of a buffer, and we end in a quoted state, it means we have unterminated - // quotes + if (!state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) { + used_unstrictness = true; + } else if (cur_buffer_handle) { + // a row still open in a quoted state after its buffer has unterminated quotes; once the file has ended, + // the end-of-file handling in TryMoveToNextBuffer has already finished that row result.current_errors.Insert(UNTERMINATED_QUOTES, result.cur_col_id, result.chunk_col_id, result.last_position); - chunk_col_id_before = result.chunk_col_id; - if (result.current_errors.HandleErrors(result)) { - result.InvalidateUnwrittenColumns(chunk_col_id_before); - result.number_of_rows++; - } - } else { - used_unstrictness = true; } } + // the errors all belong to the row being finished, so this appends at most one row + const auto chunk_col_id_before = result.chunk_col_id; + if (result.current_errors.HandleErrors(result)) { + result.InvalidateUnwrittenColumns(chunk_col_id_before); + result.number_of_rows++; + } if (!iterator.done) { if (iterator.pos.buffer_pos >= iterator.GetEndPos() || iterator.pos.buffer_idx > iterator.GetBufferIdx() || FinishedFile()) { diff --git a/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_file_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_file_scanner.cpp index 0fc650862..5a4a742a5 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_file_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_file_scanner.cpp @@ -115,6 +115,7 @@ void CSVFileScan::InitializeFileNamesTypes() { // just read the first column file_types.emplace_back(LogicalType::VARCHAR); projected_columns.insert(0); + reads_first_column_to_count_rows = true; projection_ids.emplace_back(0, 0); return; } 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 837f73edd..082dd992f 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 @@ -591,6 +591,9 @@ bool StoreUserDefinedParameter(const Identifier &option) { return true; } +//! A buffer sized by a user maximum line size holds this many lines of that size +static constexpr idx_t LINES_PER_BUFFER = 16; + void CSVReaderOptions::Verify(MultiFileOptions &file_options) { if (rejects_table_name.IsSetByUser() && !store_rejects.GetValue() && store_rejects.IsSetByUser()) { throw BinderException("REJECTS_TABLE option is only supported when store_rejects is not manually set to false"); @@ -624,16 +627,17 @@ void CSVReaderOptions::Verify(MultiFileOptions &file_options) { "must have always be set to value bigger than MAX_LINE_SIZE", buffer_size_option.GetValue(), maximum_line_size.GetValue()); } - } else if (maximum_line_size.IsSetByUser() && maximum_line_size.GetValue() > max_line_size_default) { - // If the max line size is set by the user and bigger than we have by default, we make it part of our buffer - // size decision. + } else if (maximum_line_size.IsSetByUser()) { + // a buffer holds LINES_PER_BUFFER lines of a user maximum line size, but never shrinks below the default buffer idx_t buffer_size; - if (!TryMultiplyOperator::Operation(CSVBuffer::ROWS_PER_BUFFER, - maximum_line_size.GetValue(), buffer_size)) { + if (!TryMultiplyOperator::Operation(LINES_PER_BUFFER, maximum_line_size.GetValue(), + buffer_size)) { throw BinderException("MAX_LINE_SIZE option was set to %d, which is too large", maximum_line_size.GetValue()); } - buffer_size_option.Set(buffer_size, false); + if (buffer_size > CSVBuffer::CSV_BUFFER_SIZE) { + buffer_size_option.Set(buffer_size, false); + } } } diff --git a/src/duckdb/src/execution/operator/helper/physical_execute.cpp b/src/duckdb/src/execution/operator/helper/physical_execute.cpp deleted file mode 100644 index 27a4356f4..000000000 --- a/src/duckdb/src/execution/operator/helper/physical_execute.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "duckdb/execution/operator/helper/physical_execute.hpp" - -#include "duckdb/parallel/meta_pipeline.hpp" - -namespace duckdb { - -PhysicalExecute::PhysicalExecute(PhysicalPlan &physical_plan, PhysicalOperator &plan, - shared_ptr prepared) - : PhysicalOperator(physical_plan, PhysicalOperatorType::EXECUTE, plan.types, idx_t(-1)), plan(plan), - prepared(std::move(prepared)) { -} - -vector> PhysicalExecute::GetChildren() const { - return {plan}; -} - -void PhysicalExecute::BuildPipelines(Pipeline ¤t, MetaPipeline &meta_pipeline) { - // EXECUTE statement: build pipeline on child - meta_pipeline.Build(plan); -} - -} // namespace duckdb diff --git a/src/duckdb/src/execution/operator/helper/physical_load.cpp b/src/duckdb/src/execution/operator/helper/physical_load.cpp index a475bfc7a..561f4c401 100644 --- a/src/duckdb/src/execution/operator/helper/physical_load.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_load.cpp @@ -8,12 +8,13 @@ namespace duckdb { -static void InstallFromRepository(ClientContext &context, const LoadInfo &info) { +//! Install from the FROM source, which is a trusted repository that was added by the user, a built-in repository name +//! or a url. Returns the repository it resolved to, so that a following LOAD looks where the install put the extension +static ExtensionRepository InstallFromRepository(ClientContext &context, const LoadInfo &info) { auto &db = DatabaseInstance::GetDatabase(context); auto &fs = FileSystem::GetLocal(db); ExtensionRepository repository; - // the repository can be a trusted repository that was added by the user, a built-in repository name or a url if (!ExtensionRepositoryManager::TryGetRepository(db, fs, info.repository, repository)) { if (info.repo_is_alias) { // This has been checked during bind, so it should not fail here @@ -32,6 +33,7 @@ static void InstallFromRepository(ClientContext &context, const LoadInfo &info) options.repository = repository; ExtensionHelper::InstallExtension(context, info.filename, options); + return repository; } static void ExecuteRepositoryStatement(ClientContext &context, const LoadInfo &info, DataChunk &chunk) { @@ -39,8 +41,9 @@ static void ExecuteRepositoryStatement(ClientContext &context, const LoadInfo &i auto &fs = FileSystem::GetLocal(db); if (info.load_type == LoadType::CREATE_REPOSITORY) { - ExtensionRepository repository(info.repository, info.repository_url, info.public_keys); - auto result = ExtensionRepositoryManager::CreateRepository(db, fs, context, repository, info.on_conflict); + // what was asked for; without a prefix the manager resolves the name as a host + ExtensionRepository requested(info.repository, info.repository_url, info.public_keys); + auto result = ExtensionRepositoryManager::CreateRepository(db, fs, context, requested, info.on_conflict); // report the repository as it was stored, so that the keys can be compared with the published fingerprints vector fingerprints; @@ -61,6 +64,9 @@ SourceResultType PhysicalLoad::GetDataInternal(ExecutionContext &context, DataCh if (info->load_type == LoadType::CREATE_REPOSITORY || info->load_type == LoadType::DROP_REPOSITORY) { ExecuteRepositoryStatement(context.client, *info, chunk); } else if (info->load_type == LoadType::INSTALL || info->load_type == LoadType::FORCE_INSTALL) { + // the repository the install resolved to; a bare install has none to name, so the load stays bare + ExtensionRepository installed_from; + installed_from.name.clear(); if (info->repository.empty()) { ExtensionInstallOptions options; options.force_install = info->load_type == LoadType::FORCE_INSTALL; @@ -68,16 +74,16 @@ SourceResultType PhysicalLoad::GetDataInternal(ExecutionContext &context, DataCh options.version = info->version; ExtensionHelper::InstallExtension(context.client, info->filename, options); } else { - InstallFromRepository(context.client, *info); + installed_from = InstallFromRepository(context.client, *info); } - // INSTALL AND LOAD: load the extension immediately after installing it. Only a named repository (core, - // community or a user repository alias) is passed on to the load - a URL or bare install lands in the flat - // top-level layout, which a bare load resolves + // INSTALL AND LOAD: load the extension immediately after installing it, from the repository the install + // resolved - whether it was named as an identifier or as a string. A url or a bare install resolves to no name, + // and lands in the flat top-level layout, which a bare load resolves if (info->load_after_install) { ExtensionLoadOptions load_options; load_options.extension_name = info->filename; - load_options.repository = info->repo_is_alias ? info->repository : string(); + load_options.repository = installed_from.name; ExtensionHelper::LoadExternalExtension(context.client, load_options); ExtensionLoader::RefreshSearchPath(context.client); } diff --git a/src/duckdb/src/execution/operator/helper/physical_reset.cpp b/src/duckdb/src/execution/operator/helper/physical_reset.cpp index b8a9866a3..6d6430317 100644 --- a/src/duckdb/src/execution/operator/helper/physical_reset.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_reset.cpp @@ -21,8 +21,7 @@ void PhysicalReset::ResetExtensionVariable(ExecutionContext &context, DBConfig & config.ResetOption(extension_option); } else { auto &client_config = ClientConfig::GetConfig(context.client); - auto setting_index = extension_option.setting_index.GetIndex(); - client_config.user_settings.SetUserSetting(setting_index, extension_option.default_value); + client_config.user_settings.ClearSetting(extension_option.setting_index.GetIndex()); } } diff --git a/src/duckdb/src/execution/operator/join/perfect_hash_join_executor.cpp b/src/duckdb/src/execution/operator/join/perfect_hash_join_executor.cpp deleted file mode 100644 index b03e321d0..000000000 --- a/src/duckdb/src/execution/operator/join/perfect_hash_join_executor.cpp +++ /dev/null @@ -1,403 +0,0 @@ -#include "duckdb/execution/operator/join/perfect_hash_join_executor.hpp" - -#include "duckdb/common/operator/subtract.hpp" -#include "duckdb/execution/operator/join/physical_hash_join.hpp" -#include "duckdb/common/atomic.hpp" -#include "duckdb/planner/joinside.hpp" - -namespace duckdb { - -PerfectHashJoinExecutor::PerfectHashJoinExecutor(const PhysicalHashJoin &join_p, JoinHashTable &ht_p) - : join(join_p), ht(ht_p) { -} - -const LogicalType &PerfectHashJoinExecutor::GetKeyType() const { - return ht.equality_types[0]; -} - -//===--------------------------------------------------------------------===// -// Initialize -//===--------------------------------------------------------------------===// -bool ExtractNumericValue(const Value &val, hugeint_t &result) { - if (!val.type().IsIntegral()) { - switch (val.type().InternalType()) { - case PhysicalType::INT8: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::INT16: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::INT32: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::INT64: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::INT128: - result = val.GetValueUnsafe(); - break; - case PhysicalType::UINT8: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::UINT16: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::UINT32: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::UINT64: - result = Hugeint::Convert(val.GetValueUnsafe()); - break; - case PhysicalType::UINT128: { - const auto uhugeint_val = val.GetValueUnsafe(); - if (uhugeint_val > NumericCast(NumericLimits::Maximum())) { - return false; - } - result.lower = uhugeint_val.lower; - result.upper = NumericCast(uhugeint_val.upper); - break; - } - default: - return false; - } - } else { - auto cast = val.DefaultTryCastAs(LogicalType::HUGEINT); - if (!cast) { - return false; - } - result = cast->GetValue(); - } - return true; -} - -bool PerfectHashJoinExecutor::CanDoPerfectHashJoin(const PhysicalHashJoin &op, const Value &min, const Value &max) { - // TODO: Add support for residual predicates - if (op.predicate) { - return false; - } - - if (perfect_join_statistics.is_build_small) { - return true; // Already true based on static statistics - } - - // We only do this optimization for inner joins with one integer equality condition - const auto key_type = op.conditions[0].GetLHS().GetReturnType(); - if (op.join_type != JoinType::INNER || op.conditions.size() != 1 || - op.conditions[0].GetComparisonType() != ExpressionType::COMPARE_EQUAL || - !TypeIsInteger(key_type.InternalType())) { - return false; - } - - // We bail out if there are nested types on the RHS - for (auto &type : op.children[1].get().GetTypes()) { - switch (type.InternalType()) { - case PhysicalType::STRUCT: - case PhysicalType::LIST: - case PhysicalType::ARRAY: - return false; - default: - break; - } - } - - // And when the build range is smaller than the threshold - perfect_join_statistics.build_min = min; - perfect_join_statistics.build_max = max; - hugeint_t min_value, max_value; - if (!ExtractNumericValue(perfect_join_statistics.build_min, min_value) || - !ExtractNumericValue(perfect_join_statistics.build_max, max_value)) { - return false; - } - if (max_value < min_value) { - return false; // Empty table - } - - hugeint_t build_range; - if (!TrySubtractOperator::Operation(max_value, min_value, build_range)) { - return false; - } - - // The max size our build must have to run the perfect HJ - static constexpr idx_t MAX_BUILD_SIZE = 1048576; - if (build_range > Hugeint::Convert(MAX_BUILD_SIZE)) { - return false; - } - perfect_join_statistics.build_range = NumericCast(build_range); - - // If count is larger than range (duplicates), we bail out - if (ht.Count() > perfect_join_statistics.build_range) { - return false; - } - - perfect_join_statistics.is_build_small = true; - return true; -} - -//===--------------------------------------------------------------------===// -// Build -//===--------------------------------------------------------------------===// -bool PerfectHashJoinExecutor::BuildPerfectHashTable() { - // First, allocate memory for each build column - const auto build_size = perfect_join_statistics.build_range + 1; - for (const auto &type : join.rhs_output_columns.col_types) { - // PHJ keeps each entry alive for the operator's lifetime and wraps it in every emitted chunk - perfect_hash_table.emplace_back(DictionaryVector::CreateReusableGlobalDictionary(type, build_size)); - } - - // and for duplicate_checking - bitmap_build_idx.Initialize(build_size); - bitmap_build_idx.SetAllInvalid(build_size); - - // Now fill columns with build data - return FullScanHashTable(); -} - -bool PerfectHashJoinExecutor::FullScanHashTable() { - auto &data_collection = ht.GetDataCollection(); - - // TODO: In a parallel finalize: One should exclusively lock and each thread should do one part of the code below. - Vector tuples_addresses(LogicalType::POINTER, ht.Count()); // allocate space for all the tuples - Vector build_vector(GetKeyType(), ht.Count()); - auto key_count = ht.ScanKeyColumn(tuples_addresses, build_vector, 0); - - // Now fill the selection vector using the build keys and create a sequential vector - // TODO: add check for fast pass when probe is part of build domain - SelectionVector sel_build(key_count + 1); - SelectionVector sel_tuples(key_count + 1); - bool success = FillSelectionVectorSwitchBuild(build_vector, sel_build, sel_tuples, key_count); - - // early out - if (!success) { - return false; - } - - const auto build_size = perfect_join_statistics.build_range + 1; - if (unique_keys == build_size && !ht.has_null) { - perfect_join_statistics.is_build_dense = true; - bitmap_build_idx.Reset(build_size); // All valid - } - key_count = unique_keys; // do not consider keys out of the range - - // Full scan the remaining build columns and fill the perfect hash table - for (idx_t i = 0; i < join.rhs_output_columns.col_types.size(); i++) { - auto &vector = perfect_hash_table[i]->data; - const auto output_col_idx = ht.output_columns[i]; - D_ASSERT(vector.GetType() == ht.layout_ptr->GetTypes()[output_col_idx]); - auto &col_mask = FlatVector::ValidityMutable(vector); - col_mask.Reset(build_size); - data_collection.Gather(tuples_addresses, sel_tuples, key_count, output_col_idx, vector, sel_build, nullptr); - // This ensures the empty entries are set to NULL, so that the emitted dictionary vectors make sense - col_mask.Combine(bitmap_build_idx, build_size); - } - - return true; -} - -bool PerfectHashJoinExecutor::FillSelectionVectorSwitchBuild(const Vector &source, SelectionVector &sel_vec, - SelectionVector &seq_sel_vec, idx_t count) { - switch (source.GetType().InternalType()) { - case PhysicalType::INT8: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::INT16: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::INT32: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::INT64: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::INT128: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::UINT8: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::UINT16: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::UINT32: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::UINT64: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - case PhysicalType::UINT128: - return TemplatedFillSelectionVectorBuild(source, sel_vec, seq_sel_vec, count); - default: - throw NotImplementedException("Type not supported for perfect hash join"); - } -} - -template -bool PerfectHashJoinExecutor::TemplatedFillSelectionVectorBuild(const Vector &source, SelectionVector &sel_vec, - SelectionVector &seq_sel_vec, idx_t count) { - if (perfect_join_statistics.build_min.IsNull() || perfect_join_statistics.build_max.IsNull()) { - return false; - } - auto min_value = perfect_join_statistics.build_min.GetValueUnsafe(); - auto max_value = perfect_join_statistics.build_max.GetValueUnsafe(); - auto entries = source.Values(); - // generate the selection vector - for (idx_t i = 0, sel_idx = 0; i < count; ++i) { - auto input_value = entries.GetValueUnsafe(i); - // add index to selection vector if value in the range - if (min_value <= input_value && input_value <= max_value) { - auto idx = UnsafeNumericCast(input_value - min_value); // subtract min value to get the idx position - sel_vec.set_index(sel_idx, idx); - if (bitmap_build_idx.RowIsValidUnsafe(idx)) { - return false; - } else { - bitmap_build_idx.SetValidUnsafe(idx); - unique_keys++; - } - seq_sel_vec.set_index(sel_idx++, i); - } - } - return true; -} - -//===--------------------------------------------------------------------===// -// Probe -//===--------------------------------------------------------------------===// -class PerfectHashJoinState : public OperatorState { -public: - PerfectHashJoinState(ClientContext &context, const PhysicalHashJoin &join) : probe_executor(context) { - join_keys.Initialize(Allocator::Get(context), join.condition_types); - for (auto &cond : join.conditions) { - probe_executor.AddExpression(cond.GetLHS()); - } - build_sel_vec.Initialize(STANDARD_VECTOR_SIZE); - probe_sel_vec.Initialize(STANDARD_VECTOR_SIZE); - seq_sel_vec.Initialize(STANDARD_VECTOR_SIZE); - } - - DataChunk join_keys; - ExpressionExecutor probe_executor; - SelectionVector build_sel_vec; - SelectionVector probe_sel_vec; - SelectionVector seq_sel_vec; -}; - -unique_ptr PerfectHashJoinExecutor::GetOperatorState(ExecutionContext &context) { - auto state = make_uniq(context.client, join); - return std::move(state); -} - -OperatorResultType PerfectHashJoinExecutor::ProbePerfectHashTable(ExecutionContext &context, DataChunk &input, - DataChunk &lhs_output_columns, DataChunk &result, - OperatorState &state_p) { - auto &state = state_p.Cast(); - // keeps track of how many probe keys have a match - idx_t probe_sel_count = 0; - - // fetch the join keys from the chunk - state.join_keys.Reset(); - state.probe_executor.Execute(input, state.join_keys); - // select the keys that are in the min-max range - const auto &keys_vec = state.join_keys.data[0]; - auto keys_count = state.join_keys.size(); - // todo: add check for fast pass when probe is part of build domain - FillSelectionVectorSwitchProbe(keys_vec, keys_count, state.probe_sel_vec, probe_sel_count, &state.build_sel_vec); - - // If build is dense and probe is in build's domain, just reference probe - if (perfect_join_statistics.is_build_dense && keys_count == probe_sel_count) { - result.Reference(lhs_output_columns); - } else { - // otherwise, filter it out the values that do not match - result.Slice(lhs_output_columns, state.probe_sel_vec, probe_sel_count, 0); - } - // on the build side, we need to fetch the data and build dictionary vectors with the sel_vec - for (idx_t i = 0; i < join.rhs_output_columns.col_types.size(); i++) { - auto &result_vector = result.data[lhs_output_columns.ColumnCount() + i]; - D_ASSERT(result_vector.GetType() == ht.layout_ptr->GetTypes()[ht.output_columns[i]]); - result_vector.Dictionary(perfect_hash_table[i], state.build_sel_vec, probe_sel_count); - } - return OperatorResultType::NEED_MORE_INPUT; -} - -void PerfectHashJoinExecutor::FillSelectionVectorSwitchProbe(const Vector &source, const idx_t &count, - SelectionVector &probe_sel_vec, idx_t &probe_sel_count, - optional_ptr build_sel_vec) const { - if (build_sel_vec) { - FillSelectionVectorSwitchProbe(source, count, probe_sel_vec, probe_sel_count, build_sel_vec.get()); - } else { - FillSelectionVectorSwitchProbe(source, count, probe_sel_vec, probe_sel_count, nullptr); - } -} - -template -void PerfectHashJoinExecutor::FillSelectionVectorSwitchProbe(const Vector &source, const idx_t &count, - SelectionVector &probe_sel_vec, idx_t &probe_sel_count, - SelectionVector *build_sel_vec) const { - D_ASSERT(BUILD_SEL_VEC == static_cast(build_sel_vec)); - switch (source.GetType().InternalType()) { - case PhysicalType::INT8: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::INT16: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::INT32: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::INT64: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::INT128: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::UINT8: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::UINT16: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::UINT32: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::UINT64: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - case PhysicalType::UINT128: - TemplatedFillSelectionVectorProbe(source, count, probe_sel_vec, probe_sel_count, - build_sel_vec); - break; - default: - throw NotImplementedException("Type not supported"); - } -} - -template -void PerfectHashJoinExecutor::TemplatedFillSelectionVectorProbe(const Vector &source, const idx_t &count, - SelectionVector &probe_sel_vec, idx_t &probe_sel_count, - SelectionVector *build_sel_vec) const { - D_ASSERT(probe_sel_count == 0); - const auto min_value = perfect_join_statistics.build_min.GetValueUnsafe(); - const auto max_value = perfect_join_statistics.build_max.GetValueUnsafe(); - - auto entries = source.Values(); - // build selection vector for non-dense build - for (idx_t i = 0; i < count; ++i) { - auto entry = entries[i]; - if (!entry.IsValid()) { - continue; - } - const auto &input_value = entry.GetValue(); - // add index to selection vector if value in the range - if (min_value <= input_value && input_value <= max_value) { - // subtract min value to get the idx - const auto idx = UnsafeNumericCast(input_value - min_value); - // position check for matches in the build - if (bitmap_build_idx.RowIsValid(idx)) { - if (BUILD_SEL_VEC) { - build_sel_vec->set_index(probe_sel_count, idx); - } - probe_sel_vec.set_index(probe_sel_count++, i); - } - } - } -} - -} // namespace duckdb 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 923ef48a5..80d06361c 100644 --- a/src/duckdb/src/execution/operator/join/physical_hash_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_hash_join.cpp @@ -14,7 +14,6 @@ #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/perfect_hash_join_executor.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" @@ -278,18 +277,6 @@ JoinFilterGlobalState::~JoinFilterGlobalState() { JoinFilterLocalState::~JoinFilterLocalState() { } -static bool CanUsePerfectHashJoin(const PhysicalHashJoin &op, PerfectHashJoinExecutor &perfect_join_executor) { - if (op.conditions.size() != 1 || !op.conditions[0].GetRightStats()) { - return false; - } - const auto &right_stats = *op.conditions[0].GetRightStats(); - if (!TypeIsIntegral(right_stats.GetType().InternalType()) || !NumericStats::HasMinMax(right_stats)) { - return false; - } - return perfect_join_executor.CanDoPerfectHashJoin(op, NumericStats::Min(right_stats), - NumericStats::Max(right_stats)); -} - unique_ptr JoinFilterPushdownInfo::GetGlobalState(ClientContext &context, const PhysicalOperator &op) const { // clear any previously set filters @@ -389,8 +376,17 @@ 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) { @@ -465,18 +461,11 @@ class HashJoinGlobalSinkState : public GlobalSinkState { } //! Establishes the per-execution decisions, both at construction and at a recursive iteration reset: - //! the perfect-hash candidate, filter-pushdown participation, and the sink bloom filter. + //! filter-pushdown participation and the sink bloom filter. void InitializePerExecutionState(ClientContext &context, shared_ptr recycled_filter = nullptr) { - perfect_join_executor = make_uniq(op, *hash_table); - can_use_perfect_hash = CanUsePerfectHashJoin(op, *perfect_join_executor); external = Settings::Get(context); - skip_filter_pushdown = false; global_filter_state.reset(); - if (op.filter_pushdown) { - if (op.filter_pushdown->probe_info.empty() && can_use_perfect_hash) { - // Only computing min/max to check for perfect HJ, but we already can - skip_filter_pushdown = true; - } + if (op.filter_pushdown && !op.filter_pushdown->probe_info.empty()) { global_filter_state = op.filter_pushdown->GetGlobalState(context, op); } InitializeBloomFilter(std::move(recycled_filter)); @@ -489,8 +478,7 @@ class HashJoinGlobalSinkState : public GlobalSinkState { if (recycled_filter && recycled_filter->IsPublished()) { recycled_filter.reset(); } - // a perfect hash join publishes its own exact filter, so a bloom filter would never leave the sink - if (skip_filter_pushdown || can_use_perfect_hash || !ShouldBuildBloomFilterInSink(context, op)) { + 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 @@ -516,8 +504,6 @@ class HashJoinGlobalSinkState : public GlobalSinkState { //! First-chunk election: build the canonical layout (with per-column slot narrowing) and publish it. //! Idempotent and safe to call concurrently; only the first thread runs the slow path. void PublishLayoutIfFirst(class HashJoinLocalSinkState &lstate, DataChunk &payload_chunk); - //! True iff at least one column on the global JHT carries a pinned upstream dictionary entry. - bool DictSurvivingActive() const; bool SupportsReuse() const override { return true; @@ -561,8 +547,6 @@ class HashJoinGlobalSinkState : public GlobalSinkState { const idx_t initial_radix_bits; //! Global HT used by the join unique_ptr hash_table; - //! The perfect hash join executor (if any) - unique_ptr perfect_join_executor; //! Whether or not the hash table has been finalized bool finalized; //! The number of active local states @@ -595,15 +579,11 @@ class HashJoinGlobalSinkState : public GlobalSinkState { //! Preserve the finalized build-side state across recursive CTE iterations bool preserve_build_for_reuse = false; - bool skip_filter_pushdown = false; unique_ptr global_filter_state; bool keep_local_hash_tables = false; //! Coordinates first-chunk publication of the TupleDataLayout across parallel sinks. LayoutGate layout_gate; - //! True iff this join may use perfect-hash-join at Finalize. PHJ's FullScanHashTable reads payload at native - //! width, so it disables dict-surviving slot narrowing. - bool can_use_perfect_hash = false; //! True iff the build subtree funnels multiple producer pipelines into this sink (UNION ALL / //! recursive CTE); disables dict-surviving because the first-chunk layout election is unsound there. bool build_side_multi_source = false; @@ -641,7 +621,7 @@ class HashJoinLocalSinkState : public LocalSinkState { gstate.active_local_states++; - if (op.filter_pushdown) { + if (gstate.global_filter_state) { local_filter_state = op.filter_pushdown->GetLocalState(*gstate.global_filter_state); } } @@ -686,7 +666,7 @@ class HashJoinLocalSinkState : public LocalSinkState { hash_table->SetBloomFilter(gstate.hash_table->GetBloomFilter()); keep_hash_table = gstate.keep_local_hash_tables; gstate.active_local_states++; - if (op.filter_pushdown) { + if (gstate.global_filter_state) { local_filter_state = op.filter_pushdown->GetLocalState(*gstate.global_filter_state); } else { local_filter_state.reset(); @@ -718,9 +698,8 @@ static shared_ptr BuildJoinLayout(const vector &co return layout; } -//! Join-level gate: shape-only eligibility checks, mirroring the dict-emission path plus a PHJ exclusion -static bool CanUseDictSurvivingJoin(const PhysicalHashJoin &op, const JoinHashTable &ht, bool can_use_perfect_hash, - bool build_side_multi_source) { +//! Join-level eligibility for preserving build-side dictionary slots. +static bool CanUseDictSurvivingJoin(const PhysicalHashJoin &op, const JoinHashTable &ht, 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 @@ -747,24 +726,16 @@ static bool CanUseDictSurvivingJoin(const PhysicalHashJoin &op, const JoinHashTa if (op.rhs_output_columns.col_types.empty()) { return false; } - // PHJ's FullScanHashTable reads payload from the row store at native width; a narrowed slot would corrupt it. - if (can_use_perfect_hash) { - return false; - } return true; } -bool HashJoinGlobalSinkState::DictSurvivingActive() const { - return hash_table && hash_table->HasDictSurvivingColumns(); -} - void HashJoinGlobalSinkState::PublishLayoutIfFirst(HashJoinLocalSinkState &lstate, DataChunk &payload_chunk) { CallOnce(*layout_gate.publish_once, [&] { const auto &cond_types = lstate.hash_table->condition_types; const auto &build_types = lstate.hash_table->build_types; shared_ptr dict_info; - if (CanUseDictSurvivingJoin(op, *lstate.hash_table, can_use_perfect_hash, build_side_multi_source)) { + if (CanUseDictSurvivingJoin(op, *lstate.hash_table, 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. @@ -909,7 +880,7 @@ SinkResultType PhysicalHashJoin::Sink(ExecutionContext &context, DataChunk &chun lstate.join_keys.Reset(); lstate.join_key_executor.Execute(chunk, lstate.join_keys); - if (filter_pushdown && !gstate.skip_filter_pushdown) { + if (lstate.local_filter_state) { filter_pushdown->Sink(lstate.join_keys, *lstate.local_filter_state); } @@ -966,7 +937,7 @@ SinkCombineResultType PhysicalHashJoin::Combine(ExecutionContext &context, Opera auto &client_profiler = QueryProfiler::Get(context.client); context.thread.profiler.Flush(*this); client_profiler.Flush(context.thread.profiler); - if (filter_pushdown && !gstate.skip_filter_pushdown) { + if (lstate.local_filter_state) { filter_pushdown->Combine(*gstate.global_filter_state, *lstate.local_filter_state); } @@ -977,22 +948,28 @@ SinkCombineResultType PhysicalHashJoin::Combine(ExecutionContext &context, Opera // Finalize //===--------------------------------------------------------------------===// -static constexpr idx_t PARALLEL_CONSTRUCT_THRESHOLD = 1048576; -static constexpr double SKEW_SINGLE_THREADED_THRESHOLD = 0.33; +struct HashJoinBuildConfig { + static constexpr idx_t PARALLEL_CONSTRUCT_THRESHOLD = 1048576; + static constexpr idx_t SMALL_PARALLEL_CONSTRUCT_THRESHOLD = 65536; + static constexpr idx_t SMALL_PARALLEL_MIN_THREADS = 4; + static constexpr double SKEW_SINGLE_THREADED_THRESHOLD = 0.33; + static constexpr double SMALL_BUILD_SKEW_THRESHOLD = 0.20; +}; //! If the data is very skewed (many of the exact same key), our finalize will become slow, //! due to completely slamming the same atomic using compare-and-swaps. //! We can detect this because we partition the data, and go for a single-threaded finalize instead. -static bool KeysAreSkewed(const HashJoinGlobalSinkState &sink) { +static bool KeysAreSkewed(const HashJoinGlobalSinkState &sink, + double threshold = HashJoinBuildConfig::SKEW_SINGLE_THREADED_THRESHOLD) { const auto max_partition_ht_size = sink.max_partition_size + sink.hash_table->PointerTableSize(sink.max_partition_count); const auto skew = static_cast(max_partition_ht_size) / static_cast(sink.total_size); - return skew > SKEW_SINGLE_THREADED_THRESHOLD; + return skew > threshold; } //! If we have only one thread, always finalize single-threaded. Otherwise, we finalize in parallel if we -//! have more than 1M rows or if we want to verify parallelism. -static bool FinalizeSingleThreaded(const HashJoinGlobalSinkState &sink, const bool consider_skew) { +//! have at least 1M rows, an unskewed medium input with enough threads, or want to verify parallelism. +static bool FinalizeSingleThreaded(const HashJoinGlobalSinkState &sink) { // if only one thread, finalize single-threaded const auto num_threads = NumericCast(sink.num_threads); if (num_threads == 1) { @@ -1004,14 +981,15 @@ static bool FinalizeSingleThreaded(const HashJoinGlobalSinkState &sink, const bo return false; } - // finalize single-threaded if we have less than 1M rows const auto &ht = *sink.hash_table; - const bool ht_is_small = ht.Count() < PARALLEL_CONSTRUCT_THRESHOLD; - - if (consider_skew) { - return ht_is_small || KeysAreSkewed(sink); + if (ht.Count() >= HashJoinBuildConfig::PARALLEL_CONSTRUCT_THRESHOLD) { + return false; + } + if (num_threads < HashJoinBuildConfig::SMALL_PARALLEL_MIN_THREADS || + ht.Count() < HashJoinBuildConfig::SMALL_PARALLEL_CONSTRUCT_THRESHOLD) { + return true; } - return ht_is_small; + return KeysAreSkewed(sink, HashJoinBuildConfig::SMALL_BUILD_SKEW_THRESHOLD); } static idx_t GetTupleWidth(const vector &types, bool &all_constant) { @@ -1082,10 +1060,10 @@ static void ExecuteHashJoinTableInitTask(HashJoinGlobalSinkState &sink, idx_t en } struct PrefixRangeBuildLane { - explicit PrefixRangeBuildLane(unique_ptr state_p) : state(std::move(state_p)) { + explicit PrefixRangeBuildLane(JoinHashTable::PrefixRangeBuildStates states_p) : states(std::move(states_p)) { } - unique_ptr state; + JoinHashTable::PrefixRangeBuildStates states; idx_t task_count = 0; }; @@ -1096,13 +1074,13 @@ struct JoinBuildRange { static void ExecuteHashJoinFinalizeTask(HashJoinGlobalSinkState &sink, const JoinBuildRange &chunk_range, bool parallel, optional_ptr prefix_range_lane) { - optional_ptr prefix_range_state; + optional_ptr prefix_range_states; bool prefix_range_parallel = false; if (prefix_range_lane) { - prefix_range_state = *prefix_range_lane->state; + prefix_range_states = prefix_range_lane->states; prefix_range_parallel = prefix_range_lane->task_count > 1; } - sink.hash_table->Finalize(chunk_range.begin, chunk_range.end, parallel, prefix_range_state, prefix_range_parallel); + 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); @@ -1284,7 +1262,7 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { vector> GetTasks() { auto &ht = *sink.hash_table; auto &data_collection = ht.GetDataCollection(); - const bool parallel = !FinalizeSingleThreaded(sink, false) && ht.GetRadixBits() != 0; + const bool parallel = !FinalizeSingleThreaded(sink) && ht.GetRadixBits() != 0; const auto partitions = RadixPartitioning::NumberOfPartitions(ht.GetRadixBits()); queue = make_uniq(partitions); if (!parallel) { @@ -1343,7 +1321,7 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { private: void FinishTasks() { for (auto &lane : prefix_range_lanes) { - sink.hash_table->MergePrefixRangeBuildState(*lane->state); + sink.hash_table->MergePrefixRangeBuildState(lane->states); } sink.hash_table->GetDataCollection().VerifyEverythingPinned(); @@ -1367,11 +1345,12 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { if (!ht.ShouldBuildPrefixRangeFilter() || task_count == 0) { return; } - // Bound replicated PRF state independently of the number of radix partitions. - static constexpr idx_t MAX_PREFIX_RANGE_BUILD_MEMORY = 16ULL * 1024ULL * 1024ULL; const auto state_size = ht.GetPrefixRangeBuildStateSize(); D_ASSERT(state_size > 0); - const auto lanes_within_budget = MaxValue(MAX_PREFIX_RANGE_BUILD_MEMORY / state_size, 1); + 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 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); for (idx_t lane_idx = 0; lane_idx < lane_count; lane_idx++) { @@ -1388,10 +1367,10 @@ void HashJoinGlobalSinkState::ScheduleFinalize(Pipeline &pipeline, Event &event) hash_table->finalized = true; return; } - hash_table->AllocatePointerTable(!external && !FinalizeSingleThreaded(*this, false)); + hash_table->AllocatePointerTable(!external && !FinalizeSingleThreaded(*this)); auto new_init_event = make_shared_ptr(pipeline, *this); - if (FinalizeSingleThreaded(*this, false)) { + if (FinalizeSingleThreaded(*this)) { new_init_event->ExecuteDirectly(); auto new_finalize_event = make_shared_ptr(pipeline, *this); new_finalize_event->ExecuteDirectly(); @@ -1415,7 +1394,7 @@ void HashJoinGlobalSinkState::InitializeProbeSpill() { //! scheduled. Every input is accumulated during Sink, so it does not matter which partitions are materialized. static void FinalizeExternalRuntimeFilters(ClientContext &context, const PhysicalHashJoin &op, HashJoinGlobalSinkState &sink) { - if (!op.filter_pushdown || sink.skip_filter_pushdown) { + if (!sink.global_filter_state) { return; } auto &ht = *sink.hash_table; @@ -1548,19 +1527,6 @@ bool JoinFilterPushdownInfo::CanUseBloomFilter(const JoinFilterPushdownFilter &i return false; } - // and only if there is exactly one equality condition - // as the Filter API only allows single-column filters so far - idx_t equality_column_count = 0; - for (auto &cond : ht->conditions) { - const auto cond_cmp = cond.GetComparisonType(); - if (cond_cmp == ExpressionType::COMPARE_EQUAL || cond_cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM) { - equality_column_count++; - } - } - if (equality_column_count != 1) { - return false; - } - auto build_count = ht->Count(); if (build_count == 0) { build_count = ht->GetSinkCollection().Count(); @@ -1580,17 +1546,12 @@ bool JoinFilterPushdownInfo::CanUseBloomFilter(const JoinFilterPushdownFilter &i return false; } - return true; -} - -bool JoinFilterPushdownInfo::CanUsePrefixRangeFilter(const JoinFilterPushdownFilter &info, const ClientContext &context, - const PhysicalComparisonJoin &op, optional_ptr ht, - const ExpressionType &cmp) const { - if (!CanUseBloomFilter(info, context, op, cmp, ht)) { + // 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; } - const auto &key_type = ht->conditions[0].GetLHS().GetReturnType(); - return PrefixRangeFilter::SupportedType(key_type); + + return true; } static unique_ptr CreateSelectivityOptionalExpressionFilter(unique_ptr child_expr, @@ -1626,25 +1587,25 @@ static unique_ptr RetainRuntimeFilterNulls(unique_ptr fi void JoinFilterPushdownInfo::DeferRuntimeFilter(DeferredRuntimeFilterType type, const PhysicalOperator &op, const JoinFilterPushdownFilter &info, const JoinFilterPushdownColumn &column, ProjectionIndex filter_col_idx, - JoinFilterGlobalState &gstate) const { - gstate.deferred_runtime_filters.push_back({type, &op, info.dynamic_filters, column, 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, const Value &min_val, - const Value &max_val, idx_t max_bits, + 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()) { - const auto key_type = ht.conditions[0].GetLHS().GetReturnType(); + 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(std::move(prefix_filter)); + ht.SetPrefixRangeFilter(key_idx, std::move(prefix_filter)); ht.SetBuildPrefixRangeFilter(); } - DeferRuntimeFilter(DeferredRuntimeFilterType::PREFIX_RANGE, op, info, column, filter_col_idx, gstate); + DeferRuntimeFilter(DeferredRuntimeFilterType::PREFIX_RANGE, op, info, column, filter_col_idx, key_idx, gstate); return true; } @@ -1707,11 +1668,12 @@ static const char *GetRuntimeFilterReconstructionModeName(JoinFilterPushdownMode static unique_ptr CreateRuntimeFilterExpression(ClientContext &context, JoinHashTable &ht, const DeferredRuntimeFilterPushdown &deferred, float selectivity_threshold, idx_t n_vectors_to_check) { - const auto key_name = ht.conditions[0].GetRHS().ToString(); - const auto key_type = ht.conditions[0].GetLHS().GetReturnType(); + 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(0); + const auto filters_null_values = !input.preserves_cast_errors && !ht.NullValuesAreEqual(key_idx); vector> children; children.push_back(std::move(input.expression)); @@ -1720,10 +1682,10 @@ static unique_ptr CreateRuntimeFilterExpression(ClientContext &conte 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()) { + if (!ht.HasPublishableBloomFilter(key_idx)) { return nullptr; } - auto bloom_filter = ht.GetBloomFilter(); + 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( @@ -1733,7 +1695,7 @@ static unique_ptr CreateRuntimeFilterExpression(ClientContext &conte break; } case DeferredRuntimeFilterType::PREFIX_RANGE: { - auto prefix_range_filter = ht.GetPrefixRangeFilter(); + 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; @@ -1935,28 +1897,47 @@ static idx_t BloomFilterBitBudget(idx_t ht_count) { return BloomFilter::GetNumberOfSectors(ht_count) * 64; } -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; // There are no table sources in which we can push down filters - } +struct JoinFilterPushdownCandidate { + const JoinFilterPushdownFilter &info; + const JoinFilterPushdownColumn &column; + Value min_val; + Value max_val; + bool reconstruct_expression; + bool can_emit_runtime_filter; +}; - // create a filter for each column that reached a table scan - for (auto &info : probe_info) { +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 < join_condition.size()); - const auto cmp = op.conditions[join_condition[filter_idx]].GetComparisonType(); - auto &filter_col_idx = pushdown_column.probe_column_index.column_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_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; @@ -1986,86 +1967,142 @@ unique_ptr JoinFilterPushdownInfo::FinalizeFilters(ClientContext &con auto condition_type = min_val.type(); auto runtime_filter_input_type = RuntimeFilterCastUtil::GetRuntimeFilterInputType(pushdown_column, condition_type); - bool can_emit_runtime_filters = pushdown_column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION; - if (can_emit_runtime_filters && ht) { - can_emit_runtime_filters = runtime_filter_input_type == ht->conditions[0].GetLHS().GetReturnType(); - } - - if (Value::NotDistinctFrom(min_val, max_val)) { - // min = max - single value - // generate a "one-sided" comparison filter for the LHS - // Note that this also works for equalities. - 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))); - } - } else { - if (cmp != ExpressionType::COMPARE_EQUAL && !retain_nulls) { - // min != max - generate range filters for non-equality comparisons. - // For non-equalities, the range must be half-open. - CreateDynamicMinMaxFilters(op, info, context, pushdown_column, filter_col_idx, cmp, min_val, - max_val, condition_type, reconstruct_filter_expression, true); - continue; - } + 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; + } - 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 && gstate && - CanUsePrefixRangeFilter(info, context, op, ht, cmp) && can_compute_span; + 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 (CanUseInFilter(context, ht, cmp)) { - pushed_in_filter = - PushInFilter(context, info, pushdown_column, *ht, op, filter_idx, filter_col_idx); - } + 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; - if (can_emit_prf && span < SMALL_EXACT_PRF_BITS && - TryRegisterPrefixRangeFilter(info, context, *ht, op, pushdown_column, filter_col_idx, - min_val_before_cast, max_val_before_cast, SMALL_EXACT_PRF_BITS, - *gstate)) { - continue; - } + 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) { - auto build_count = ht->Count(); - if (build_count == 0) { - build_count = ht->GetSinkCollection().Count(); - } - const auto bloom_filter_bits = BloomFilterBitBudget(build_count); - if (span <= bloom_filter_bits && - TryRegisterPrefixRangeFilter(info, context, *ht, op, pushdown_column, filter_col_idx, - min_val_before_cast, max_val_before_cast, bloom_filter_bits, - *gstate)) { - continue; - } - } + 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 (allow_bloom_filters && can_emit_runtime_filters && ht && gstate && - CanUseBloomFilter(info, context, op, cmp, ht)) { - if (ht->HasPublishableBloomFilter()) { - // a complete filter was accumulated during Sink (external joins build it there) - DeferRuntimeFilter(DeferredRuntimeFilterType::BLOOM_FILTER, op, info, pushdown_column, - filter_col_idx, *gstate); - } else if (allow_prefix_range_filters) { - // like a prefix-range filter, a bloom filter may be built during finalize when the - // finalize materializes the whole build side - an external finalize does not - ht->SetBuildBloomFilter(true); - DeferRuntimeFilter(DeferredRuntimeFilterType::BLOOM_FILTER, op, info, pushdown_column, - filter_col_idx, *gstate); - } - } - } + 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; } @@ -2115,7 +2152,6 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl // 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.perfect_join_executor.reset(); 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 @@ -2153,47 +2189,14 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl sink.owned_local_hash_tables.clear(); ht.Unpartition(); - Value min; - Value max; - unique_ptr filter_min_max = nullptr; - - if (filter_pushdown && !sink.skip_filter_pushdown && ht.Count() > 0) { - filter_min_max = filter_pushdown->FinalizeMinMax(*sink.global_filter_state); - min = filter_min_max->data[0].GetValue(0); - max = filter_min_max->data[1].GetValue(0); - } else if (TypeIsIntegral(conditions[0].GetRHS().GetReturnType().InternalType())) { - min = Value::MinimumValue(conditions[0].GetRHS().GetReturnType()); - max = Value::MaximumValue(conditions[0].GetRHS().GetReturnType()); - } - - // check for possible perfect hash table - auto use_perfect_hash = sink.perfect_join_executor->CanDoPerfectHashJoin(*this, min, max); - // PHJ's FullScanHashTable reads payload at native width; if any slot was narrowed it would crash. Runtime - // min/max from filter pushdown can re-enable PHJ here, so re-check after dict-surviving may have narrowed. - if (use_perfect_hash && sink.DictSurvivingActive()) { - use_perfect_hash = false; - } - if (use_perfect_hash) { - use_perfect_hash = sink.perfect_join_executor->BuildPerfectHashTable(); - } - - if (!use_perfect_hash) { - sink.perfect_join_executor.reset(); - } + const auto use_perfect_hash = ht.TryInitializePerfectHashTable(); - if (filter_min_max) { + if (sink.global_filter_state && ht.Count() > 0) { + auto filter_min_max = filter_pushdown->FinalizeMinMax(*sink.global_filter_state); filter_pushdown->FinalizeFilters(context, *this, std::move(filter_min_max), &ht, !use_perfect_hash, true, sink.global_filter_state.get()); - if (use_perfect_hash) { - ht.BuildPrefixRangeFilter(); - PublishDeferredRuntimeFilters(context, ht, *sink.global_filter_state); - } - } - - // In case of a large build side or duplicates, use regular hash join - if (!use_perfect_hash) { - sink.ScheduleFinalize(pipeline, event); } + sink.ScheduleFinalize(pipeline, event); sink.finalized = true; if (ht.Count() == 0 && EmptyResultIfRHSIsEmpty()) { return SinkFinalizeType::NO_OUTPUT_POSSIBLE; @@ -2212,7 +2215,7 @@ 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.perfect_join_executor) { + if (!sink.hash_table->SupportsCompressedProbe()) { return false; } if (conditions.size() != 1) { @@ -2245,7 +2248,6 @@ class HashJoinOperatorState : public CachingOperatorState { ExpressionExecutor probe_executor; JoinHashTable::ScanStructure scan_structure; - unique_ptr perfect_hash_join_state; JoinHashTable::ProbeSpillLocalAppendState spill_state; JoinHashTable::ProbeState probe_state; @@ -2254,6 +2256,7 @@ class HashJoinOperatorState : public CachingOperatorState { public: void Finalize(const PhysicalOperator &op, ExecutionContext &context) override { + scan_structure.dictionary_gather_state.Reset(); context.thread.profiler.Flush(op); } @@ -2267,7 +2270,6 @@ class HashJoinOperatorState : public CachingOperatorState { lhs_probe_data.Reset(); lhs_output_data.Reset(); scan_structure.Reset(); - perfect_hash_join_state.reset(); spill_state = JoinHashTable::ProbeSpillLocalAppendState(); TupleDataCollection::InitializeChunkState(join_key_state, op.condition_types); if (spill_chunk.ColumnCount() != 0) { @@ -2277,7 +2279,6 @@ class HashJoinOperatorState : public CachingOperatorState { if (probe_state.dict_state) { probe_state.dict_state = make_uniq(); } - // perfect_hash_join_state will be lazily initialized on first Execute when we have a real ExecutionContext } }; @@ -2300,10 +2301,6 @@ unique_ptr PhysicalHashJoin::GetOperatorState(ExecutionContext &c } TupleDataCollection::InitializeChunkState(state->join_key_state, condition_types); - if (sink.perfect_join_executor) { - state->perfect_hash_join_state = sink.perfect_join_executor->GetOperatorState(context); - } - if (sink.external) { state->spill_chunk.InitializeEmpty(sink.probe_types); sink.InitializeProbeSpill(); @@ -2354,18 +2351,6 @@ OperatorResultType PhysicalHashJoin::ExecuteInternal(ExecutionContext &context, return OperatorResultType::NEED_MORE_INPUT; } - if (sink.perfect_join_executor) { - D_ASSERT(!sink.external); - // Lazily initialize perfect_hash_join_state on first use if needed - if (!state.perfect_hash_join_state) { - state.perfect_hash_join_state = sink.perfect_join_executor->GetOperatorState(context); - } - // for perfect hash join, when predicate is NULL, only output columns are needed - state.lhs_output_data.ReferenceColumns(input, lhs_output_columns.col_idxs); - return sink.perfect_join_executor->ProbePerfectHashTable(context, input, state.lhs_output_data, chunk, - *state.perfect_hash_join_state); - } - if (sink.external && !state.initialized) { // some initialization for external hash join if (!sink.probe_spill) { @@ -2873,8 +2858,9 @@ void HashJoinLocalSourceState::ExternalScanHT(HashJoinGlobalSinkState &sink, Has D_ASSERT(local_stage == HashJoinSourceStage::SCAN_HT); if (!full_outer_scan_state) { - full_outer_scan_state = make_uniq(sink.hash_table->GetDataCollection(), - full_outer_chunk_idx_from, full_outer_chunk_idx_to); + full_outer_scan_state = + make_uniq(sink.hash_table->GetDataCollection(), full_outer_chunk_idx_from, + full_outer_chunk_idx_to, sink.hash_table->output_columns.size()); full_outer_chunks_reported = 0; } sink.hash_table->ScanFullOuter(*full_outer_scan_state, addresses, chunk); 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 8f2ec43d1..19057fd8f 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp @@ -442,8 +442,11 @@ SinkResultType PhysicalBatchInsert::Sink(ExecutionContext &context, DataChunk &i // we are not processing the current min batch index // check if we have exceeded the maximum number of unflushed rows if (memory_manager.OutOfMemory(batch_index)) { - // out-of-memory - // execute tasks while we wait (if any are available) + // try to free memory by merging finished batches and executing any pending tasks + { + annotated_lock_guard l(gstate.lock); + gstate.ScheduleMergeTasks(context.client, memory_manager.GetMinimumBatchIndex()); + } ExecuteTasks(context.client, gstate, lstate); const annotated_lock_guard guard {memory_manager.lock}; diff --git a/src/duckdb/src/execution/operator/persistent/physical_merge_into.cpp b/src/duckdb/src/execution/operator/persistent/physical_merge_into.cpp index d1f3cdb22..2a4d0c5db 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_merge_into.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_merge_into.cpp @@ -3,7 +3,6 @@ #include "duckdb/parallel/pipeline_broadcast_exchange.hpp" #include "duckdb/execution/operator/projection/physical_projection.hpp" #include "duckdb/execution/physical_plan_generator.hpp" -#include "duckdb/execution/row_id_deduplicator.hpp" #include "duckdb/parallel/meta_pipeline.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/parallel/task_scheduler.hpp" @@ -11,7 +10,6 @@ #include "duckdb/parser/query_node/merge_query_node.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" -#include "duckdb/common/types/vector.hpp" namespace duckdb { @@ -352,8 +350,7 @@ class MergeIntoLocalState : public LocalSinkState { class MergeIntoGlobalState : public GlobalSinkState { public: - MergeIntoGlobalState(ClientContext &context, const PhysicalMergeInto &op) - : op(op), matched_rows(context, GetRowIdTypes(op)) { + MergeIntoGlobalState(ClientContext &context, const PhysicalMergeInto &op) : op(op) { merged_count = 0; for (auto &action : op.actions) { shared_ptr exchange; @@ -376,34 +373,10 @@ class MergeIntoGlobalState : public GlobalSinkState { } } - static vector GetRowIdTypes(const PhysicalMergeInto &op) { - auto &input_types = op.children[0].get().types; - if (op.row_id_index >= input_types.size()) { - throw InternalException("MERGE row ID index is out of range"); - } - auto row_id_offset = NumericCast::difference_type>(op.row_id_index); - return vector(input_types.begin() + row_id_offset, input_types.end()); - } - const PhysicalMergeInto &op; //! The exchange of every action - NULL for actions that have no operator to push data into vector> exchanges; atomic merged_count; - //! Target row-ids already matched by a WHEN MATCHED modifying action, to detect a second action on a row. - mutex match_lock; - RowIdDeduplicator matched_rows; - - //! Record the matched target rows; throw if any row was already matched (cardinality violation). A distinct - //! count below the input count means a row ID repeated. - void CheckMatchedRows(DataChunk &matched, idx_t row_id_index) { - lock_guard glock(match_lock); - auto distinct = matched_rows.Register(matched, row_id_index); - if (distinct != matched.size()) { - throw InvalidInputException( - "MERGE INTO command cannot affect the same target row more than once. A target row matched more " - "than one source row; ensure the source rows are deduplicated or the ON condition is unique."); - } - } SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, MergeIntoLocalState &local_state, OperatorSinkInput &input, MergeActionRange range, idx_t &index_in_match) { @@ -419,15 +392,6 @@ class MergeIntoGlobalState : public GlobalSinkState { // no data for this action - move to next action continue; } - // A WHEN MATCHED update/delete must not affect the same target row twice (cardinality violation). - // Checked here, on the freshly condition-selected rows (which still carry the row-id column), so - // rows filtered out by the action condition are not counted - matching PostgreSQL. Runs once per - // input chunk: on a BLOCKED resume input_chunk is still set and we skip re-checking. - if (range.condition == MergeActionCondition::WHEN_MATCHED && - (action->action_type == MergeActionType::MERGE_UPDATE || - action->action_type == MergeActionType::MERGE_DELETE)) { - CheckMatchedRows(*input_chunk, op.row_id_index); - } } // process the action if (!action->op) { diff --git a/src/duckdb/src/execution/operator/persistent/physical_update.cpp b/src/duckdb/src/execution/operator/persistent/physical_update.cpp index d12db2446..165d985a5 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_update.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_update.cpp @@ -24,13 +24,12 @@ PhysicalUpdate::PhysicalUpdate(PhysicalPlan &physical_plan, vector vector> expressions, vector> bound_defaults, vector> bound_constraints, idx_t estimated_cardinality, - bool return_chunk, bool capture_old_rows, vector old_row_columns, - RowIdHandling row_id_handling) + bool return_chunk, bool capture_old_rows, vector old_row_columns) : PhysicalOperator(physical_plan, PhysicalOperatorType::UPDATE, std::move(types), estimated_cardinality), tableref(tableref), table(table), columns(std::move(columns)), expressions(std::move(expressions)), bound_defaults(std::move(bound_defaults)), bound_constraints(std::move(bound_constraints)), return_chunk(return_chunk), capture_old_rows(capture_old_rows), old_row_columns(std::move(old_row_columns)), - row_id_handling(row_id_handling), index_update(false) { + index_update(false) { auto &indexes = table.GetDataTableInfo().get()->GetIndexes(); auto index_columns = indexes.GetIndexedColumns(); @@ -58,9 +57,9 @@ PhysicalUpdate::PhysicalUpdate(PhysicalPlan &physical_plan, vector class UpdateGlobalState : public GlobalSinkState { public: explicit UpdateGlobalState(ClientContext &context, const vector &return_types, - RowIdHandling row_id_handling) + bool update_is_del_and_insert) : updated_count(0), return_collection(context, return_types) { - if (row_id_handling != RowIdHandling::ASSUME_UNIQUE) { + if (update_is_del_and_insert) { updated_rows = make_uniq(context, vector {LogicalType::ROW_TYPE}); } } @@ -203,71 +202,44 @@ SinkResultType PhysicalUpdate::Sink(ExecutionContext &context, DataChunk &chunk, // Regular in-place update. if (!update_is_del_and_insert) { - // Apply the duplicate row-id policy: ASSUME_UNIQUE keeps the lock-free path; KEEP_FIRST (UPDATE ... FROM) - // deduplicates so each row is updated at most once, keeping RETURNING and transition tables predictable. - idx_t update_count = update_chunk.size(); - SelectionVector sel; - Vector update_row_ids(Vector::Ref(row_ids)); - const bool deduplicate = row_id_handling != RowIdHandling::ASSUME_UNIQUE; - if (deduplicate) { - sel.Initialize(update_chunk.size()); - lock_guard glock(g_state.lock); - D_ASSERT(g_state.updated_rows); - update_count = g_state.updated_rows->Register(row_ids, update_chunk.size(), sel); - if (row_id_handling == RowIdHandling::ERROR && update_count != update_chunk.size()) { - throw InvalidInputException("UPDATE command cannot update the same row more than once"); - } - if (update_count != update_chunk.size()) { - update_chunk.Slice(sel, update_count); - update_row_ids.Slice(row_ids, sel, update_count); - } - } - if (return_chunk) { // (re)reference all output columns first, then validate + set the cardinality. mock_chunk is not reset // here, but with return_chunk the update projects every table column, so all columns are referenced. for (idx_t i = 0; i < columns.size(); i++) { mock_chunk.data[columns[i].index].Reference(update_chunk.data[i]); } - mock_chunk.CheckCardinality(update_count); + mock_chunk.CheckCardinality(update_chunk.size()); } auto &update_state = l_state.GetUpdateState(table, tableref, context.client); - table.Update(update_state, context.client, tableref, update_row_ids, columns, update_chunk); + table.Update(update_state, context.client, tableref, row_ids, columns, update_chunk); if (return_chunk) { lock_guard glock(g_state.lock); if (capture_old_rows) { - // When we deduplicated, apply the selection vector to the OLD columns so they line up with NEW. + // In-place update: every input row is affected, so no selection vector is needed. AppendReturnRows(g_state.return_collection, l_state.combined_chunk, mock_chunk, chunk, - mock_chunk.ColumnCount(), old_row_columns, update_count, deduplicate ? &sel : nullptr); + mock_chunk.ColumnCount(), old_row_columns, update_chunk.size(), nullptr); } else { g_state.return_collection.Append(mock_chunk); } } - g_state.updated_count += update_count; + g_state.updated_count += chunk.size(); return SinkResultType::NEED_MORE_INPUT; } // We update an index or a complex type, so we need to split the UPDATE into DELETE + INSERT. - // Apply the duplicate row-id policy. This path holds the lock for its whole body (the append is serialized), - // so deduplication runs under it. ASSUME_UNIQUE (plain UPDATE and MERGE-driven updates) keeps every row; - // KEEP_FIRST (UPDATE ... FROM) drops repeated row-ids so we never delete+insert the same row twice. + // Keep track of the rows that have not yet been deleted in this UPDATE. + // This is required since we might see the same row_id multiple times, e.g., + // during an UPDATE containing joins. SelectionVector sel(update_chunk.size()); lock_guard glock(g_state.lock); - idx_t update_count = update_chunk.size(); - const bool deduplicate = row_id_handling != RowIdHandling::ASSUME_UNIQUE; - if (deduplicate) { - D_ASSERT(g_state.updated_rows); - update_count = g_state.updated_rows->Register(row_ids, update_chunk.size(), sel); - if (row_id_handling == RowIdHandling::ERROR && update_count != update_chunk.size()) { - throw InvalidInputException("UPDATE command cannot update the same row more than once"); - } - } + D_ASSERT(g_state.updated_rows); + auto update_count = g_state.updated_rows->Register(row_ids, update_chunk.size(), sel); // The update chunk now contains exactly those rows that we are deleting. Vector del_row_ids(Vector::Ref(row_ids)); - if (deduplicate && update_count != update_chunk.size()) { + if (update_count != update_chunk.size()) { update_chunk.Slice(sel, update_count); del_row_ids.Slice(row_ids, sel, update_count); } @@ -310,20 +282,20 @@ SinkResultType PhysicalUpdate::Sink(ExecutionContext &context, DataChunk &chunk, table.LocalAppend(tableref, context.client, mock_chunk, bound_constraints, del_row_ids, delete_chunk); if (return_chunk) { if (capture_old_rows) { - // Apply the dedup selection vector to the OLD columns so they line up with the NEW image. + // Apply the dedup/del+insert selection vector to the OLD columns so they line up with the NEW image. AppendReturnRows(g_state.return_collection, l_state.combined_chunk, mock_chunk, chunk, - mock_chunk.ColumnCount(), old_row_columns, update_count, deduplicate ? &sel : nullptr); + mock_chunk.ColumnCount(), old_row_columns, update_count, &sel); } else { g_state.return_collection.Append(mock_chunk); } } - g_state.updated_count += update_count; + g_state.updated_count += chunk.size(); return SinkResultType::NEED_MORE_INPUT; } unique_ptr PhysicalUpdate::GetGlobalSinkState(ClientContext &context) const { - return make_uniq(context, GetTypes(), row_id_handling); + return make_uniq(context, GetTypes(), update_is_del_and_insert); } unique_ptr PhysicalUpdate::GetLocalSinkState(ExecutionContext &context) const { diff --git a/src/duckdb/src/execution/operator/projection/physical_unnest.cpp b/src/duckdb/src/execution/operator/projection/physical_unnest.cpp index 9b9731fee..63d860a1d 100644 --- a/src/duckdb/src/execution/operator/projection/physical_unnest.cpp +++ b/src/duckdb/src/execution/operator/projection/physical_unnest.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/vector/constant_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -79,7 +80,7 @@ void UnnestOperatorState::PrepareInput(DataChunk &input, const vector diff --git a/src/duckdb/src/execution/perfect_hash_join_table.cpp b/src/duckdb/src/execution/perfect_hash_join_table.cpp new file mode 100644 index 000000000..80bb00886 --- /dev/null +++ b/src/duckdb/src/execution/perfect_hash_join_table.cpp @@ -0,0 +1,360 @@ +#include "duckdb/execution/perfect_hash_join_table.hpp" + +#include "duckdb/common/array.hpp" +#include "duckdb/common/types/row/tuple_data_layout.hpp" +#include "duckdb/execution/ht_entry.hpp" + +namespace duckdb { + +PerfectHashJoinTable::~PerfectHashJoinTable() { +} + +void PerfectHashJoinTable::InitializeEntries(idx_t from, idx_t to) { + memset(entries.get() + from * sizeof(uint64_t), 0, (to - from) * sizeof(uint64_t)); +} + +void PerfectHashJoinTable::ConvertToDictionary(idx_t pointer_offset) { + D_ASSERT(type == Type::ROWS); + auto directory = GetEntries(); + for (auto &entry : directory) { + if (entry) { + // One-based dictionary positions preserve zero as the miss sentinel. + entry = static_cast(Load(cast_uint64_to_pointer(entry) + pointer_offset)) + 1; + } + } + type = Type::DICTIONARY; +} + +template +static uhugeint_t KeyDistance(T max, T min) { + return uhugeint_t(0, static_cast(max) - static_cast(min)); +} + +template <> +uhugeint_t KeyDistance(hugeint_t max, hugeint_t min) { + return uhugeint_t(static_cast(max.upper) - static_cast(min.upper) - (max.lower < min.lower), + max.lower - min.lower); +} + +template <> +uhugeint_t KeyDistance(uhugeint_t max, uhugeint_t min) { + return uhugeint_t(max.upper - min.upper - (max.lower < min.lower), max.lower - min.lower); +} + +template +class TypedPerfectHashJoinTable : public PerfectHashJoinTable { +public: + TypedPerfectHashJoinTable(Type type, bool nulls_equal) : PerfectHashJoinTable(type, nulls_equal) { + } + + void UpdateBounds(const Vector &keys) override { + if (range_too_large) { + return; + } + auto values = keys.Values(); + const auto count = + keys.GetVectorType() == VectorType::CONSTANT_VECTOR ? MinValue(keys.size(), 1) : keys.size(); + T chunk_min {}; + T chunk_max {}; + bool has_values = false; + for (idx_t i = 0; i < count; i++) { + auto entry = values[i]; + if (entry.IsValid()) { + const auto value = entry.GetValue(); + chunk_min = has_values ? MinValue(chunk_min, value) : value; + chunk_max = has_values ? MaxValue(chunk_max, value) : value; + has_values = true; + } + } + if (has_values) { + WidenBounds(chunk_min, chunk_max); + } + CheckRange(); + } + + void MergeBounds(const PerfectHashJoinTable &other_p) override { + auto &other = static_cast(other_p); + range_too_large = range_too_large || other.range_too_large; + if (!range_too_large && other.has_bounds) { + WidenBounds(other.min, other.max); + CheckRange(); + } + } + + bool Initialize(Allocator &allocator, idx_t build_count, idx_t pointer_table_size) override { + if (range_too_large || build_count == 0) { + return false; + } + // 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 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) { + return false; + } + entries = allocator.Allocate(bytes); + return true; + } + + bool Insert(const Vector &rows, const TupleDataLayout &layout, idx_t pointer_offset, bool parallel) override { + auto row_values = rows.Values(); + const auto key_offset = layout.GetOffsets()[0]; + const auto column_count = layout.ColumnCount(); + auto directory = GetEntries(); + auto atomic_directory = GetAtomicEntries(); + bool has_chains = false; + for (auto entry : row_values) { + auto row = entry.GetValue(); + const auto valid = TemplatedValidityMask(row, column_count).RowIsValid(0); + if (!valid && !nulls_equal) { + continue; + } + 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); + if (parallel) { + auto &word = atomic_directory[slot / 64]; + if (!(word.load(std::memory_order_relaxed) & mask)) { + word.fetch_or(mask, std::memory_order_relaxed); + } + } else { + directory[slot / 64] |= mask; + } + } else { + const auto pointer = cast_pointer_to_uint64(row); + const auto previous = + parallel ? atomic_directory[slot].exchange(pointer, std::memory_order_relaxed) : directory[slot]; + if (!parallel) { + directory[slot] = pointer; + } + Store(previous, row + pointer_offset); + has_chains = has_chains || previous != 0; + } + } + return has_chains; + } + + void GetRowPointers(const Vector &keys, optional_ptr sel, idx_t &count, Vector &pointers, + SelectionVector &matches) const override { + D_ASSERT(GetType() == Type::ROWS); + auto values = keys.Values(); + auto directory = GetEntries(); + FlatVector::SetSize(pointers, count_t(keys.size())); + auto writer = FlatVector::ScatterWriter(pointers); + idx_t match_count = 0; + for (idx_t i = 0; i < count; i++) { + const auto row = sel ? sel->get_index(i) : i; + auto entry = values[row]; + uint64_t pointer = 0; + if (!entry.IsValid()) { + pointer = directory[domain_size]; + } else if (InRange(entry.GetValue())) { + pointer = directory[GetIndex(entry.GetValue())]; + } + writer[row] = cast_uint64_to_pointer(pointer); + if (pointer) { + matches.set_index(match_count++, row); + } + } + count = match_count; + } + + idx_t ProbeMembership(const Vector &keys, unsafe_unique_array &found_match) const override { + D_ASSERT(IsBitmap()); + D_ASSERT(keys.size() <= STANDARD_VECTOR_SIZE); + auto values = keys.Values(); + 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 match_count; + } + + idx_t ProbeDictionary(const Vector &keys, SelectionVector &probe_sel, SelectionVector &build_sel) const override { + D_ASSERT(GetType() == Type::DICTIONARY); + auto values = keys.Values(); + auto directory = GetEntries(); + idx_t count = 0; + for (idx_t i = 0; i < values.size(); i++) { + auto entry = values[i]; + uint64_t position = 0; + if (!entry.IsValid()) { + position = directory[domain_size]; + } else if (InRange(entry.GetValue())) { + position = directory[GetIndex(entry.GetValue())]; + } + if (position) { + probe_sel.set_index(count, i); + build_sel.set_index(count++, position - 1); + } + } + return count; + } + +private: + bool ShouldPrefetchMembership(const VectorIterator &keys) const { +#if defined(__GNUC__) || defined(__clang__) + if (keys.size() < PREFETCH_MIN_COUNT || EntryCount() * sizeof(uint64_t) <= PREFETCH_MIN_BYTES) { + return false; + } + constexpr idx_t SAMPLE_COUNT = 32; + array sampled_words; + idx_t sample_count = 0; + idx_t word_variation = 0; + const auto step = (keys.size() + SAMPLE_COUNT - 1) / SAMPLE_COUNT; + idx_t min_word = EntryCount(); + idx_t max_word = 0; + for (idx_t i = 0; i < keys.size(); i += step) { + const auto entry = keys[i]; + if (!entry.IsValid() || !InRange(entry.GetValue())) { + continue; + } + const auto word = GetIndex(entry.GetValue()) / 64; + // Reject repeated sampled words to avoid prefetching hot keys. + for (idx_t j = 0; j < sample_count; j++) { + if (sampled_words[j] == word) { + return false; + } + } + sampled_words[sample_count++] = word; + word_variation |= word ^ sampled_words[0]; + min_word = MinValue(min_word, word); + max_word = MaxValue(max_word, word); + } + if (sample_count < SAMPLE_COUNT / 2) { + return false; + } + // 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); + return (max_word - min_word) / word_stride >= PREFETCH_MIN_BYTES / sizeof(uint64_t); +#else + return false; +#endif + } + + template + void PrepareMembershipPositions(const VectorIterator &keys, + array &positions) const { + D_ASSERT(has_bounds); + for (idx_t i = 0; i < keys.size(); i++) { + const auto entry = keys[i]; + if (HAS_NULL && !entry.IsValid()) { + positions[i] = UnsafeNumericCast(domain_size); + continue; + } + // Unsigned distance rejects keys outside the bounded domain. + const auto distance = KeyDistance(entry.GetValueUnsafe(), min); + const uint8_t valid = distance.upper == 0 && distance.lower < domain_size; + // A miss carries the high bit and addresses word zero. + positions[i] = valid ? UnsafeNumericCast(distance.lower) : MISS_BIT; + } + } + + static idx_t MembershipWord(uint32_t position) { + return (position & ~MISS_BIT) / 64; + } + + idx_t ProbeMembershipPrefetched(const VectorIterator &keys, unsafe_unique_array &found_match) const { + array positions; + if (keys.CanHaveNull()) { + PrepareMembershipPositions(keys, positions); + } else { + PrepareMembershipPositions(keys, positions); + } + auto directory = GetEntries(); + idx_t match_count = 0; + for (idx_t i = 0; i < keys.size(); i++) { + const auto position = positions[i]; + const auto bit = (directory[MembershipWord(position)] >> (position % 64)) & 1ULL; + const bool found = bit & (position < MISS_BIT); + found_match[i] = found; + match_count += found; + PrefetchHashTableEntry(i, keys.size(), + [&](idx_t next_idx) { return &directory[MembershipWord(positions[next_idx])]; }); + } + return match_count; + } + + void WidenBounds(T new_min, T new_max) { + min = has_bounds ? MinValue(min, new_min) : new_min; + max = has_bounds ? MaxValue(max, new_max) : new_max; + has_bounds = true; + } + + 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)) { + range_too_large = true; + } + } + + bool InRange(T value) const { + return has_bounds && value >= min && value <= max; + } + + idx_t GetIndex(T value) const { + D_ASSERT(InRange(value)); + return KeyDistance(value, min).lower; + } + + static bool Contains(const array_ptr &directory, idx_t slot) { + return (directory[slot / 64] & (uint64_t(1) << (slot % 64))) != 0; + } + +private: + 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"); + + T min {}; + T max {}; + bool has_bounds = false; + bool range_too_large = false; + idx_t domain_size = 0; +}; + +unique_ptr PerfectHashJoinTable::Create(PhysicalType key_type, Type type, bool nulls_equal) { + switch (key_type) { + case PhysicalType::INT8: + return make_uniq>(type, nulls_equal); + case PhysicalType::INT16: + return make_uniq>(type, nulls_equal); + case PhysicalType::INT32: + return make_uniq>(type, nulls_equal); + case PhysicalType::INT64: + return make_uniq>(type, nulls_equal); + case PhysicalType::INT128: + return make_uniq>(type, nulls_equal); + case PhysicalType::UINT8: + return make_uniq>(type, nulls_equal); + case PhysicalType::UINT16: + return make_uniq>(type, nulls_equal); + case PhysicalType::UINT32: + return make_uniq>(type, nulls_equal); + case PhysicalType::UINT64: + return make_uniq>(type, nulls_equal); + case PhysicalType::UINT128: + return make_uniq>(type, nulls_equal); + default: + return nullptr; + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/execution/physical_operator.cpp b/src/duckdb/src/execution/physical_operator.cpp index f2d9a020e..2cc863f73 100644 --- a/src/duckdb/src/execution/physical_operator.cpp +++ b/src/duckdb/src/execution/physical_operator.cpp @@ -532,13 +532,8 @@ static void AppendToCache(CachingOperatorState &state, DataChunk &source, Client } continue; } - // A global dictionary wraps the same entry for the producer's lifetime, so a change is a producer bug - // that would desync the downstream sink layout -> fail loudly. A non-global dict rotating is normal. - if (slot.entry->global_dictionary) { - throw InternalException("dict-surviving cache: global dictionary column %llu changed identity " - "after being seeded for dictionary caching", - static_cast(col_idx)); - } + // an operator above the producer may forward its global dictionary for some chunks only (a CASE branch, a + // spilled probe, a cross product): demote the column to flat FlattenDictColumn(state, cache, col_idx, base); } // reached by originally-flat and just-demoted columns 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 47cb8e9c5..8227fea25 100644 --- a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp @@ -109,16 +109,13 @@ optional_ptr PhysicalPlanGenerator::PlanAsOfLoopJoin(LogicalCo const auto lhs_width = probe_types.size(); const auto rhs_width = build_types.size(); - ExpressionIterator::EnumerateExpression(predicate, [&](Expression &child) { - if (child.GetExpressionClass() == ExpressionClass::BOUND_REF) { - auto &ref = child.Cast(); - if (ref.Index() < lhs_width) { - ref.IndexMutable() = ref.Index() + rhs_width; - } else { - ref.IndexMutable() = ref.Index() - lhs_width; - } - } - }); + predicate = ExpressionIterator::PreorderReplace( + std::move(predicate), [&](const BoundReferenceExpression &ref) { + if (ref.Index() < lhs_width) { + return ref.WithIndex(ref.Index() + rhs_width); + } + return ref.WithIndex(ref.Index() - lhs_width); + }); join_op.conditions.emplace_back(std::move(predicate)); } 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 da38e9748..ddc78c686 100644 --- a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp @@ -1,4 +1,3 @@ -#include "duckdb/execution/operator/join/perfect_hash_join_executor.hpp" #include "duckdb/execution/operator/join/physical_blockwise_nl_join.hpp" #include "duckdb/execution/operator/join/physical_cross_product.hpp" #include "duckdb/execution/operator/join/physical_hash_join.hpp" @@ -21,8 +20,8 @@ namespace duckdb { static void RewriteJoinCondition(unique_ptr &root_expr, idx_t offset) { - ExpressionIterator::VisitExpressionMutable( - root_expr, [&](BoundReferenceExpression &ref, unique_ptr &expr) { ref.IndexMutable() += offset; }); + root_expr = ExpressionIterator::PreorderReplace( + std::move(root_expr), [&](const BoundReferenceExpression &ref) { return ref.WithIndex(ref.Index() + offset); }); } static optional_ptr diff --git a/src/duckdb/src/execution/physical_plan/plan_execute.cpp b/src/duckdb/src/execution/physical_plan/plan_execute.cpp deleted file mode 100644 index 8e43330f0..000000000 --- a/src/duckdb/src/execution/physical_plan/plan_execute.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "duckdb/execution/operator/helper/physical_execute.hpp" -#include "duckdb/execution/physical_plan_generator.hpp" -#include "duckdb/planner/operator/logical_execute.hpp" - -namespace duckdb { - -PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalExecute &op) { - if (op.prepared->physical_plan) { - D_ASSERT(op.children.empty()); - auto &plan = op.prepared->physical_plan->Root(); - return Make(plan, op.prepared); - } - - D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); - return Make(plan, op.prepared); -} - -} // namespace duckdb diff --git a/src/duckdb/src/execution/physical_plan/plan_limit.cpp b/src/duckdb/src/execution/physical_plan/plan_limit.cpp index f76c1a92d..684b2b82d 100644 --- a/src/duckdb/src/execution/physical_plan/plan_limit.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_limit.cpp @@ -175,7 +175,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalLimit &op) { auto &plan = CreatePlan(*op.children[0]); auto *limit_child = &plan; auto total_limit = GetLimit(op.limit_val, op.offset_val); - if (op.offset_val.Type() != LimitNodeType::UNSET && !PreserveInsertionOrder(plan)) { + bool zero_offset = op.offset_val.Type() == LimitNodeType::CONSTANT_VALUE && op.offset_val.GetConstantValue() == 0; + if (op.offset_val.Type() != LimitNodeType::UNSET && !zero_offset && !PreserveInsertionOrder(plan)) { DUCKDB_LOG_WARNING(context, "OFFSET is applied to a query whose row order is not guaranteed - the result may " "differ between runs. This happens when the query contains order-breaking operators (e.g. " diff --git a/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp b/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp index c64ac988d..5dcc50b81 100644 --- a/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp @@ -70,8 +70,7 @@ unique_ptr PlanMergeIntoAction(ClientContext &context, Logica op.table.GetStorage(), std::move(action.columns), std::move(action.expressions), std::move(defaults), std::move(bound_constraints), cardinality, op.return_chunk, - /*capture_old_rows=*/false, /*old_row_columns=*/vector(), - /*row_id_handling=*/RowIdHandling::ASSUME_UNIQUE); + /*capture_old_rows=*/false, /*old_row_columns=*/vector()); auto &cast_update = result->op->Cast(); cast_update.update_is_del_and_insert = action.update_is_del_and_insert; result->op->children.push_back(action_input); @@ -219,6 +218,15 @@ static unique_ptr PlanGenericMergeIntoAction(ClientContext &c // that layout so that we can plan the update exactly like a regular update vector> select_list; vector> update_expressions; + //! Deprecated: plans serialized before v2.0 keep SET col = DEFAULT as a placeholder that the update operator + //! resolved, now the binder resolves it - resolve it here, as it cannot be evaluated in the projection + for (idx_t i = 0; i < action.expressions.size(); i++) { + if (action.expressions[i]->GetExpressionType() != ExpressionType::VALUE_DEFAULT) { + continue; + } + auto storage_idx = op.table.GetColumns().GetColumn(action.columns[i]).StorageOid(); + action.expressions[i] = op.bound_defaults[storage_idx]->Copy(); + } CastActionExpressionsToColumnTypes(context, op.table, action.expressions, action.columns); for (auto &expr : action.expressions) { update_expressions.push_back( diff --git a/src/duckdb/src/execution/physical_plan/plan_update.cpp b/src/duckdb/src/execution/physical_plan/plan_update.cpp index bf9dfd232..082d968b6 100644 --- a/src/duckdb/src/execution/physical_plan/plan_update.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_update.cpp @@ -9,10 +9,10 @@ namespace duckdb { PhysicalOperator &DuckCatalog::PlanUpdate(ClientContext &context, PhysicalPlanGenerator &planner, LogicalUpdate &op, PhysicalOperator &plan) { - auto &update = planner.Make( - op.types, op.table.Cast(), op.table.GetStorage(), op.columns, std::move(op.expressions), - std::move(op.bound_defaults), std::move(op.bound_constraints), op.estimated_cardinality, op.return_chunk, - op.capture_old_rows, std::move(op.old_row_columns), op.row_id_handling); + auto &update = planner.Make(op.types, op.table.Cast(), op.table.GetStorage(), + op.columns, std::move(op.expressions), std::move(op.bound_defaults), + std::move(op.bound_constraints), op.estimated_cardinality, + op.return_chunk, op.capture_old_rows, std::move(op.old_row_columns)); auto &cast_update = update.Cast(); cast_update.update_is_del_and_insert = op.update_is_del_and_insert; cast_update.children.push_back(plan); diff --git a/src/duckdb/src/execution/physical_plan_generator.cpp b/src/duckdb/src/execution/physical_plan_generator.cpp index 5f8c678e0..1acf4ba32 100644 --- a/src/duckdb/src/execution/physical_plan_generator.cpp +++ b/src/duckdb/src/execution/physical_plan_generator.cpp @@ -151,8 +151,6 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlanInternal(LogicalOperator &op) return CreatePlan(op.Cast()); case LogicalOperatorType::LOGICAL_PREPARE: return CreatePlan(op.Cast()); - case LogicalOperatorType::LOGICAL_EXECUTE: - return CreatePlan(op.Cast()); case LogicalOperatorType::LOGICAL_CREATE_VIEW: case LogicalOperatorType::LOGICAL_CREATE_SEQUENCE: case LogicalOperatorType::LOGICAL_CREATE_SCHEMA: diff --git a/src/duckdb/src/execution/radix_ht_adaptivity.cpp b/src/duckdb/src/execution/radix_ht_adaptivity.cpp index af99abfeb..b68711249 100644 --- a/src/duckdb/src/execution/radix_ht_adaptivity.cpp +++ b/src/duckdb/src/execution/radix_ht_adaptivity.cpp @@ -32,10 +32,18 @@ bool RadixHTAdaptivity::TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSink if (next_capacity > NumericLimits::Maximum() / sizeof(ht_entry_t)) { return false; } - const auto current_size = ht.GetSizeInBytes(); + // Without a spill plan the arena stays in memory either way, so it does not count against the growth. + const auto current_size = gstate.SpillableSize(ht); const auto table_size = next_capacity * sizeof(ht_entry_t); // Grow only when repeated tuple materialization outweighs the larger pointer table. - if (static_cast(materialized_count - hll_count) * static_cast(ht.GetLayout().GetRowWidth()) < + // Without a spill plan, a duplicate row also re-creates its states in the arena, which cannot spill, + // so count those bytes too. + const auto arena_bytes_per_row = gstate.spill_plan + ? 0.0 + : static_cast(ht.GetAggregateAllocator()->AllocationSize()) / + static_cast(materialized_count); + const auto duplicate_bytes_per_row = static_cast(ht.GetLayout().GetRowWidth()) + arena_bytes_per_row; + if (static_cast(materialized_count - hll_count) * duplicate_bytes_per_row < GROWTH_DUPLICATE_BYTES_FACTOR * static_cast(table_size)) { return false; } diff --git a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp index 671dd0c1c..f32179d84 100644 --- a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp +++ b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp @@ -282,7 +282,10 @@ idx_t RadixHTConfig::ExternalRadixBits(const bool dynamic) const { // 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 memory_limit = dynamic ? sink.temporary_memory_state->GetReservation() : sink.memory_limit / 2; + 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; @@ -357,6 +360,7 @@ void RadixHTLocalSinkState::ResetForReuse(const RadixPartitionedHashTable &radix } registered = false; spilling = false; + size_after_abandon = 0; abandoned_data.reset(); abandoned_exported_data.clear(); if (!ht) { @@ -573,6 +577,14 @@ bool RadixHTGlobalSinkState::StatePressureExceeded(GroupedAggregateHashTable &ht GetThreadLimit() / RadixHTConfig::AGGREGATE_STATE_PRESSURE_DIVISOR; } +idx_t RadixHTGlobalSinkState::SpillableSize(GroupedAggregateHashTable &ht) const { + const auto total_size = ht.GetSizeInBytes(); + if (spill_plan) { + return total_size; + } + return total_size - MinValue(total_size, ht.GetAggregateAllocator()->AllocationSize()); +} + // Whether this thread's aggregate states should be exported to spillable storage bool ShouldExportStates(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate, GroupedAggregateHashTable &ht) { const auto arena_size = ht.GetAggregateAllocator()->AllocationSize(); @@ -589,6 +601,38 @@ bool ShouldExportStates(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &l return arena_size >= gstate.GetThreadLimit() / RadixHTConfig::AGGREGATE_STATE_SPILL_DIVISOR; } +idx_t SpillableLimit(RadixHTGlobalSinkState &gstate, GroupedAggregateHashTable &ht) { + const auto thread_limit = gstate.GetThreadLimit(); + if (gstate.spill_plan || ht.GetAggregateAllocator()->AllocationSize() == 0 || + !BufferManager::GetBufferManager(gstate.context).HasTemporaryDirectory()) { + return thread_limit; + } + // The arena's minimum reservation can exceed the memory limit. + return MinValue(thread_limit, gstate.memory_limit / gstate.number_of_threads / 10 * 8); +} + +// Without a spill plan, arena pressure alone must not repeatedly abandon and re-create the same states. +bool MemoryPressure(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate, GroupedAggregateHashTable &ht, + idx_t total_size) { + const auto thread_limit = gstate.GetThreadLimit(); + if (gstate.spill_plan) { + return total_size > thread_limit || gstate.StatePressureExceeded(ht); + } + if (total_size <= thread_limit) { + return false; + } + if (ht.GetAggregateAllocator()->AllocationSize() == 0) { + // abandoning duplicates nothing that cannot spill + return true; + } + const auto spillable_size = gstate.SpillableSize(ht); + const auto arena_size = ht.GetAggregateAllocator()->AllocationSize(); + // Preserve growth opportunities when spilling rows would reclaim little compared with the arena. + const auto growth_limit = + gstate.external || spillable_size > arena_size / 4 ? SpillableLimit(gstate, ht) : thread_limit; + return spillable_size > lstate.size_after_abandon + growth_limit / RadixHTConfig::AGGREGATE_STATE_SPILL_DIVISOR; +} + void UpdateSinkReservation(ClientContext &context, RadixHTGlobalSinkState &gstate, GroupedAggregateHashTable &ht, idx_t total_size) { // Include the headroom required by the arena's export threshold. @@ -623,7 +667,7 @@ void MaybeRepartition(ClientContext &context, RadixHTGlobalSinkState &gstate, Ra const auto total_size = ht.GetSizeInBytes(); UpdateSinkReservation(context, gstate, ht, total_size); - if (total_size > gstate.GetThreadLimit()) { + if (gstate.SpillableSize(ht) > SpillableLimit(gstate, ht)) { if (gstate.config.SetRadixBitsToExternal()) { lstate.PrepareForSpill(gstate); // We're approaching the memory limit, unpin the data @@ -695,8 +739,7 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk // Row width and aggregate state size can increase without filling the pointer table. const auto total_size = ht.GetSizeInBytes(); UpdateSinkReservation(context.client, gstate, ht, total_size); - const auto memory_pressure = - total_size > gstate.GetThreadLimit() || (gstate.spill_plan && gstate.StatePressureExceeded(ht)); + const auto memory_pressure = MemoryPressure(gstate, lstate, ht, total_size); if (!memory_pressure && ht.Count() + STANDARD_VECTOR_SIZE < GroupedAggregateHashTable::ResizeThreshold(lstate.local_sink_capacity)) { return; @@ -709,11 +752,13 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk 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); } @@ -728,6 +773,7 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk // We repartitioned, but we didn't clear the pointer table / reset the count because we're on 1 or 2 threads gstate.any_abandoned = true; ht.Abandon(); + abandoned = true; if (gstate.external) { ht.Resize(lstate.local_sink_capacity); } @@ -755,6 +801,10 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk ht.AcquirePartitionedData()->Repartition(context.client, *lstate.abandoned_data); ExportAbandonedData(context.client, gstate, lstate); ht.GetAggregateAllocator()->FreeAll(); + abandoned = true; + } + if (abandoned) { + lstate.size_after_abandon = gstate.SpillableSize(ht); } // TODO: combine early and often @@ -1357,6 +1407,10 @@ ProgressData RadixPartitionedHashTable::GetProgress(ClientContext &, GlobalSinkS auto &sink = sink_p.Cast(); auto &gstate = gstate_p.Cast(); + if (sink.count_before_combining == 0) { + return ProgressData {gstate.finished ? 1.0 : 0.0, 1.0, false}; + } + // Get partition combine progress, weigh it 2x ProgressData progress; for (auto &partition : sink.partitions) { 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 48f9a0c67..cb6ae3316 100644 --- a/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp +++ b/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp @@ -24,7 +24,7 @@ unique_ptr RewriteOrderedFirst(AggregateRewriteInput &input) { FunctionBinder binder(input.context); vector> sort_children; - for (auto &order : aggregate->GetOrderBysMutable()->orders) { + for (auto &order : aggregate->GetOrderBys()->orders) { sort_children.emplace_back(std::move(order.expression)); sort_children.emplace_back(make_uniq(Value(order.GetOrderModifier()))); } diff --git a/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp b/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp index 1cbeec6ed..9427266b0 100644 --- a/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp @@ -640,7 +640,7 @@ void FunctionBinder::BindSortedAggregate(ClientContext &context, BoundAggregateE // the exported state buffers the values, so the ORDER BY must be preserved verbatim - skip the simplification const bool state_export = expr.StateExportMode() == AggregateStateExportMode::STATE_EXPORT; if (!state_export && Settings::Get(context)) { - if (expr.GetOrderBysMutable()->Simplify(groups, grouping_sets)) { + if (expr.GetOrderBys()->Simplify(groups, grouping_sets)) { expr.GetOrderBysMutable().reset(); return; } diff --git a/src/duckdb/src/function/cast/cast_function_set.cpp b/src/duckdb/src/function/cast/cast_function_set.cpp index d01c24f08..26b6ec25a 100644 --- a/src/duckdb/src/function/cast/cast_function_set.cpp +++ b/src/duckdb/src/function/cast/cast_function_set.cpp @@ -8,12 +8,21 @@ #include "duckdb/function/cast_rules.hpp" #include "duckdb/planner/collation_binding.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/context.hpp" +#include "duckdb/main/client_context.hpp" namespace duckdb { BindCastInput::BindCastInput(CastFunctionSet &function_set, optional_ptr info, - optional_ptr context) - : function_set(function_set), info(info), context(context) { + GetCastFunctionInput &get_input) + : function_set(function_set), info(info), context(get_input.client_context), services(get_input.TryGetContext()) { +} + +Context &BindCastInput::GetContext() { + if (!services) { + throw InternalException("BindCastInput::GetContext called on the input of a default cast"); + } + return *services; } //! Orders the stabilities from the most to the least stable @@ -34,8 +43,27 @@ static FunctionStability LeastStable(FunctionStability left, FunctionStability r return StabilityRank(left) >= StabilityRank(right) ? left : right; } +GetCastFunctionInput::GetCastFunctionInput(Context &context_p) + : client_context(context_p.TryGetClientContext()), context(context_p) { +} + +GetCastFunctionInput::GetCastFunctionInput(ClientContext &context_p) + : client_context(context_p), context(context_p.GetContext()) { +} + +GetCastFunctionInput GetCastFunctionInput::Default() { + return GetCastFunctionInput(); +} + +Context &GetCastFunctionInput::GetContext() { + if (!context) { + throw InternalException("GetCastFunctionInput::GetContext called on the input of a default cast"); + } + return *context; +} + BoundCastInfo BindCastInput::GetCastFunction(const LogicalType &source, const LogicalType &target) { - GetCastFunctionInput input(context); + auto input = services ? GetCastFunctionInput(*services) : GetCastFunctionInput::Default(); input.query_location = query_location; auto result = function_set.GetCastFunction(source, target, input); stability = LeastStable(stability, result.GetStability()); @@ -92,7 +120,7 @@ BoundCastInfo CastFunctionSet::GetCastFunction(const LogicalType &source, const source.id() == LogicalTypeId::VARIANT || registration_probe->HasRegisteredCast(source, target); } auto bind_cast = [&](BindCastFunction &bind_function) { - BindCastInput input(*this, bind_function.info.get(), get_input.context); + BindCastInput input(*this, bind_function.info.get(), get_input); input.query_location = get_input.query_location; auto result = bind_function.function(input, source, target); result.SetStability(LeastStable(result.GetStability(), input.stability)); @@ -219,6 +247,18 @@ struct MapCastInfo : public BindCastInfo { return &target_type_entry->second; } + vector GetSourceTypes(const LogicalType &target) const { + vector result; + for (auto &source_id : casts) { + for (auto &source_type : source_id.second) { + if (GetEntry(source_type.first, target)) { + result.push_back(source_type.first); + } + } + } + return result; + } + void AddEntry(const LogicalType &source, const LogicalType &target, MapCastNode node) { casts[source.id()][source][target.id()].insert(make_pair(target, std::move(node))); } @@ -231,6 +271,10 @@ bool CastFunctionSet::HasRegisteredCast(const LogicalType &source, const Logical return map_info && map_info->GetEntry(source, target); } +vector CastFunctionSet::GetRegisteredCastSourceTypes(const LogicalType &target) const { + return map_info ? map_info->GetSourceTypes(target) : vector(); +} + bool CastFunctionSet::CanOverrideDefaultCast(const LogicalType &source, const LogicalType &target) const { if (!map_info || source == target) { return false; @@ -240,7 +284,7 @@ bool CastFunctionSet::CanOverrideDefaultCast(const LogicalType &source, const Lo } CastFunctionSet probe; probe.registration_probe = this; - GetCastFunctionInput input; + auto input = GetCastFunctionInput::Default(); probe.GetCastFunction(source, target, input); return probe.registered_cast_found; } diff --git a/src/duckdb/src/function/cast/variant/from_variant.cpp b/src/duckdb/src/function/cast/variant/from_variant.cpp index 7e2ba37f8..37ee672e7 100644 --- a/src/duckdb/src/function/cast/variant/from_variant.cpp +++ b/src/duckdb/src/function/cast/variant/from_variant.cpp @@ -10,8 +10,17 @@ #include "yyjson_memory.hpp" #include "duckdb/function/cast/default_casts.hpp" #include "duckdb/common/types/variant.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/types/variant_visitor.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/function/scalar/variant_utils.hpp" #include "duckdb/common/serializer/varint.hpp" +#include "duckdb/common/operator/decimal_cast_operators.hpp" +#include "duckdb/common/operator/string_cast.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/string_heap.hpp" +#include "duckdb/common/types/uuid.hpp" +#include "duckdb/function/cast/vector_cast_helpers.hpp" #include "yyjson.hpp" #include "duckdb/common/algorithm.hpp" @@ -42,6 +51,8 @@ struct FromVariantConversionData { UnifiedVariantVectorData variant; //! The optional client to use for casting optional_ptr client; + //! Checked at execution time so prepared casts see newly registered overrides. + optional varchar_cast_override; //! If unsuccessful - the error of the conversion string error; }; @@ -179,52 +190,447 @@ struct VariantDecimalConversion { } }; -template -static bool CastVariantToPrimitive(FromVariantConversionData &conversion_data, Vector &result, - const SelectionVector &sel, idx_t offset, idx_t count, optional_idx row, - PAYLOAD_CLASS payload) { - auto &variant = conversion_data.variant; - +//! Casts a single value by converting it to a Value first +static bool CastVariantValue(FromVariantConversionData &conversion_data, Vector &result, idx_t result_index, + idx_t row_index, uint32_t values_index) { auto &target_type = result.GetType(); - auto result_data = FlatVector::GetDataMutable(result); - auto &result_validity = FlatVector::ValidityMutable(result); + auto value = VariantUtils::ConvertVariantToValue(conversion_data.variant, row_index, values_index); + auto cast_value = conversion_data.TryCastAs(value, target_type); + const bool success = cast_value.has_value(); + if (!success) { + auto type_id = conversion_data.variant.GetTypeId(row_index, values_index); + conversion_data.error = + StringUtil::Format("Can't convert VARIANT(%s) value '%s'", EnumUtil::ToString(type_id), value.ToString()); + cast_value = Value(target_type); + } + result.SetValue(result_index, *cast_value); + return success; +} +template +static bool CastVariantRows(FromVariantConversionData &conversion_data, Vector &result, const SelectionVector &sel, + idx_t offset, idx_t count, optional_idx row, CONVERT &&convert) { + auto &variant = conversion_data.variant; + auto &result_validity = FlatVector::ValidityMutable(result); bool all_valid = true; for (idx_t i = 0; i < count; i++) { auto row_index = row.IsValid() ? row.GetIndex() : i; - + auto result_index = offset + i; if (!variant.RowIsValid(row_index)) { - result_validity.SetInvalid(offset + i); + result_validity.SetInvalid(result_index); continue; } - if (!result_validity.RowIsValid(offset + i)) { + if (!result_validity.RowIsValid(result_index)) { continue; } + if (!convert(row_index, sel[i], result_index) && + !CastVariantValue(conversion_data, result, result_index, row_index, sel[i])) { + all_valid = false; + } + } + return all_valid; +} - auto type_id = variant.GetTypeId(row_index, sel[i]); - auto byte_offset = variant.GetByteOffset(row_index, sel[i]); +template +static bool CastVariantToPrimitive(FromVariantConversionData &conversion_data, Vector &result, + const SelectionVector &sel, idx_t offset, idx_t count, optional_idx row, + PAYLOAD_CLASS payload) { + auto &variant = conversion_data.variant; + auto result_data = FlatVector::GetDataMutable(result); + auto convert = [&](idx_t row_index, uint32_t values_index, idx_t result_index) { + auto type_id = variant.GetTypeId(row_index, values_index); + if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { + return false; + } + auto byte_offset = variant.GetByteOffset(row_index, values_index); auto &blob = variant.GetData(row_index); - auto value_blob_data = const_data_ptr_cast(blob.GetData()); - bool converted = false; - if (type_id != VariantLogicalType::OBJECT && type_id != VariantLogicalType::ARRAY) { - if (OP::Convert(type_id, byte_offset, value_blob_data, blob.GetSize(), result_data[i + offset], payload, - conversion_data.error)) { - converted = true; + return OP::Convert(type_id, byte_offset, const_data_ptr_cast(blob.GetData()), blob.GetSize(), + result_data[result_index], payload, conversion_data.error); + }; + return CastVariantRows(conversion_data, result, sel, offset, count, row, convert); +} + +namespace { + +//! Writes a VARIANT value as the text produced by casting its Value representation to VARCHAR, without +//! materializing the Value. It handles the types JSON produces and the scalar types whose text does not depend on +//! settings. Serialize returns false for values that need the Value conversion (objects that become MAPs or have +//! case-insensitively duplicate keys, time zone dependent types, ...). +class VariantVarcharSerializer { +public: + using result_type = bool; + using Visitor = VariantVisitor; + + explicit VariantVarcharSerializer(const UnifiedVariantVectorData &variant) + : variant(variant), object_entries(Visitor::MAX_RECURSION_DEPTH), first_entries(Visitor::MAX_RECURSION_DEPTH), + other_entries(Visitor::MAX_RECURSION_DEPTH) { + } + + bool Serialize(idx_t row, uint32_t values_index) { + buffer.clear(); + heap.GetAllocator().Reset(); + return WriteValue(row, values_index, 0); + } + + const string &GetResult() const { + return buffer; + } + +private: + struct ObjectEntry { + string_t key; + uint32_t values_index; + }; + //! Collects the entries of an OBJECT, sorted by key. Returns false if the object is not converted to a STRUCT + //! with unique names. + bool GetSortedEntries(idx_t row, const VariantNestedData &nested_data, vector &entries) { + entries.clear(); + for (idx_t i = 0; i < nested_data.child_count; i++) { + auto &key = variant.GetKey(row, variant.GetKeysIndex(row, nested_data.children_idx + i)); + if (key.Empty()) { + return false; } + entries.push_back(ObjectEntry {key, variant.GetValuesIndex(row, nested_data.children_idx + i)}); } - if (!converted) { - auto value = VariantUtils::ConvertVariantToValue(conversion_data.variant, row_index, sel[i]); - auto cast_value = conversion_data.TryCastAs(value, target_type); - if (!cast_value) { - conversion_data.error = StringUtil::Format("Can't convert VARIANT(%s) value '%s'", - EnumUtil::ToString(type_id), value.ToString()); - cast_value = Value(target_type); - all_valid = false; + std::sort(entries.begin(), entries.end(), [](const ObjectEntry &left, const ObjectEntry &right) { + return StringUtil::CILessThan(std::string_view(left.key.GetData(), left.key.GetSize()), + std::string_view(right.key.GetData(), right.key.GetSize())); + }); + for (idx_t i = 1; i < entries.size(); i++) { + auto &left = entries[i - 1].key; + auto &right = entries[i].key; + if (StringUtil::CIEquals(left.GetData(), left.GetSize(), right.GetData(), right.GetSize())) { + return false; } - result.SetValue(i + offset, *cast_value); } + std::sort(entries.begin(), entries.end(), + [](const ObjectEntry &left, const ObjectEntry &right) { return left.key < right.key; }); + return true; + } + + //! A LIST casts its elements to the type of the first one, which renames STRUCT fields whose names only differ in + //! case. Returns true if that can rename a field of `other`. + bool NamesDifferInCase(idx_t row, uint32_t first, uint32_t other, idx_t depth) { + if (depth >= Visitor::MAX_RECURSION_DEPTH) { + return true; + } + auto first_type = variant.GetTypeId(row, first); + auto other_type = variant.GetTypeId(row, other); + if (first_type == VariantLogicalType::ARRAY && other_type == VariantLogicalType::ARRAY) { + auto first_data = VariantUtils::DecodeNestedData(variant, row, first); + auto other_data = VariantUtils::DecodeNestedData(variant, row, other); + if (first_data.child_count == 0 || other_data.child_count == 0) { + return false; + } + return NamesDifferInCase(row, variant.GetValuesIndex(row, first_data.children_idx), + variant.GetValuesIndex(row, other_data.children_idx), depth + 1); + } + if (first_type != VariantLogicalType::OBJECT || other_type != VariantLogicalType::OBJECT) { + return false; + } + auto &first_sorted = first_entries[depth]; + auto &other_sorted = other_entries[depth]; + if (!GetSortedEntries(row, VariantUtils::DecodeNestedData(variant, row, first), first_sorted) || + !GetSortedEntries(row, VariantUtils::DecodeNestedData(variant, row, other), other_sorted) || + first_sorted.size() != other_sorted.size()) { + return false; + } + for (idx_t i = 0; i < first_sorted.size(); i++) { + auto &first_key = first_sorted[i].key; + auto &other_key = other_sorted[i].key; + if (!StringUtil::CIEquals(first_key.GetData(), first_key.GetSize(), other_key.GetData(), + other_key.GetSize())) { + return false; + } + if (first_key != other_key || + NamesDifferInCase(row, first_sorted[i].values_index, other_sorted[i].values_index, depth + 1)) { + return true; + } + } + return false; + } + + template + void WriteEscaped(const string_t &text) { + bool needs_quotes; + auto length = VectorCastHelpers::CalculateEscapedStringLength(text, needs_quotes); + auto offset = buffer.size(); + buffer.resize(offset + length); + VectorCastHelpers::WriteEscapedString(&buffer[offset], text, needs_quotes); + } + + void WriteText(const string_t &text, bool escape) { + if (escape) { + WriteEscaped(text); + } else { + buffer.append(text.GetData(), text.GetSize()); + } + } + + bool WriteObject(idx_t row, const VariantNestedData &nested_data, idx_t depth) { + auto &entries = object_entries[depth]; + if (!GetSortedEntries(row, nested_data, entries)) { + return false; + } + buffer.push_back('{'); + for (idx_t i = 0; i < entries.size(); i++) { + if (i > 0) { + buffer.append(", "); + } + WriteEscaped(entries[i].key); + buffer.append(": "); + if (!WriteValue(row, entries[i].values_index, depth + 1)) { + return false; + } + } + buffer.push_back('}'); + return true; + } + + bool WriteArray(idx_t row, const VariantNestedData &nested_data, idx_t depth) { + buffer.push_back('['); + uint32_t first = 0; + for (idx_t i = 0; i < nested_data.child_count; i++) { + auto child = variant.GetValuesIndex(row, nested_data.children_idx + i); + if (i == 0) { + first = child; + } else { + if (NamesDifferInCase(row, first, child, depth + 1)) { + return false; + } + buffer.append(", "); + } + if (!WriteValue(row, child, depth + 1)) { + return false; + } + } + buffer.push_back(']'); + return true; + } + + //! Primitive members of a STRUCT or LIST are escaped. + bool WriteValue(idx_t row, uint32_t values_index, idx_t depth) { + return Visitor::Visit(variant, row, values_index, depth, *this, depth > 0); + } + +public: + static bool VisitNull(VariantVarcharSerializer &writer, bool) { + writer.buffer.append("NULL"); + return true; + } + + template + static bool VisitInteger(T value, VariantVarcharSerializer &writer, bool escape) { + writer.WriteText(StringCast::Operation(value, writer.heap), escape); + return true; + } + + static bool VisitBoolean(bool value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitFloat(float value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitDouble(double value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitDate(date_t value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitTime(dtime_t value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitTimestamp(timestamp_t value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitInterval(interval_t value, VariantVarcharSerializer &writer, bool escape) { + return VisitInteger(value, writer, escape); + } + + static bool VisitUUID(hugeint_t value, VariantVarcharSerializer &writer, bool escape) { + char uuid[UUID::STRING_SIZE]; + UUID::ToString(value, uuid); + writer.WriteText(string_t(uuid, UUID::STRING_SIZE), escape); + return true; + } + + template + static bool VisitDecimal(T value, uint32_t width, uint32_t scale, VariantVarcharSerializer &writer, bool escape) { + writer.WriteText(StringCastFromDecimal::Operation(value, width, scale, writer.heap), escape); + return true; + } + + static bool VisitString(const string_t &value, VariantVarcharSerializer &writer, bool escape) { + writer.WriteText(value, escape); + return true; + } + + static bool VisitObject(const UnifiedVariantVectorData &, idx_t row, const VariantNestedData &nested_data, + idx_t depth, VariantVarcharSerializer &writer, bool) { + return writer.WriteObject(row, nested_data, depth); + } + + static bool VisitArray(const UnifiedVariantVectorData &, idx_t row, const VariantNestedData &nested_data, + idx_t depth, VariantVarcharSerializer &writer, bool) { + return writer.WriteArray(row, nested_data, depth); + } + + //! Use the Value conversion for session-dependent and uncommon types. + static bool VisitTimeNanos(dtime_ns_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitTimeTZ(dtime_tz_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitTimestampSec(timestamp_sec_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitTimestampMs(timestamp_ms_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitTimestampNanos(timestamp_ns_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitTimestampTZ(timestamp_tz_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitTimestampTZNanos(timestamp_tz_ns_t, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitBlob(const string_t &, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitBignum(const string_t &, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitGeometry(const string_t &, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitBitstring(const string_t &, VariantVarcharSerializer &, bool) { + return false; + } + static bool VisitDefault(VariantLogicalType, const_data_ptr_t, VariantVarcharSerializer &, bool) { + return false; + } + +private: + const UnifiedVariantVectorData &variant; + string buffer; + StringHeap heap; + //! Per-depth scratch space for the sorted entries of an OBJECT + vector> object_entries; + vector> first_entries; + vector> other_entries; +}; + +} // namespace + +#ifdef D_ASSERT_IS_ENABLED +//! The serializer must produce the same text as the Value conversion +static void VerifyVarcharSerialization(FromVariantConversionData &conversion_data, const LogicalType &target_type, + idx_t row_index, uint32_t values_index, const string &serialized) { + auto value = VariantUtils::ConvertVariantToValue(conversion_data.variant, row_index, values_index); + auto expected = conversion_data.TryCastAs(value, target_type); + if (!expected || StringValue::Get(*expected) != serialized) { + throw InternalException("VARIANT to VARCHAR serialization produced \"%s\", expected \"%s\"", serialized, + expected ? StringValue::Get(*expected) : "a cast error"); } - return all_valid; +} +#endif + +static bool HasVarcharCastOverride(FromVariantConversionData &conversion_data) { + if (conversion_data.varchar_cast_override) { + return *conversion_data.varchar_cast_override; + } + conversion_data.varchar_cast_override = false; + if (!conversion_data.client) { + return false; + } + auto &casts = CastFunctionSet::Get(*conversion_data.client); + for (auto &type : casts.GetRegisteredCastSourceTypes(LogicalType::VARCHAR)) { + // VARIANT does not preserve aliases, including JSON in nested types. + if (TypeVisitor::Contains(type, [](const LogicalType &child) { return child.HasAlias(); })) { + continue; + } + switch (type.id()) { + case LogicalTypeId::ANY: + case LogicalTypeId::SQLNULL: + 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::FLOAT: + case LogicalTypeId::DOUBLE: + case LogicalTypeId::DATE: + case LogicalTypeId::TIME: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::INTERVAL: + case LogicalTypeId::UUID: + case LogicalTypeId::DECIMAL: + case LogicalTypeId::STRUCT: + case LogicalTypeId::LIST: + case LogicalTypeId::VARIANT: + conversion_data.varchar_cast_override = true; + return true; + default: + // The serializer already falls back for the remaining types. + break; + } + } + return false; +} + +static bool CastVariantToVarchar(FromVariantConversionData &conversion_data, Vector &result, const SelectionVector &sel, + idx_t offset, idx_t count, optional_idx row) { + if (result.GetType().HasAlias() || HasVarcharCastOverride(conversion_data)) { + StringConversionPayload payload(result); + return CastVariantToPrimitive>( + conversion_data, result, sel, offset, count, row, payload); + } + auto &variant = conversion_data.variant; + auto result_data = FlatVector::GetDataMutable(result); + auto &result_validity = FlatVector::ValidityMutable(result); + + unique_ptr serializer; + auto convert = [&](idx_t row_index, uint32_t values_index, idx_t result_index) { + auto type_id = variant.GetTypeId(row_index, values_index); + if (type_id == VariantLogicalType::VARIANT_NULL) { + result_validity.SetInvalid(result_index); + return true; + } + if (type_id == VariantLogicalType::VARCHAR) { + result_data[result_index] = + StringVector::AddStringOrBlob(result, VariantUtils::DecodeStringData(variant, row_index, values_index)); + return true; + } + if (!serializer) { + serializer = make_uniq(variant); + } + if (!serializer->Serialize(row_index, values_index)) { + return false; + } + auto &serialized = serializer->GetResult(); + // Let the string heap validate the full size before narrowing it to string_t's length. + result_data[result_index] = StringVector::GetStringHeap(result).AddBlob(serialized.data(), serialized.size()); +#ifdef D_ASSERT_IS_ENABLED + VerifyVarcharSerialization(conversion_data, result.GetType(), row_index, values_index, serialized); +#endif + return true; + }; + return CastVariantRows(conversion_data, result, sel, offset, count, row, convert); } static bool FindValues(UnifiedVariantVectorData &variant, idx_t row_index, SelectionVector &sel, @@ -779,9 +1185,7 @@ static bool CastVariant(FromVariantConversionData &conversion_data, Vector &resu if (target_type.IsJSONType()) { return CastVariantToJSON(conversion_data, result, sel, offset, count, row); } - StringConversionPayload string_payload(result); - return CastVariantToPrimitive>( - conversion_data, result, sel, offset, count, row, string_payload); + return CastVariantToVarchar(conversion_data, result, sel, offset, count, row); } case LogicalTypeId::INTERVAL: return CastVariantToPrimitive>( diff --git a/src/duckdb/src/function/cast/variant/to_variant.cpp b/src/duckdb/src/function/cast/variant/to_variant.cpp index d29a20442..abfa57114 100644 --- a/src/duckdb/src/function/cast/variant/to_variant.cpp +++ b/src/duckdb/src/function/cast/variant/to_variant.cpp @@ -234,13 +234,15 @@ static bool CastToVARIANT(Vector &source, Vector &result, idx_t count, CastParam auto &keys_entry = ListVector::GetChildMutable(keys); //! Initialize the dictionary - OrderedOwningStringMap dictionary(StringVector::GetStringAllocator(keys_entry)); + OrderedOwningStringMap dictionary; + auto &keys_arena = StringVector::GetStringAllocator(keys_entry); SelectionVector keys_selvec; ToVariantSourceData source_data(source, count); { VariantVectorData variant_data(result); - ToVariantGlobalResultData result_data(variant_data, offsets, dictionary, keys_selvec, local_data.allocator); + ToVariantGlobalResultData result_data(variant_data, offsets, dictionary, keys_arena, keys_selvec, + local_data.allocator); if (!GatherOffsetsAndSizes(source_data, result_data, count)) { return false; } @@ -252,7 +254,8 @@ static bool CastToVARIANT(Vector &source, Vector &result, idx_t count, CastParam { VariantVectorData variant_data(result); - ToVariantGlobalResultData result_data(variant_data, offsets, dictionary, keys_selvec, local_data.allocator); + ToVariantGlobalResultData result_data(variant_data, offsets, dictionary, keys_arena, keys_selvec, + local_data.allocator); if (!WriteVariantResultData(source_data, result_data, count)) { return false; } diff --git a/src/duckdb/src/function/cast_rules.cpp b/src/duckdb/src/function/cast_rules.cpp index f907d99f3..2c5dd2da7 100644 --- a/src/duckdb/src/function/cast_rules.cpp +++ b/src/duckdb/src/function/cast_rules.cpp @@ -300,6 +300,16 @@ static int64_t ImplicitCastTimestamp(const LogicalType &to) { } } +static int64_t ImplicitCastTimestampTz(const LogicalType &to) { + switch (to.id()) { + case LogicalTypeId::TIMESTAMP_TZ_NS: + // like TIMESTAMP to TIMESTAMP_NS: a TIMESTAMPTZ combines with a TIMESTAMPTZ_NS at nanosecond precision + return TargetTypeCost(to); + default: + return -1; + } +} + static int64_t ImplicitCastBignum(const LogicalType &to) { switch (to.id()) { case LogicalTypeId::DOUBLE: @@ -633,6 +643,8 @@ int64_t CastRules::ImplicitCast(const LogicalType &from, const LogicalType &to) return ImplicitCastTimestampNS(to); case LogicalTypeId::TIMESTAMP: return ImplicitCastTimestamp(to); + case LogicalTypeId::TIMESTAMP_TZ: + return ImplicitCastTimestampTz(to); case LogicalTypeId::BIGNUM: return ImplicitCastBignum(to); case LogicalTypeId::VARIANT: diff --git a/src/duckdb/src/function/function.cpp b/src/duckdb/src/function/function.cpp index bd80e30b4..91434adcc 100644 --- a/src/duckdb/src/function/function.cpp +++ b/src/duckdb/src/function/function.cpp @@ -171,6 +171,9 @@ static bool RequiresCatalogAndSchemaNamePrefix(const Identifier &catalog_name, c } string FunctionParameter::ToString() const { + if (!named) { + return type.ToString(); + } if (kind == FunctionParameterKind::VAR_POSITIONAL) { return StringUtil::Format("*%s %s", SQLIdentifier(name), type.ToString()); } @@ -215,12 +218,17 @@ string FunctionSignature::ToString() const { vector params; params.reserve(parameters.size()); // A keyword-only parameter that no "*args" precedes closes the positional parameters by itself, which Python - // spells as a bare "*" in that position; a "/" likewise closes the positional-only parameters + // spells as a bare "*" in that position; a "/" likewise closes the positional-only parameters. It says that the + // names before it cannot be used, so it is left out when none of them is shown (see FunctionParameter::Unnamed) const auto positional_only_count = GetPositionalOnlyParameterCount(); + bool close_positional_only = false; + for (idx_t i = 0; i < positional_only_count; i++) { + close_positional_only = close_positional_only || parameters[i].IsNamed(); + } auto needs_separator = !GetArgs(); for (idx_t i = 0; i < parameters.size(); i++) { auto ¶m = parameters[i]; - if (i == positional_only_count && positional_only_count > 0) { + if (i == positional_only_count && close_positional_only) { params.push_back("/"); } if (needs_separator && param.GetKind() == FunctionParameterKind::KEYWORD_ONLY) { @@ -229,7 +237,7 @@ string FunctionSignature::ToString() const { } params.push_back(param.ToString()); } - if (positional_only_count > 0 && positional_only_count == parameters.size()) { + if (close_positional_only && positional_only_count == parameters.size()) { params.push_back("/"); } auto head = StringUtil::Format("(%s)", StringUtil::Join(params, ", ")); diff --git a/src/duckdb/src/function/function_binder.cpp b/src/duckdb/src/function/function_binder.cpp index 5dae97d37..c45e5ef7d 100644 --- a/src/duckdb/src/function/function_binder.cpp +++ b/src/duckdb/src/function/function_binder.cpp @@ -393,7 +393,7 @@ std::variant FunctionBinder::MatchOverload(op } if (!filled) { // This parameter cannot be filled by the call, so this function cannot be a match. - mismatch(FunctionMismatch::MissingParameter {i, param.GetName()}); + mismatch(FunctionMismatch::MissingParameter {i, param.IsNamed() ? param.GetName() : Identifier()}); } } @@ -424,7 +424,7 @@ std::variant FunctionBinder::MatchOverload(op } } - if (mismatches > 0) { + if (reason) { // the wrong shape is further away than arguments that cannot be cast, of which there are at most this many return FunctionMismatch(overload, std::move(function), received_count + mismatches, std::move(*reason)); } @@ -446,26 +446,19 @@ std::variant FunctionBinder::MatchOverload(op } } - FunctionBinding binding; - binding.overload = overload; - binding.function = function; + auto get_parameter_index = [&](idx_t i) { + if (i >= received_positional_count) { + auto by_name = sig.GetParameterIndexByName(call.GetArgument(i).name); + return by_name.IsValid() ? by_name.GetIndex() : kwargs_idx.GetIndex(); + } + return i < accepted_positional_count ? i : args_idx.GetIndex(); + }; + idx_t cost = 0; bool has_unknown_argument = false; - vector filled(sig.GetParameterCount(), false); for (idx_t i = 0; i < received_count; i++) { - auto &argument = call.GetArgument(i); - auto &arg_type = argument.type; + auto &arg_type = call.GetArgument(i).type; const bool is_named = i >= received_positional_count; - idx_t param_idx; - if (is_named) { - auto by_name = sig.GetParameterIndexByName(argument.name); - param_idx = by_name.IsValid() ? by_name.GetIndex() : kwargs_idx.GetIndex(); - } else { - param_idx = i < accepted_positional_count ? i : args_idx.GetIndex(); - } - binding.argument_to_parameters.push_back(param_idx); - filled[param_idx] = true; - if (!is_named && arg_type.id() == LogicalTypeId::UNKNOWN) { has_unknown_argument = true; continue; @@ -473,6 +466,7 @@ std::variant FunctionBinder::MatchOverload(op if (explicit_casts) { continue; } + auto param_idx = get_parameter_index(i); int64_t cast_cost = ImplicitCastCost(context, arg_type, sig.GetParameter(param_idx).GetType()); if (cast_cost < 0) { mismatch(FunctionMismatch::IncompatibleArgument {i, sig.GetParameter(param_idx).GetType()}); @@ -480,18 +474,31 @@ std::variant FunctionBinder::MatchOverload(op } cost += static_cast(cast_cost); } - if (mismatches > 0) { + if (reason) { return FunctionMismatch(overload, std::move(function), mismatches, std::move(*reason)); } + // Only candidates whose casts match need a materialized argument-to-parameter mapping. + FunctionBinding binding; + binding.overload = overload; + binding.function = function; + binding.argument_to_parameters.reserve(received_count); + for (idx_t i = 0; i < received_count; i++) { + binding.argument_to_parameters.push_back(get_parameter_index(i)); + } binding.return_type = sig.GetReturnType(); bool is_templated = binding.return_type.IsTemplated(); + binding.parameter_types.reserve(sig.GetParameterCount()); for (auto ¶m : sig.GetParameters()) { binding.parameter_types.push_back(param.GetType()); is_templated = is_templated || param.GetType().IsTemplated(); } if (is_templated) { // the shape and the casts match, so a template that cannot be deduced is the closest miss there is + vector filled(sig.GetParameterCount(), false); + for (auto param_idx : binding.argument_to_parameters) { + filled[param_idx] = true; + } auto template_mismatch = DeduceTemplates(context, sig, call, filled, binding); if (template_mismatch) { return FunctionMismatch(overload, std::move(function), 0, std::move(*template_mismatch)); @@ -522,7 +529,10 @@ FunctionBindResult FunctionBinder::SelectFunction(optional_ptr co auto match = MatchOverload(context, overload, functions.GetSharedOverload(overload), call, explicit_casts); auto binding = std::get_if(&match); if (!binding) { - mismatches.push_back(std::move(std::get(match))); + // Once an overload matches, unsuccessful candidates cannot contribute to the result or diagnostics. + if (cheapest.empty()) { + mismatches.push_back(std::move(std::get(match))); + } continue; } @@ -796,8 +806,7 @@ static ResolvedArguments ResolveArguments(const SimpleFunction &function, const } if (!param.IsVariadic() && received[param_idx].empty()) { // the call matches the function, so every parameter it leaves out has a default - auto default_arg = make_uniq(*param.GetDefaultValue()); - default_arg->SetAlias(param.GetName()); + auto default_arg = make_uniq(*param.GetDefaultValue(), param.GetName()); result.arguments.push_back(std::move(default_arg)); result.types.push_back(param_type); } @@ -998,7 +1007,7 @@ void FunctionBinder::CastToFunctionArguments(const Identifier &function_name, ve function_name); } if (children[i]->GetReturnType().id() == LogicalTypeId::UNKNOWN && !target_type.IsComplete()) { - // an unresolved parameter cannot take an incomplete type, the statement is bound again at EXECUTE + // bind callbacks only see concrete types - an unresolved parameter is bound again at EXECUTE throw ParameterNotResolvedException(); } target_type.Verify(); @@ -1035,19 +1044,23 @@ void FunctionBinder::CastToFunctionArguments(const Identifier &function_name, ve unique_ptr FunctionBinder::BindScalarFunction(const Identifier &schema, const Identifier &name, vector> children, ErrorData &error, - bool is_operator, optional_ptr binder) { + bool is_operator, optional_ptr binder, + Identifier alias, QueryLocation query_location) { // bind the function auto &function = Catalog::GetSystemCatalog(context).GetEntry( context, QualifiedName(Catalog::GetSystemCatalog(context).GetName(), schema, name)); D_ASSERT(function.type == CatalogType::SCALAR_FUNCTION_ENTRY); - return BindScalarFunction(function, std::move(children), error, is_operator, binder); + return BindScalarFunction(function, std::move(children), error, is_operator, binder, std::move(alias), + query_location); } unique_ptr FunctionBinder::BindScalarFunction(const Identifier &schema, const Identifier &name, vector> children, bool is_operator, - optional_ptr binder) { + optional_ptr binder, Identifier alias, + QueryLocation query_location) { ErrorData error; - auto result = BindScalarFunction(schema, name, std::move(children), error, is_operator, binder); + auto result = BindScalarFunction(schema, name, std::move(children), error, is_operator, binder, std::move(alias), + query_location); if (!result) { error.Throw(); } @@ -1056,13 +1069,14 @@ unique_ptr FunctionBinder::BindScalarFunction(const Identifier &sche unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunctionCatalogEntry &func, vector> children, ErrorData &error, - bool is_operator, optional_ptr binder) { + bool is_operator, optional_ptr binder, + Identifier alias, QueryLocation query_location) { vector>> arguments; arguments.reserve(children.size()); for (auto &child : children) { arguments.emplace_back(string(), std::move(child)); } - return BindScalarFunction(func, std::move(arguments), error, is_operator, binder); + return BindScalarFunction(func, std::move(arguments), error, is_operator, binder, std::move(alias), query_location); } //! Returns true if any argument is an untyped NULL, i.e. has type SQLNULL @@ -1104,10 +1118,7 @@ static bool FoldConstantArgument(ClientContext &context, unique_ptr if (result.IsNull()) { return true; } - auto constant = make_uniq(std::move(result)); - constant->SetAlias(child->GetAlias()); - constant->SetQueryLocation(child->GetQueryLocation()); - child = std::move(constant); + child = make_uniq(std::move(result), child->GetAlias(), child->GetQueryLocation()); return false; } @@ -1140,7 +1151,8 @@ static LogicalType NullReturnType(const LogicalType &return_type) { unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunctionCatalogEntry &func, vector>> arguments, ErrorData &error, bool is_operator, - optional_ptr binder) { + optional_ptr binder, Identifier alias, + QueryLocation query_location) { // select the best matching overload (this may name positional arguments by their alias for functions that opt // into implicit argument naming, e.g. struct_pack/row) vector> regular_args; @@ -1162,7 +1174,8 @@ unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunctionCa if (bound_function.GetNullHandling() == FunctionNullHandling::DEFAULT_NULL_HANDLING) { const auto &return_type = bound_function.GetReturnType(); if (HasUntypedNullArgument(regular_args, keyword_args)) { - return make_uniq(Value(NullReturnType(return_type))); + return make_uniq(Value(NullReturnType(return_type)), std::move(alias), + query_location); } if (HasNullConstantArgument(context, regular_args, keyword_args, binder)) { if (return_type.IsComplete()) { @@ -1171,15 +1184,18 @@ unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunctionCa regular_args.push_back(std::move(child.second)); } PropagateReturnCollation(null_function, null_function.GetProperties(), regular_args, string()); - return make_uniq(Value(null_function.GetReturnType())); + return make_uniq(Value(null_function.GetReturnType()), std::move(alias), + query_location); } auto resolved = ResolveScalarFunctionTypes(binding, regular_args, keyword_args); PropagateReturnCollation(resolved.bound_function, resolved.bound_function.GetProperties(), regular_args, resolved.pushed_collation); - return make_uniq(Value(NullReturnType(resolved.bound_function.GetReturnType()))); + return make_uniq(Value(NullReturnType(resolved.bound_function.GetReturnType())), + std::move(alias), query_location); } } - return BindScalarFunction(binding, std::move(regular_args), std::move(keyword_args), is_operator, binder); + return BindScalarFunction(binding, std::move(regular_args), std::move(keyword_args), is_operator, binder, + std::move(alias), query_location); } static bool RequiresCollationPropagation(const LogicalType &type) { @@ -1517,39 +1533,46 @@ FunctionBinder::ResolveScalarFunction(const FunctionBinding &binding, vector FunctionBinder::BindScalarFunction(const shared_ptr &function, vector> children, bool is_operator, - optional_ptr binder) { - return BindScalarFunction(function, std::move(children), {}, is_operator, binder); + optional_ptr binder, Identifier alias, + QueryLocation query_location) { + return BindScalarFunction(function, std::move(children), {}, is_operator, binder, std::move(alias), query_location); } unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunction &function, vector> children, bool is_operator, - optional_ptr binder) { - return BindScalarFunction(make_shared_ptr(function), std::move(children), {}, is_operator, binder); + optional_ptr binder, Identifier alias, + QueryLocation query_location) { + return BindScalarFunction(make_shared_ptr(function), std::move(children), {}, is_operator, binder, + std::move(alias), query_location); } unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunction &function, vector> children, vector>> keyword_args, - bool is_operator, optional_ptr binder) { + bool is_operator, optional_ptr binder, + Identifier alias, QueryLocation query_location) { return BindScalarFunction(make_shared_ptr(function), std::move(children), std::move(keyword_args), - is_operator, binder); + is_operator, binder, std::move(alias), query_location); } unique_ptr FunctionBinder::BindScalarFunction(const shared_ptr &function, vector> children, vector>> keyword_args, - bool is_operator, optional_ptr binder) { + bool is_operator, optional_ptr binder, + Identifier alias, QueryLocation query_location) { auto binding = MatchFunction(function, children, keyword_args); - return BindScalarFunction(binding, std::move(children), std::move(keyword_args), is_operator, binder); + return BindScalarFunction(binding, std::move(children), std::move(keyword_args), is_operator, binder, + std::move(alias), query_location); } unique_ptr FunctionBinder::BindScalarFunction(const FunctionBinding &binding, vector> children, vector>> keyword_args, - bool is_operator, optional_ptr binder) { + bool is_operator, optional_ptr binder, + Identifier alias, QueryLocation query_location) { auto [bound_function, bind_info] = ResolveScalarFunction(binding, children, keyword_args); auto result_func = make_uniq(std::move(bound_function), std::move(children), - std::move(bind_info), is_operator); + std::move(bind_info), is_operator, alias, query_location); if (binder && result_func->Function().GetStability() == FunctionStability::CONSISTENT_WITHIN_QUERY) { // the result depends on the query it is bound in, also when the bind_expression callback folds it @@ -1561,6 +1584,13 @@ unique_ptr FunctionBinder::BindScalarFunction(const FunctionBinding result_func->GetChildrenMutable()); auto result = result_func->Function().GetBindExpressionCallback()(input); if (result) { + // the callback constructs the expression itself + if (!alias.empty()) { + result->SetAlias(std::move(alias)); + } + if (query_location.IsValid()) { + result->SetQueryLocation(query_location); + } return result; } } diff --git a/src/duckdb/src/function/macro_function.cpp b/src/duckdb/src/function/macro_function.cpp index f8fba3ef2..281bae58b 100644 --- a/src/duckdb/src/function/macro_function.cpp +++ b/src/duckdb/src/function/macro_function.cpp @@ -349,6 +349,26 @@ void MacroFunction::FinalizeDeserialization() { } } +bool MacroFunction::MatchesSignature(const vector &signature) const { + if (parameters.size() != signature.size()) { + return false; + } + for (idx_t i = 0; i < signature.size(); i++) { + const auto member_type_id = i < types.size() ? types[i].id() : LogicalTypeId::UNKNOWN; + if (signature[i].id() == LogicalTypeId::ANY) { + // ANY names an untyped slot exactly, it does not match a typed slot + if (member_type_id != LogicalTypeId::UNKNOWN) { + return false; + } + continue; + } + if (member_type_id == LogicalTypeId::UNKNOWN || types[i] != signature[i]) { + return false; + } + } + return true; +} + string MacroFunction::ToSQL() const { vector param_strings; for (idx_t param_idx = 0; param_idx < parameters.size(); param_idx++) { diff --git a/src/duckdb/src/function/pragma/pragma_functions.cpp b/src/duckdb/src/function/pragma/pragma_functions.cpp index 4ddce15a7..73edcec05 100644 --- a/src/duckdb/src/function/pragma/pragma_functions.cpp +++ b/src/duckdb/src/function/pragma/pragma_functions.cpp @@ -78,7 +78,7 @@ static void PragmaEnableForceParallelism(ClientContext &context, const FunctionP static void PragmaForceCheckpoint(ClientContext &context, const FunctionParameters ¶meters) { DBConfig::GetConfig(context).CheckLock("force_checkpoint"); - DBConfig::GetConfig(context).options.force_checkpoint = true; + Settings::Set(context, SetScope::GLOBAL, Value::BOOLEAN(true)); } static void PragmaDisableForceParallelism(ClientContext &context, const FunctionParameters ¶meters) { @@ -96,12 +96,12 @@ static void PragmaDisableObjectCache(ClientContext &context, const FunctionParam static void PragmaEnableCheckpointOnShutdown(ClientContext &context, const FunctionParameters ¶meters) { DBConfig::GetConfig(context).CheckLock("checkpoint_on_shutdown"); - DBConfig::GetConfig(context).options.checkpoint_on_shutdown = true; + Settings::Set(context, SetScope::GLOBAL, Value::BOOLEAN(true)); } static void PragmaDisableCheckpointOnShutdown(ClientContext &context, const FunctionParameters ¶meters) { DBConfig::GetConfig(context).CheckLock("checkpoint_on_shutdown"); - DBConfig::GetConfig(context).options.checkpoint_on_shutdown = false; + Settings::Set(context, SetScope::GLOBAL, Value::BOOLEAN(false)); } static string PragmaEnableOptimizer(ClientContext &context, const FunctionParameters ¶meters) { diff --git a/src/duckdb/src/function/scalar/comparison/comparison.cpp b/src/duckdb/src/function/scalar/comparison/comparison.cpp index 99d556ff2..5717a36da 100644 --- a/src/duckdb/src/function/scalar/comparison/comparison.cpp +++ b/src/duckdb/src/function/scalar/comparison/comparison.cpp @@ -241,7 +241,7 @@ unique_ptr &BoundComparisonExpression::RightMutable(BoundFunctionExp } void BoundComparisonExpression::SetType(BoundFunctionExpression &comparison_expr, ExpressionType new_type) { - auto arguments = comparison_expr.FunctionMutable().GetArguments(); + auto arguments = comparison_expr.Function().GetArguments(); comparison_expr.SetExpressionTypeUnsafe(new_type); comparison_expr.FunctionMutable() = BoundScalarFunction(GetComparisonFunction(new_type)); 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 46796845a..434a250dd 100644 --- a/src/duckdb/src/function/scalar/compressed_materialization/compress_string.cpp +++ b/src/duckdb/src/function/scalar/compressed_materialization/compress_string.cpp @@ -1,4 +1,6 @@ #include "duckdb/common/bswap.hpp" +#include "duckdb/main/context.hpp" +#include "duckdb/main/database.hpp" #include "duckdb/function/scalar/compressed_materialization_functions.hpp" #include "duckdb/function/scalar/compressed_materialization_utils.hpp" #include "duckdb/common/serializer/serializer.hpp" @@ -120,7 +122,7 @@ string StringDecompressFunctionName() { struct StringDecompressLocalState : public FunctionLocalState { public: - explicit StringDecompressLocalState(ClientContext &context) : allocator(Allocator::Get(context)) { + explicit StringDecompressLocalState(Context &context) : allocator(Allocator::Get(context.GetDatabase())) { } static unique_ptr Init(ExpressionState &state, const BoundFunctionExpression &expr, diff --git a/src/duckdb/src/function/scalar/compressed_materialization_utils.cpp b/src/duckdb/src/function/scalar/compressed_materialization_utils.cpp index f3d2949d9..fed2a951a 100644 --- a/src/duckdb/src/function/scalar/compressed_materialization_utils.cpp +++ b/src/duckdb/src/function/scalar/compressed_materialization_utils.cpp @@ -15,7 +15,6 @@ ScalarFunction InternalCompressedMaterializationCastFun::GetFunction() { void CMUtils::MarkCast(BoundFunctionExpression &expression) { D_ASSERT(BoundCastExpression::IsCast(expression)); - D_ASSERT(BoundCastExpression::IsDefaultCast(expression)); auto definition = make_shared_ptr(InternalCompressedMaterializationCastFun::GetFunction()); auto &function = expression.FunctionMutable(); function.SetName(definition->GetName()); @@ -53,6 +52,23 @@ optional_ptr CMUtils::GetWrappedInput(const Expression &expres return function.GetChildren()[0].get(); } +bool CMUtils::CompressesInput(const Expression &expression) { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { + return false; + } + auto &function = expression.Cast(); + switch (GetExpressionType(function)) { + case CMExpressionType::COMPRESS: + return true; + case CMExpressionType::CAST: + // the cast narrows the type when it compresses and widens it back when it decompresses + return GetTypeIdSize(function.GetReturnType().InternalType()) < + GetTypeIdSize(function.GetChildren()[0]->GetReturnType().InternalType()); + default: + return false; + } +} + const vector CMUtils::IntegralTypes() { return {LogicalType::UTINYINT, LogicalType::USMALLINT, LogicalType::UINTEGER, LogicalType::UBIGINT}; } diff --git a/src/duckdb/src/function/scalar/generic/getvariable.cpp b/src/duckdb/src/function/scalar/generic/getvariable.cpp index 4eca4fa03..b7dfe5f41 100644 --- a/src/duckdb/src/function/scalar/generic/getvariable.cpp +++ b/src/duckdb/src/function/scalar/generic/getvariable.cpp @@ -26,12 +26,7 @@ struct GetVariableBindData : FunctionData { unique_ptr GetVariableBind(BindScalarFunctionInput &input) { auto &context = input.GetClientContext(); - auto &arguments = input.GetArguments(); auto &function = input.GetBoundFunction(); - - if (arguments[0]->GetReturnType().id() == LogicalTypeId::UNKNOWN) { - throw ParameterNotResolvedException(); - } auto variable_name = input.GetConstant(0); Value value; if (!variable_name.IsNull()) { diff --git a/src/duckdb/src/function/scalar/generic/invoke.cpp b/src/duckdb/src/function/scalar/generic/invoke.cpp index baa8f1d78..42a45928e 100644 --- a/src/duckdb/src/function/scalar/generic/invoke.cpp +++ b/src/duckdb/src/function/scalar/generic/invoke.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/function/scalar/generic_functions.hpp" #include "duckdb/function/lambda_functions.hpp" #include "duckdb/function/scalar_function.hpp" diff --git a/src/duckdb/src/function/scalar/list/list_zip.cpp b/src/duckdb/src/function/scalar/list/list_zip.cpp index e7318989f..cd219ec7e 100644 --- a/src/duckdb/src/function/scalar/list/list_zip.cpp +++ b/src/duckdb/src/function/scalar/list/list_zip.cpp @@ -163,8 +163,6 @@ static unique_ptr ListZipBind(BindScalarFunctionInput &input) { case LogicalTypeId::SQLNULL: struct_children.emplace_back(make_pair(string(), LogicalTypeId::SQLNULL)); break; - case LogicalTypeId::UNKNOWN: - throw ParameterNotResolvedException(); default: throw BinderException("Parameter type needs to be List"); } diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index cbd9e05e3..58cf027e5 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/assert.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/types/value.hpp" @@ -274,6 +275,7 @@ unique_ptr PropagateNumericStats(ClientContext &context, Functio } expr.FunctionMutable().SetFunctionCallback( GetScalarIntegerFunction(expr.GetReturnType().InternalType())); + expr.FunctionMutable().SetErrorMode(FunctionErrors::CANNOT_ERROR); } auto result = NumericStats::CreateEmpty(expr.GetReturnType()); NumericStats::SetMin(result, new_min); @@ -403,7 +405,9 @@ void DecimalAddSubtractResolveTypes(ResolveScalarFunctionTypesInput &input) { if (check_overflow) { bound_function.SetFunctionCallback(GetScalarBinaryFunction(result_type.InternalType())); } else { + // the result type holds every result of the operation, so it cannot overflow bound_function.SetFunctionCallback(GetScalarBinaryFunction(result_type.InternalType())); + bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } if (IS_SUBTRACT) { bound_function.SetStatisticsCallback( @@ -432,6 +436,7 @@ unique_ptr DeserializeDecimalArithmetic(Deserializer &deserializer bound_function.SetFunctionCallback(GetScalarBinaryFunction(return_type.InternalType())); } else { bound_function.SetFunctionCallback(GetScalarBinaryFunction(return_type.InternalType())); + bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } bound_function.SetStatisticsCallback(nullptr); // TODO we likely dont want to do stats prop again bound_function.SetReturnType(return_type); @@ -482,14 +487,9 @@ static void BignumSubtract(DataChunk &args, ExpressionState &state, Vector &resu }); } -//! The client context (if any) lets long BIGNUM multiplications and divisions check for interrupts -static optional_ptr GetBignumArithmeticContext(ExpressionState &state) { - return state.HasContext() ? &state.GetContext() : nullptr; -} - static void BignumMultiply(DataChunk &args, ExpressionState &state, Vector &result) { auto &heap = StringVector::GetStringHeap(result); - BignumArithmeticState arithmetic_state(GetBignumArithmeticContext(state)); + BignumArithmeticState arithmetic_state(state.GetContext()); BinaryExecutor::Execute( args.data[0], args.data[1], result, [&](bignum_t a, bignum_t b) { const BignumIntermediate lhs(a); @@ -1196,7 +1196,9 @@ void DecimalMultiplyResolveTypes(ResolveScalarFunctionTypesInput &input) { bound_function.SetFunctionCallback( GetScalarBinaryFunction(result_type.InternalType())); } else { + // the result type holds every product of the input types, so the operation cannot overflow bound_function.SetFunctionCallback(GetScalarBinaryFunction(result_type.InternalType())); + bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } bound_function.SetStatisticsCallback( PropagateNumericStats); @@ -1249,7 +1251,11 @@ ScalarFunctionSet OperatorMultiplyFun::GetFunctions() { // we can multiply bignums together multiply.AddFunction( ScalarFunction({LogicalType::BIGNUM, LogicalType::BIGNUM}, LogicalType::BIGNUM, BignumMultiply)); - multiply.SetFallible(); + multiply.ApplyToFunctions([](ScalarFunction &function) { + if (!function.GetReturnType().IsFloating()) { + function.SetFallible(); + } + }); multiply.ApplyToFunctions(NameOperatorParameters); return multiply; @@ -1446,13 +1452,18 @@ unique_ptr BindBinaryFloatingPoint(BindScalarFunctionInput &input) auto &context = input.GetClientContext(); auto &bound_function = input.GetBoundFunction(); - if (Settings::Get(context)) { + const auto ieee_ops = Settings::Get(context); + const auto null_on_zero = !Settings::Get(context); + if (ieee_ops) { bound_function.SetFunctionCallback(GetScalarBinaryFunction(bound_function.GetReturnType().InternalType())); } else { - auto null_on_zero = !Settings::Get(context); bound_function.SetFunctionCallback( GetBinaryFunctionZeroCheck(bound_function.GetReturnType().InternalType(), null_on_zero)); } + if (std::is_same::value && (ieee_ops || null_on_zero)) { + // a division by zero yields inf, nan or NULL instead of raising an error + bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); + } return nullptr; } @@ -1511,7 +1522,7 @@ unique_ptr PropagateIntegerDivideStats(ClientContext &context, F template static void BignumDivideOperation(DataChunk &args, ExpressionState &state, Vector &result) { auto &heap = StringVector::GetStringHeap(result); - BignumArithmeticState arithmetic_state(GetBignumArithmeticContext(state)); + BignumArithmeticState arithmetic_state(state.GetContext()); BinaryExecutor::Execute( args.data[0], args.data[1], result, [&](bignum_t a, bignum_t b) -> optional { const BignumIntermediate lhs(a); diff --git a/src/duckdb/src/function/scalar/operator/cast.cpp b/src/duckdb/src/function/scalar/operator/cast.cpp index 0c416e702..09f0eea27 100644 --- a/src/duckdb/src/function/scalar/operator/cast.cpp +++ b/src/duckdb/src/function/scalar/operator/cast.cpp @@ -22,7 +22,7 @@ static BoundCastInfo BindCastScalarFunction(ClientContext &context, const Logica static BoundCastInfo BindDefaultCastScalarFunction(const LogicalType &source, const LogicalType &target) { CastFunctionSet cast_functions; - GetCastFunctionInput input; + auto input = GetCastFunctionInput::Default(); return cast_functions.GetCastFunction(source, target, input); } @@ -100,7 +100,7 @@ static unique_ptr CastInitLocalState(ExpressionState &state, if (!cast_data.bound_cast.HasInitLocalState()) { return nullptr; } - auto context_ptr = state.root.executor->HasContext() ? &state.root.executor->GetContext() : nullptr; + auto context_ptr = state.root.executor->TryGetClientContext(); CastLocalStateParameters parameters(context_ptr, cast_data.bound_cast.GetCastData()); return cast_data.bound_cast.InitLocalState(parameters); } @@ -196,10 +196,8 @@ static unique_ptr CreateCastExpression(unique_ptr child, BoundScalarFunction bound_function(scalar_function); bound_function.GetArguments() = {source_type}; - auto result = make_uniq(std::move(bound_function), std::move(children), - std::move(function_data), true); - result->SetQueryLocation(query_location); - return std::move(result); + return make_uniq(std::move(bound_function), std::move(children), std::move(function_data), + true, Identifier(), query_location); } unique_ptr BoundCastExpression::Create(unique_ptr child, const LogicalType &target_type, @@ -255,7 +253,7 @@ const BoundCastInfo &BoundCastExpression::GetBoundCast(const BoundFunctionExpres } BoundCastInfo &BoundCastExpression::GetBoundCastMutable(BoundFunctionExpression &cast_expr) { - return cast_expr.BindInfoMutable()->Cast().bound_cast; + return cast_expr.BindInfo()->Cast().bound_cast; } unique_ptr BoundCastExpression::PropagateStatistics(BoundFunctionExpression &cast_expr, diff --git a/src/duckdb/src/function/scalar/sequence/nextval.cpp b/src/duckdb/src/function/scalar/sequence/nextval.cpp index b8257b420..8191a3697 100644 --- a/src/duckdb/src/function/scalar/sequence/nextval.cpp +++ b/src/duckdb/src/function/scalar/sequence/nextval.cpp @@ -74,7 +74,7 @@ unique_ptr NextValLocalFunction(ExpressionState &state, cons if (!bind_data) { return nullptr; } - auto &context = state.GetContext(); + auto &context = state.GetClientContext(); auto &info = bind_data->Cast(); auto &sequence = info.sequence; auto &transaction = DuckTransaction::Get(context, sequence.catalog); diff --git a/src/duckdb/src/function/scalar/struct/struct_concat.cpp b/src/duckdb/src/function/scalar/struct/struct_concat.cpp index 2013b591d..5c8b717ea 100644 --- a/src/duckdb/src/function/scalar/struct/struct_concat.cpp +++ b/src/duckdb/src/function/scalar/struct/struct_concat.cpp @@ -37,10 +37,6 @@ static unique_ptr StructConcatBind(BindScalarFunctionInput &input) for (idx_t arg_idx = 0; arg_idx < arguments.size(); arg_idx++) { const auto &arg = arguments[arg_idx]; - if (arg->GetReturnType().id() == LogicalTypeId::UNKNOWN) { - throw ParameterNotResolvedException(); - } - if (!StructType::IsStruct(arg->GetReturnType())) { throw InvalidInputException("struct_concat: Argument at position \"%d\" is not a STRUCT", arg_idx + 1); } diff --git a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp index bd67c027c..43bc7539d 100644 --- a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/types/value.hpp" #include "duckdb/common/types/variant.hpp" #include "duckdb/common/enum_util.hpp" +#include "duckdb/common/optional.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/types/variant_iterator.hpp" #include "duckdb/common/types/variant_comparison.hpp" @@ -125,8 +126,24 @@ void VariantEncodeString(SINK &sink, const string_t &str, bool is_varchar) { sink.Write(STRING_DELIMITER); } +//! An ARRAY or OBJECT being encoded, and the position of its next child. The open containers are kept on an explicit +//! stack, so that deeply nested values cannot overflow the call stack +struct VariantEncodeFrame { + explicit VariantEncodeFrame(const VariantNode &array) { + elements.emplace(array.GetArrayChildren()); + } + VariantEncodeFrame(const VariantNode &object, VariantIterationOrder order) { + entries.emplace(object, order); + } + + optional elements; + optional entries; + idx_t next_child = 0; +}; + +//! Encodes a single value, or opens the frame of an ARRAY or OBJECT and returns true template -void EncodeVariantValue(const VariantNode &it, SINK &sink) { +bool EncodeVariantNode(const VariantNode &it, SINK &sink, vector &frames) { const auto type_id = it.GetTypeId(); const auto comparison_type = GetVariantComparisonType(type_id); // write the type rank - this guarantees values are ordered by type first @@ -190,27 +207,58 @@ void EncodeVariantValue(const VariantNode &it, SINK &sink) { sink.Write(STRING_DELIMITER); break; } - case VariantComparisonType::ARRAY: { - for (auto child : it.GetArrayChildren()) { - EncodeVariantValue(child, sink); - } - sink.Write(LIST_DELIMITER); - break; - } - case VariantComparisonType::OBJECT: { + case VariantComparisonType::ARRAY: + frames.emplace_back(it); + return true; + case VariantComparisonType::OBJECT: // process the children in string-sorted key order so that objects that only differ in key order // compare equal - for (auto &entry : it.GetObjectChildren(VariantIterationOrder::LEXICOGRAPHIC)) { - VariantEncodeString(sink, entry.key, true); - EncodeVariantValue(entry.value, sink); - } - sink.Write(LIST_DELIMITER); - break; - } + frames.emplace_back(it, VariantIterationOrder::LEXICOGRAPHIC); + return true; default: throw NotImplementedException("Variant type %s is not supported in variant_comparator", EnumUtil::ToString(type_id)); } + return false; +} + +//! Encodes the children of the frame on top, until one of them opens a frame. Returns whether the frame is done +template +bool EncodeVariantChildren(VariantEncodeFrame &frame, SINK &sink, vector &frames) { + if (frame.elements) { + auto &elements = *frame.elements; + while (frame.next_child < elements.size()) { + auto element = elements[frame.next_child++]; + if (EncodeVariantNode(element, sink, frames)) { + return false; + } + } + return true; + } + auto &entries = frame.entries->GetOrderedEntries(); + while (frame.next_child < entries.size()) { + auto entry = entries[frame.next_child++]; + VariantEncodeString(sink, entry.key, true); + if (EncodeVariantNode(entry.value, sink, frames)) { + return false; + } + } + return true; +} + +template +void EncodeVariantValue(const VariantNode &root, SINK &sink, vector &frames) { + frames.clear(); + if (!EncodeVariantNode(root, sink, frames)) { + return; + } + while (!frames.empty()) { + // the frame is not used after one of its children opened another, which may move it + if (EncodeVariantChildren(frames.back(), sink, frames)) { + frames.pop_back(); + sink.Write(LIST_DELIMITER); + } + } } //! Encodes the *logical* value of a VARIANT into a byte-comparable sort key. VARIANT is physically a @@ -226,6 +274,7 @@ void CreateVariantComparator(const Vector &input, idx_t count, Vector &result) { //! reused growable buffer, so encoding a chunk does not allocate once per value string buffer; + vector frames; for (idx_t r = 0; r < count; r++) { auto root = variant[r]; // a VARIANT is only NULL at the root via a genuine SQL NULL (never a VARIANT_NULL value) @@ -238,7 +287,7 @@ void CreateVariantComparator(const Vector &input, idx_t count, Vector &result) { // NULLs are handled via validity above, so no NULL/validity prefix byte is needed in the key. buffer.clear(); VariantComparatorBufferSink sink(buffer); - EncodeVariantValue(root, sink); + EncodeVariantValue(root, sink, frames); writer.WriteValue(string_t(buffer.data(), NumericCast(buffer.size()))); } } diff --git a/src/duckdb/src/function/scalar/variant/variant_normalize.cpp b/src/duckdb/src/function/scalar/variant/variant_normalize.cpp index 639ad4484..7102dff0f 100644 --- a/src/duckdb/src/function/scalar/variant/variant_normalize.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_normalize.cpp @@ -14,9 +14,9 @@ namespace duckdb { VariantNormalizerState::VariantNormalizerState(idx_t result_row, VariantVectorData &source, - OrderedOwningStringMap &dictionary, + OrderedOwningStringMap &dictionary, ArenaAllocator &keys_arena, SelectionVector &keys_selvec) - : source(source), dictionary(dictionary), keys_selvec(keys_selvec), + : source(source), dictionary(dictionary), keys_arena(keys_arena), keys_selvec(keys_selvec), keys_index_validity(source.keys_index_validity) { auto keys_list_entry = source.keys_data[result_row]; auto values_list_entry = source.values_data[result_row]; @@ -38,7 +38,7 @@ data_ptr_t VariantNormalizerState::GetDestination() { uint32_t VariantNormalizerState::GetOrCreateIndex(const string_t &key) { auto unsorted_idx = dictionary.size(); //! This will later be remapped to the sorted idx (see FinalizeVariantKeys in 'to_variant.cpp') - return dictionary.emplace(std::make_pair(key, unsorted_idx)).first->second; + return dictionary.emplace(std::make_pair(key, unsorted_idx), keys_arena).first->second; } void VariantNormalizer::VisitNull(VariantNormalizerState &state) { @@ -212,7 +212,8 @@ void VariantNormalizer::Normalize(const Vector &variant_vec, Vector &result) { //! Initialize the dictionary auto &keys_entry = ListVector::GetChildMutable(keys); - OrderedOwningStringMap dictionary(StringVector::GetStringAllocator(keys_entry)); + OrderedOwningStringMap dictionary; + auto &keys_arena = StringVector::GetStringAllocator(keys_entry); VariantVectorData variant_data(result); SelectionVector keys_selvec; @@ -237,7 +238,7 @@ void VariantNormalizer::Normalize(const Vector &variant_vec, Vector &result) { values_list_entry.offset = ListVector::GetListSize(values); //! Visit the source to populate the result - VariantNormalizerState visitor_state(i, variant_data, dictionary, keys_selvec); + VariantNormalizerState visitor_state(i, variant_data, dictionary, keys_arena, keys_selvec); VariantVisitor::Visit(variant, i, 0, 0, visitor_state); blob_data.SetSizeAndFinalize(visitor_state.blob_size, original_data.GetSize()); 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 6f454fd29..f8250b833 100644 --- a/src/duckdb/src/function/table/system/create_external_resource.cpp +++ b/src/duckdb/src/function/table/system/create_external_resource.cpp @@ -60,7 +60,7 @@ static bool MapTryGet(const Value &map_value, const string &key, string &out) { return false; } -Value RequireResourceMap(const Value &value, const string &function_name, const string &column) { +Value RequireResourceMap(Context &context, const Value &value, const string &function_name, const string &column) { if (value.IsNull()) { return value; } @@ -68,7 +68,7 @@ Value RequireResourceMap(const Value &value, const string &function_name, const throw InvalidInputException("external resource callback \"%s\" must return a MAP in its '%s' column, got %s", function_name, column, value.type().ToString()); } - return value.DefaultCastAs(LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); + return value.CastAs(context, LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); } //===--------------------------------------------------------------------===// @@ -200,7 +200,7 @@ static void CreateExternalResourceFunction(ClientContext &context, TableFunction const bool adopting = !bind_data.adopt_handle.IsNull(); Value handle; if (adopting) { - handle = RequireResourceMap(bind_data.adopt_handle, bind_data.type_name, "handle"); + handle = RequireResourceMap(context.GetContext(), bind_data.adopt_handle, bind_data.type_name, "handle"); } else { if (type->create_function.empty()) { throw InvalidInputException("create_external_resource: resource type \"%s\" has no create function", @@ -220,7 +220,8 @@ static void CreateExternalResourceFunction(ClientContext &context, TableFunction throw InvalidInputException("create_external_resource: create function \"%s\" returned no rows", type->create_function); } - handle = RequireResourceMap(result->Collection().GetRows().GetValue(0, 0), type->create_function, "handle"); + handle = RequireResourceMap(context.GetContext(), result->Collection().GetRows().GetValue(0, 0), + type->create_function, "handle"); if (handle.IsNull()) { // the handle identifies the resource for status and teardown - without one it can never be destroyed throw InvalidInputException("create_external_resource: create function \"%s\" returned a NULL handle", @@ -313,7 +314,8 @@ static void CreateExternalResourceFunction(ClientContext &context, TableFunction bind_data.type_name); } if (status_state == "ready") { - status_result = RequireResourceMap(status_rows.GetValue(1, 0), type->status_function, "result"); + status_result = RequireResourceMap(context.GetContext(), status_rows.GetValue(1, 0), + type->status_function, "result"); ready = true; } else if (has_deadline && std::chrono::steady_clock::now() >= deadline) { throw IOException("create_external_resource: timed out awaiting readiness for \"%s\" (last state '%s')", diff --git a/src/duckdb/src/function/table/system/duckdb_extension_repositories.cpp b/src/duckdb/src/function/table/system/duckdb_extension_repositories.cpp index 3a89af8d9..e63c8319b 100644 --- a/src/duckdb/src/function/table/system/duckdb_extension_repositories.cpp +++ b/src/duckdb/src/function/table/system/duckdb_extension_repositories.cpp @@ -32,6 +32,9 @@ static unique_ptr DuckDBExtensionRepositoriesBind(ClientContext &c names.emplace_back("public_keys"); return_types.emplace_back(LogicalType::LIST(LogicalType::VARCHAR)); + names.emplace_back("host"); + return_types.emplace_back(LogicalType::VARCHAR); + return nullptr; } @@ -70,12 +73,15 @@ void DuckDBExtensionRepositoriesFunction(ClientContext &context, TableFunctionIn auto &key_fingerprints = output.data[3]; // public_keys, LIST(VARCHAR) auto &public_keys = output.data[4]; + // host, VARCHAR: the host a repository was resolved from, NULL for one added by prefix or built in + auto &host = output.data[5]; while (data.offset < data.entries.size() && count < STANDARD_VECTOR_SIZE) { auto &entry = data.entries[data.offset++]; name.Append(Value(entry.name)); prefix.Append(Value(entry.path)); type.Append(Value(EnumUtil::ToString(entry.type))); + host.Append(entry.host.empty() ? Value(LogicalType::VARCHAR) : Value(entry.host)); // only user provided repositories have keys of their own - the core and community keys are built in if (entry.public_keys.empty()) { key_fingerprints.Append(Value(LogicalType::LIST(LogicalType::VARCHAR))); diff --git a/src/duckdb/src/function/table/system/duckdb_extensions.cpp b/src/duckdb/src/function/table/system/duckdb_extensions.cpp index 8d0b8aeb9..133e7a3da 100644 --- a/src/duckdb/src/function/table/system/duckdb_extensions.cpp +++ b/src/duckdb/src/function/table/system/duckdb_extensions.cpp @@ -70,6 +70,8 @@ static unique_ptr DuckDBExtensionsBind(ClientContext &context, Tab return nullptr; } +using ExtensionKey = std::pair; + unique_ptr DuckDBExtensionsInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); @@ -77,7 +79,8 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context auto &db = DatabaseInstance::GetDatabase(context); // Firstly, we go over all Default Extensions: duckdb_extensions always prints those, installed/loaded or not - map installed_extensions; + map installed_extensions; + unordered_map installed_paths; auto extension_count = ExtensionHelper::DefaultExtensionCount(); auto alias_count = ExtensionHelper::ExtensionAliasCount(); for (idx_t i = 0; i < extension_count; i++) { @@ -94,7 +97,7 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context info.aliases.emplace_back(alias.alias); } } - installed_extensions[info.name] = std::move(info); + installed_extensions[ExtensionKey(info.name, string())] = std::move(info); } // Extensions linked into this binary are built in, whether or not the default list knows them @@ -102,7 +105,7 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context if (!linked.load) { continue; } - auto &info = installed_extensions[linked.name]; + auto &info = installed_extensions[ExtensionKey(linked.name, string())]; info.name = linked.name; info.installed = true; info.file_path = "(BUILT-IN)"; @@ -111,8 +114,8 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context // Secondly we scan all installed extensions and their install info #ifndef WASM_LOADABLE_EXTENSIONS - auto ext_directories = ExtensionHelper::GetExtensionDirectoryPath(context); - for (const auto &ext_directory : ext_directories) { + for (const auto &directory : ExtensionHelper::GetInstalledExtensionDirectories(context)) { + const auto &ext_directory = directory.path; fs.ListFiles(ext_directory, [&](const string &path, bool is_directory) { if (!ExtensionHelper::IsInstalledExtensionFile(path)) { return; @@ -131,21 +134,25 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context info.install_mode = extension_install_info->mode; info.extension_version = extension_install_info->version; info.signature_key_fingerprint = extension_install_info->signature_key_fingerprint; - if (extension_install_info->mode == ExtensionInstallMode::REPOSITORY) { - info.installed_from = ExtensionRepository::GetRepository(extension_install_info->repository_url); - } else { + if (extension_install_info->mode != ExtensionInstallMode::REPOSITORY) { info.installed_from = extension_install_info->full_path; + } else if (extension_install_info->repository_type == ExtensionRepositoryType::USER_PROVIDED && + !extension_install_info->repository_name.empty()) { + info.installed_from = extension_install_info->repository_name; + } else { + info.installed_from = ExtensionRepository::GetRepository(extension_install_info->repository_url); } - auto entry = installed_extensions.find(info.name); + ExtensionKey key(info.name, directory.repository); + installed_paths[fs.CanonicalizePath(info.file_path)] = key; + auto entry = installed_extensions.find(key); if (entry == installed_extensions.end()) { - installed_extensions[info.name] = std::move(info); + installed_extensions[key] = std::move(info); } else { if (entry->second.install_mode != ExtensionInstallMode::STATICALLY_LINKED) { entry->second.file_path = info.file_path; entry->second.install_mode = info.install_mode; entry->second.installed_from = info.installed_from; - entry->second.install_mode = info.install_mode; entry->second.extension_version = info.extension_version; entry->second.signature_key_fingerprint = info.signature_key_fingerprint; } @@ -168,10 +175,17 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context continue; } auto &ext_data = *ext_info; + + ExtensionKey key(ext_name, string()); + auto installed_path = installed_paths.find(ext_data.file_path); + if (!ext_data.file_path.empty() && installed_path != installed_paths.end() && + installed_path->second.first == ext_name) { + key = installed_path->second; + } if (auto &ext_install_info = ext_data.install_info) { - auto entry = installed_extensions.find(ext_name); + auto entry = installed_extensions.find(key); if (entry == installed_extensions.end() || !entry->second.installed) { - ExtensionInformation &info = installed_extensions[ext_name]; + ExtensionInformation &info = installed_extensions[key]; info.name = ext_name; info.loaded = true; @@ -187,7 +201,7 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context } } if (auto &ext_load_info = ext_data.load_info) { - auto entry = installed_extensions.find(ext_name); + auto entry = installed_extensions.find(key); if (entry != installed_extensions.end()) { entry->second.description = ext_load_info->description; } diff --git a/src/duckdb/src/function/table/system/duckdb_log.cpp b/src/duckdb/src/function/table/system/duckdb_log.cpp index d9415df80..cf3b8f646 100644 --- a/src/duckdb/src/function/table/system/duckdb_log.cpp +++ b/src/duckdb/src/function/table/system/duckdb_log.cpp @@ -4,21 +4,21 @@ #include "duckdb/parser/parser.hpp" #include "duckdb/parser/parser_options.hpp" #include "duckdb/logging/log_manager.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/parser/tableref/subqueryref.hpp" namespace duckdb { struct DuckDBLogData : public GlobalTableFunctionState { - explicit DuckDBLogData(shared_ptr log_storage_p) : log_storage(std::move(log_storage_p)) { - scan_state = log_storage->CreateScanState(LoggingTargetTable::LOG_ENTRIES); - log_storage->InitializeScan(*scan_state); - total_rows = log_storage->GetScanRowCount(LoggingTargetTable::LOG_ENTRIES); + explicit DuckDBLogData(shared_ptr log_sink_p) : log_sink(std::move(log_sink_p)) { + scan_state = log_sink->CreateScanState(LoggingTargetTable::LOG_ENTRIES); + log_sink->InitializeScan(*scan_state); + total_rows = log_sink->GetScanRowCount(LoggingTargetTable::LOG_ENTRIES); } - //! The log storage we are scanning - shared_ptr log_storage; - unique_ptr scan_state; + //! The log sink we are scanning + shared_ptr log_sink; + unique_ptr scan_state; //! The number of log entries when the scan started, if known (for progress) optional_idx total_rows; atomic scanned_rows {0}; @@ -48,23 +48,23 @@ unique_ptr DuckDBLogInit(ClientContext &context, Table auto &log_manager = LogManager::Get(context); if (!log_manager.CanScan(LoggingTargetTable::LOG_ENTRIES)) { throw InvalidConfigurationException( - "Log storage '%s' does not support this query. Select a queryable storage, such as 'memory' or 'file', " - "before generating logs.", + "Log sink '%s' does not support this query. Select a queryable sink, such as 'memory' or 'file', before " + "generating logs.", log_manager.GetConfig().storage); } - return make_uniq(log_manager.GetLogStorage()); + return make_uniq(log_manager.GetLogSink()); } void DuckDBLogFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { auto &data = data_p.global_state->Cast(); - data.log_storage->Scan(*data.scan_state, output); + data.log_sink->Scan(*data.scan_state, output); data.scanned_rows.fetch_add(output.size(), std::memory_order_relaxed); } static double DuckDBLogProgress(ClientContext &context, const FunctionData *bind_data, const GlobalTableFunctionState *global_state) { auto &data = global_state->Cast(); - if (!data.log_storage) { + if (!data.log_sink) { return 100.0; } if (!data.total_rows.IsValid()) { @@ -79,7 +79,7 @@ static double DuckDBLogProgress(ClientContext &context, const FunctionData *bind } unique_ptr DuckDBLogBindReplace(ClientContext &context, TableFunctionBindInput &input) { - auto log_storage = LogManager::Get(context).GetLogStorage(); + auto log_sink = LogManager::Get(context).GetLogSink(); bool denormalized_table = false; auto denormalized_table_setting = input.named_parameters.find("denormalized_table"); @@ -92,12 +92,12 @@ unique_ptr DuckDBLogBindReplace(ClientContext &context, TableFunctionB // Without join contexts we simply scan the LOG_ENTRIES tables if (!denormalized_table) { - auto res = log_storage->BindReplace(context, input, LoggingTargetTable::LOG_ENTRIES); + auto res = log_sink->BindReplace(context, input, LoggingTargetTable::LOG_ENTRIES); return res; } - // If the storage can bind replace for LoggingTargetTable::ALL_LOGS, we use that since that will be most efficient - auto all_log_scan = log_storage->BindReplace(context, input, LoggingTargetTable::ALL_LOGS); + // If the sink can bind replace for LoggingTargetTable::ALL_LOGS, we use that since that will be most efficient + auto all_log_scan = log_sink->BindReplace(context, input, LoggingTargetTable::ALL_LOGS); if (all_log_scan) { return all_log_scan; } diff --git a/src/duckdb/src/function/table/system/duckdb_log_contexts.cpp b/src/duckdb/src/function/table/system/duckdb_log_contexts.cpp index d3b0005fe..5f234b9a9 100644 --- a/src/duckdb/src/function/table/system/duckdb_log_contexts.cpp +++ b/src/duckdb/src/function/table/system/duckdb_log_contexts.cpp @@ -4,7 +4,7 @@ #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/logging/log_manager.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/parser/tableref.hpp" @@ -12,14 +12,14 @@ namespace duckdb { struct DuckDBLogContextData : public GlobalTableFunctionState { - explicit DuckDBLogContextData(shared_ptr log_storage_p) : log_storage(std::move(log_storage_p)) { - scan_state = log_storage->CreateScanState(LoggingTargetTable::LOG_CONTEXTS); - log_storage->InitializeScan(*scan_state); + explicit DuckDBLogContextData(shared_ptr log_sink_p) : log_sink(std::move(log_sink_p)) { + scan_state = log_sink->CreateScanState(LoggingTargetTable::LOG_CONTEXTS); + log_sink->InitializeScan(*scan_state); } - //! The log storage we are scanning - shared_ptr log_storage; - unique_ptr scan_state; + //! The log sink we are scanning + shared_ptr log_sink; + unique_ptr scan_state; }; static unique_ptr DuckDBLogContextBind(ClientContext &context, TableFunctionBindInput &input, @@ -49,23 +49,23 @@ unique_ptr DuckDBLogContextInit(ClientContext &context auto &log_manager = LogManager::Get(context); if (!log_manager.CanScan(LoggingTargetTable::LOG_CONTEXTS)) { throw InvalidConfigurationException( - "Log storage '%s' does not support this query. Select a queryable storage, such as 'memory' or 'file', " - "before generating logs.", + "Log sink '%s' does not support this query. Select a queryable sink, such as 'memory' or 'file', before " + "generating logs.", log_manager.GetConfig().storage); } - return make_uniq(log_manager.GetLogStorage()); + return make_uniq(log_manager.GetLogSink()); } void DuckDBLogContextFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { auto &data = data_p.global_state->Cast(); - data.log_storage->Scan(*data.scan_state, output); + data.log_sink->Scan(*data.scan_state, output); } static unique_ptr DuckDBLogContextsBindReplace(ClientContext &context, TableFunctionBindInput &input) { - auto log_storage = LogManager::Get(context).GetLogStorage(); + auto log_sink = LogManager::Get(context).GetLogSink(); - // Attempt to let the storage BindReplace the scan function - return log_storage->BindReplace(context, input, LoggingTargetTable::LOG_CONTEXTS); + // Attempt to let the sink BindReplace the scan function + return log_sink->BindReplace(context, input, LoggingTargetTable::LOG_CONTEXTS); } void DuckDBLogContextFun::RegisterFunction(BuiltinFunctions &set) { diff --git a/src/duckdb/src/function/table/system/duckdb_settings.cpp b/src/duckdb/src/function/table/system/duckdb_settings.cpp index b90d72b5f..65e0a0c8b 100644 --- a/src/duckdb/src/function/table/system/duckdb_settings.cpp +++ b/src/duckdb/src/function/table/system/duckdb_settings.cpp @@ -117,6 +117,10 @@ unique_ptr DuckDBSettingsInit(ClientContext &context, value.value = option->default_value; } } + if (option->scope == SettingScopeTarget::LOCAL_ONLY) { + // a local-only setting never has a global value + scope = SettingScope::LOCAL; + } value.description = option->description; value.input_type = option->parameter_type; value.scope = EnumUtil::ToString(scope); diff --git a/src/duckdb/src/function/table/system/enable_profiling.cpp b/src/duckdb/src/function/table/system/enable_profiling.cpp index 8d450b8f3..ae02a7b8a 100644 --- a/src/duckdb/src/function/table/system/enable_profiling.cpp +++ b/src/duckdb/src/function/table/system/enable_profiling.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/file_system.hpp" #include "duckdb/main/profiler/gathered_metrics.hpp" #include "duckdb/function/function_set.hpp" +#include "duckdb/execution/operator/helper/physical_set.hpp" namespace duckdb { @@ -35,7 +36,7 @@ static void EnableProfiling(ClientContext &context, TableFunctionInput &data, Da } EnableProfilingSetting::ResetLocal(context); - ProfilingOutputSetting::ResetLocal(context); + Settings::Set(context, SetScope::SESSION, Value("")); } if (!bind_data.format.IsNull()) { @@ -43,11 +44,13 @@ static void EnableProfiling(ClientContext &context, TableFunctionInput &data, Da } if (!bind_data.coverage.IsNull()) { - ProfilingCoverageSetting::SetLocal(context, bind_data.coverage); + PhysicalSet::SetVariable(context, Identifier(ProfilingCoverageSetting::Name), SetScope::SESSION, + bind_data.coverage); } if (!bind_data.save_location.IsNull()) { - ProfilingOutputSetting::SetLocal(context, bind_data.save_location); + PhysicalSet::SetVariable(context, Identifier(ProfilingOutputSetting::Name), SetScope::SESSION, + bind_data.save_location); } if (!bind_data.mode.IsNull()) { diff --git a/src/duckdb/src/function/table/system/logging_utils.cpp b/src/duckdb/src/function/table/system/logging_utils.cpp index 08f6c002c..160451619 100644 --- a/src/duckdb/src/function/table/system/logging_utils.cpp +++ b/src/duckdb/src/function/table/system/logging_utils.cpp @@ -50,17 +50,27 @@ static void VerifyFileStoragePath(LogManager &log_manager, const string &storage static void EnableLogging(ClientContext &context, TableFunctionInput &data, DataChunk &output) { auto bind_data = data.bind_data->Cast(); - DUCKDB_LOG_WARNING(context, "The logging settings have been changed so you may lose warnings printed in the CLI.\n" - "To continue printing warnings to the console, set storage='shell_log_storage'.\n" - "For more info see https://duckdb.org/docs/current/operations_manual/logging/overview.") - auto &log_manager = context.db->GetLogManager(); + // warnings stop being printed in the CLI when they no longer reach the shell's sink + static constexpr const char *SHELL_LOG_SINK = "shell_log_sink"; + static constexpr const char *DEPRECATED_SHELL_LOG_SINK = "shell_log_storage"; + const bool leaves_shell_sink = !StringUtil::CIEquals(bind_data.config.storage, SHELL_LOG_SINK) && + !StringUtil::CIEquals(bind_data.config.storage, DEPRECATED_SHELL_LOG_SINK); + const bool drops_warnings = bind_data.config.level > LogLevel::LOG_WARNING || !bind_data.log_types_to_set.empty(); + if (StringUtil::CIEquals(log_manager.GetConfig().storage, SHELL_LOG_SINK) && + (leaves_shell_sink || drops_warnings)) { + DUCKDB_LOG_WARNING(context, + "The logging settings have been changed so you may lose warnings printed in the CLI.\n" + "To continue printing warnings to the console, set storage='shell_log_sink'.\n" + "For more info see https://duckdb.org/docs/current/operations_manual/logging/overview.") + } + // a prepared call can run after the storage it was bound against changed VerifyFileStoragePath(log_manager, bind_data.config.storage, bind_data.storage_config); // Apply the config generated from the input - restoring the previous config if that fails part-way - auto previous = log_manager.GetConfigAndStorage(); + auto previous = log_manager.GetConfigAndSink(); try { log_manager.SetConfig(*context.db, bind_data.config); @@ -72,10 +82,10 @@ static void EnableLogging(ClientContext &context, TableFunctionInput &data, Data } if (!bind_data.storage_config.empty()) { - log_manager.UpdateLogStorageConfig(*context.db, bind_data.storage_config); + log_manager.UpdateLogSinkConfig(*context.db, bind_data.storage_config); } } catch (...) { - // the previous storage itself, as a new one of its kind would lack its storage config + // the previous sink itself, as a new one of its kind would lack its storage config log_manager.RestoreConfig(previous.first, std::move(previous.second)); throw; } @@ -102,7 +112,7 @@ static unique_ptr BindEnableLogging(ClientContext &context, TableF config.CheckLock(EnabledLogTypes::Name); config.CheckLock(LoggingLevel::Name); config.CheckLock(LoggingMode::Name); - config.CheckLock(LoggingStorage::Name); + config.CheckLock(LoggingSink::Name); auto result = make_uniq(); @@ -140,7 +150,7 @@ static unique_ptr BindEnableLogging(ClientContext &context, TableF // If the user didn't explicitly set storage=, infer it. A 'path' in storage_config (provided // either via storage_path= or storage_config={path:...}) implies file storage. Otherwise - // preserve the currently configured storage so logging_storage isn't silently reset. + // preserve the currently configured storage so logging_sink isn't silently reset. if (!storage_isset) { if (result->storage_config.find("path") != result->storage_config.end()) { result->config.storage = LogConfig::FILE_STORAGE_NAME; @@ -183,9 +193,9 @@ static void DisableLogging(ClientContext &context, TableFunctionInput &data, Dat context.db->GetLogManager().SetEnableLogging(false); } -//! Truncate the current log storage +//! Truncate the current log sink static void TruncateLogs(ClientContext &context, TableFunctionInput &data, DataChunk &output) { - context.db->GetLogManager().TruncateLogStorage(); + context.db->GetLogManager().TruncateLogSink(); } static unique_ptr BindDisableLogging(ClientContext &context, TableFunctionBindInput &input, diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index d6341077b..305741049 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -945,12 +945,10 @@ bool TryScanIndex(const IndexReadHandle &art, const ColumnList &column_list // A bound column reference in an unbound index expression is an ordinal into indexed_columns, which is not the // column's position in this scan. Rebind the references to the ART column's position in the scan input. - ExpressionIterator::EnumerateExpression(index_expr, [&](Expression &expr) { - if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return; - } - expr.Cast().BindingMutable().column_index = storage_index; - }); + index_expr = ExpressionIterator::PreorderReplace( + std::move(index_expr), [&](const BoundColumnRefExpression &colref) { + return colref.WithBinding(ColumnBinding(colref.Binding().table_index, storage_index)); + }); // Try to find a matching filter for the column. auto filter = filter_set.TryGetFilterByColumnIndex(storage_index); diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index d097e3018..9f6dcce81 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-alpha54418" +#define DUCKDB_PATCH_VERSION "0-alpha55910" #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-alpha54418" +#define DUCKDB_VERSION "v2.1.0-alpha55910" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "23221edfd5" +#define DUCKDB_SOURCE_ID "6f053d3d8f" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/window/window_executor.cpp b/src/duckdb/src/function/window/window_executor.cpp index 156623fec..69f536118 100644 --- a/src/duckdb/src/function/window/window_executor.cpp +++ b/src/duckdb/src/function/window/window_executor.cpp @@ -15,18 +15,18 @@ WindowExecutor::WindowExecutor(BoundWindowExpression &wexpr, WindowSharedExpress ? wexpr.OrderBy()[0].expression.get() : nullptr) { if (range_expr) { - range_idx = shared.RegisterCollection(wexpr.OrderByMutable()[0].expression, false); + range_idx = shared.RegisterCollection(wexpr.OrderBy()[0].expression, false); } - boundary_start_idx = shared.RegisterEvaluate(wexpr.StartExprMutable()); - boundary_end_idx = shared.RegisterEvaluate(wexpr.EndExprMutable()); + boundary_start_idx = shared.RegisterEvaluate(wexpr.StartExpr()); + boundary_end_idx = shared.RegisterEvaluate(wexpr.EndExpr()); if (wexpr.WindowFunction()) { if (wexpr.WindowFunction()->HasSharingCallback()) { wexpr.WindowFunction()->GetSharing(*this, shared); } else { // If no one overrides, assume the arguments are only needed at evaluate time - for (auto &child : wexpr.GetChildrenMutable()) { + for (auto &child : wexpr.GetChildren()) { child_idx.emplace_back(shared.RegisterEvaluate(child)); } } diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry.hpp index c931a960a..d6d86dd6f 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry.hpp @@ -74,6 +74,9 @@ class CatalogEntry { virtual void UndoAlter(ClientContext &context, AlterInfo &info); virtual void Rollback(CatalogEntry &prev_entry); virtual void OnDrop(); + //! Whether this version breaks what dependents bound against previous rely on. Previous is any earlier + //! version of this entry, possibly several alters back, so the answer has to hold across a chain of alters + virtual bool InvalidatesDependents(const CatalogEntry &previous) const; virtual unique_ptr Copy(ClientContext &context) const; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/macro_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/macro_catalog_entry.hpp index 6e368156c..3815d641c 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/macro_catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/macro_catalog_entry.hpp @@ -29,6 +29,13 @@ class MacroCatalogEntry : public FunctionEntry { public: unique_ptr GetInfo() const override; + unique_ptr AlterEntry(CatalogTransaction transaction, AlterInfo &info) override; + //! A dependent may have bound any overload, so losing one invalidates it. Overloads are only ever removed by an + //! alter, so a lower count than any earlier version means one was removed in between + bool InvalidatesDependents(const CatalogEntry &previous) const override; + + //! The index of the member a parameter type list names, invalid when none matches + optional_idx FindMember(const vector &signature) const; string ToSQL() const override; }; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_set.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_set.hpp index fabbabee0..ebdcc4bf4 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_set.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_set.hpp @@ -77,7 +77,10 @@ class CatalogSet { DUCKDB_API bool DropEntry(ClientContext &context, const Identifier &name, bool cascade, bool allow_drop_internal = false); //! Verify that the entry referenced by the dependency is still alive - DUCKDB_API void VerifyExistenceOfDependency(transaction_t commit_id, CatalogEntry &entry); + DUCKDB_API void VerifyExistenceOfDependency(transaction_t commit_id, VisibilityBound visibility_bound, + CatalogEntry &entry); + //! Verify that no concurrent dependency creation prevents dropping an entry or one of its members + void VerifyCommitDrop(transaction_t commit_id, VisibilityBound visibility_bound, CatalogEntry &entry); //! Verify we can still drop the entry while committing DUCKDB_API void CommitDrop(transaction_t commit_id, VisibilityBound visibility_bound, CatalogEntry &entry); diff --git a/src/duckdb/src/include/duckdb/catalog/dependency_manager.hpp b/src/duckdb/src/include/duckdb/catalog/dependency_manager.hpp index 536709abf..d62b0e101 100644 --- a/src/duckdb/src/include/duckdb/catalog/dependency_manager.hpp +++ b/src/duckdb/src/include/duckdb/catalog/dependency_manager.hpp @@ -132,7 +132,8 @@ class DependencyManager { catalog_entry_vector_t &order, bool allow_internal); void ReorderEntries(catalog_entry_vector_t &entries, CatalogTransaction transaction, bool allow_internal); void AddObject(CatalogTransaction transaction, CatalogEntry &object, const LogicalDependencyList &dependencies); - void VerifyExistence(CatalogTransaction transaction, DependencyEntry &object); + void VerifyExistence(CatalogTransaction transaction, CatalogTransaction snapshot_transaction, + DependencyEntry &object); void VerifyCommitDrop(CatalogTransaction transaction, VisibilityBound visibility_bound, CatalogEntry &object); //! Returns the objects that should be dropped alongside the object catalog_entry_set_t CheckDropDependencies(CatalogTransaction transaction, CatalogEntry &object, bool cascade); diff --git a/src/duckdb/src/include/duckdb/common/bignum.hpp b/src/duckdb/src/include/duckdb/common/bignum.hpp index c9acf2053..6f565e0f3 100644 --- a/src/duckdb/src/include/duckdb/common/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/bignum.hpp @@ -19,7 +19,7 @@ namespace duckdb { class StringHeap; class ArenaAllocator; -class ClientContext; +class Context; struct bignum_t { string_t data; @@ -49,10 +49,10 @@ enum AbsoluteNumberComparison : uint8_t { //! Per-vector scratch digit buffers and interrupt-check state for BIGNUM multiplication and division struct BignumArithmeticState { - explicit BignumArithmeticState(optional_ptr context = nullptr) : context(context) { + explicit BignumArithmeticState(Context &context_p) : context(context_p) { } - optional_ptr context; + Context &context; //! Digit operations performed since the last interrupt check idx_t work_since_interrupt_check = 0; unsafe_vector lhs_digits; diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 29bb9ce03..1852d5dfd 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -68,6 +68,8 @@ enum class AlterDatabaseType : uint8_t; enum class AlterForeignKeyType : uint8_t; +enum class AlterMacroType : uint8_t; + enum class AlterScalarFunctionType : uint8_t; enum class AlterSchemaType : uint8_t; @@ -478,6 +480,8 @@ enum class PipelineScheduleMode : uint8_t; enum class PipelineScheduleStageType : uint8_t; +enum class PlanningMode : uint8_t; + enum class PragmaType : uint8_t; enum class PreparedParamType : uint8_t; @@ -540,8 +544,6 @@ enum class ResultOrdering : uint8_t; enum class RowGroupAppendMode : uint8_t; -enum class RowIdHandling : uint8_t; - enum class SampleMethod : uint8_t; enum class SampleType : uint8_t; @@ -759,6 +761,9 @@ const char* EnumUtil::ToChars(AlterDatabaseType value); template<> const char* EnumUtil::ToChars(AlterForeignKeyType value); +template<> +const char* EnumUtil::ToChars(AlterMacroType value); + template<> const char* EnumUtil::ToChars(AlterScalarFunctionType value); @@ -1374,6 +1379,9 @@ const char* EnumUtil::ToChars(PipelineScheduleMode value); template<> const char* EnumUtil::ToChars(PipelineScheduleStageType value); +template<> +const char* EnumUtil::ToChars(PlanningMode value); + template<> const char* EnumUtil::ToChars(PragmaType value); @@ -1467,9 +1475,6 @@ const char* EnumUtil::ToChars(ResultOrdering value); template<> const char* EnumUtil::ToChars(RowGroupAppendMode value); -template<> -const char* EnumUtil::ToChars(RowIdHandling value); - template<> const char* EnumUtil::ToChars(SampleMethod value); @@ -1768,6 +1773,9 @@ AlterDatabaseType EnumUtil::FromString(const char *value); template<> AlterForeignKeyType EnumUtil::FromString(const char *value); +template<> +AlterMacroType EnumUtil::FromString(const char *value); + template<> AlterScalarFunctionType EnumUtil::FromString(const char *value); @@ -2383,6 +2391,9 @@ PipelineScheduleMode EnumUtil::FromString(const char *valu template<> PipelineScheduleStageType EnumUtil::FromString(const char *value); +template<> +PlanningMode EnumUtil::FromString(const char *value); + template<> PragmaType EnumUtil::FromString(const char *value); @@ -2476,9 +2487,6 @@ ResultOrdering EnumUtil::FromString(const char *value); template<> RowGroupAppendMode EnumUtil::FromString(const char *value); -template<> -RowIdHandling EnumUtil::FromString(const char *value); - template<> SampleMethod EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/enums/date_part_specifier.hpp b/src/duckdb/src/include/duckdb/common/enums/date_part_specifier.hpp index bac710773..6156c44b3 100644 --- a/src/duckdb/src/include/duckdb/common/enums/date_part_specifier.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/date_part_specifier.hpp @@ -17,6 +17,8 @@ namespace duckdb { +struct string_t; + enum class DatePartSpecifier : uint8_t { // BIGINT values YEAR, @@ -61,5 +63,7 @@ inline bool IsBigintDatepart(DatePartSpecifier part_code) { DUCKDB_API bool TryGetDatePartSpecifier(const string &specifier, DatePartSpecifier &result); DUCKDB_API DatePartSpecifier GetDatePartSpecifier(const string &specifier); +DUCKDB_API bool TryGetDatePartSpecifier(string_t specifier, DatePartSpecifier &result); +DUCKDB_API DatePartSpecifier GetDatePartSpecifier(string_t specifier); } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp b/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp index 5689afa47..097d2bf40 100644 --- a/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp @@ -98,7 +98,6 @@ enum class LogicalOperatorType : uint8_t { // Helpers // ----------------------------- LOGICAL_PREPARE = 175, - LOGICAL_EXECUTE = 176, LOGICAL_EXPORT = 177, LOGICAL_VACUUM = 178, LOGICAL_SET = 179, 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 09320feeb..810a9c374 100644 --- a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp @@ -65,7 +65,8 @@ enum class OptimizerType : uint32_t { REDUNDANT_ORDER = 48, WINDOW_JOIN_PUSHDOWN = 49, SELF_JOIN_AGGREGATE = 50, - SCALAR_AGGREGATE_MERGE = 51 + SCALAR_AGGREGATE_MERGE = 51, + DUPLICATE_ELIMINATED_DOMAIN = 52 }; string OptimizerTypeToString(OptimizerType type); diff --git a/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp b/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp index 8a0fa86e4..cbfab147c 100644 --- a/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp @@ -108,8 +108,8 @@ enum class PhysicalOperatorType : uint8_t { EXPLAIN, EXPLAIN_ANALYZE, EMPTY_RESULT, - EXECUTE, - PREPARE, + // 70 was EXECUTE - keep the values of the operators after it + PREPARE = 71, VACUUM, EXPORT, SET, diff --git a/src/duckdb/src/include/duckdb/common/enums/row_id_handling.hpp b/src/duckdb/src/include/duckdb/common/enums/row_id_handling.hpp deleted file mode 100644 index dd9f7fbe9..000000000 --- a/src/duckdb/src/include/duckdb/common/enums/row_id_handling.hpp +++ /dev/null @@ -1,28 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/common/enums/row_id_handling.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/constants.hpp" -#include "duckdb/common/windows_undefs.hpp" - -namespace duckdb { - -//! How a data-modifying operator handles a target row-id that appears more than once in its input (e.g. an -//! UPDATE ... FROM whose join matches a target row via several source rows). Decouples the duplicate-row-id -//! policy from the SQL syntax that produced it. -enum class RowIdHandling : uint8_t { - //! Row-ids are assumed unique; do not deduplicate (keeps the lock-free path). Used by plain UPDATE. - ASSUME_UNIQUE = 0, - //! Deduplicate row-ids, keeping the first occurrence of each. Used by UPDATE ... FROM. - KEEP_FIRST = 1, - //! Raise a cardinality error when a row-id repeats. (MERGE enforces this at the outer MERGE operator.) - ERROR = 2 -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/error_data.hpp b/src/duckdb/src/include/duckdb/common/error_data.hpp index 6e4ec0917..de3fd0348 100644 --- a/src/duckdb/src/include/duckdb/common/error_data.hpp +++ b/src/duckdb/src/include/duckdb/common/error_data.hpp @@ -48,6 +48,7 @@ class ErrorData { const unordered_map &ExtraInfo() const { return extra_info; } + DUCKDB_API void SetExtraInfo(const string &key, const string &value); DUCKDB_API void FinalizeError(); DUCKDB_API void AddErrorLocation(const string &query); diff --git a/src/duckdb/src/include/duckdb/common/exception.hpp b/src/duckdb/src/include/duckdb/common/exception.hpp index 98dfeb089..58386e8d3 100644 --- a/src/duckdb/src/include/duckdb/common/exception.hpp +++ b/src/duckdb/src/include/duckdb/common/exception.hpp @@ -133,6 +133,8 @@ class Exception : public std::runtime_error { DUCKDB_API static bool InvalidatesTransaction(ExceptionType exception_type); DUCKDB_API static bool InvalidatesDatabase(ExceptionType exception_type); + //! Extra info key naming the attached database that has been invalidated for a fatal error, instead of the instance + static constexpr const char *INVALIDATED_DATABASE_KEY = "invalidated_database"; DUCKDB_API static string ConstructMessageRecursive(const string &msg, std::vector &values); 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 11aa595c4..f7906e738 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 @@ -233,7 +233,7 @@ class TableFunctionUnionData : public BaseUnionData { //! kept afterwards so that the bind that reads the file can reuse what this one read from it shared_ptr bind_data; //! The statistics callback of the wrapped function, which reads the statistics of this file from its bind data - table_statistics_t statistics = nullptr; + table_statistics_extended_t statistics = nullptr; optional_idx TryGetCardinalityEstimate() const override { return cardinality; diff --git a/src/duckdb/src/include/duckdb/common/operator/aggregate_operators.hpp b/src/duckdb/src/include/duckdb/common/operator/aggregate_operators.hpp index 53462d605..f35076f87 100644 --- a/src/duckdb/src/include/duckdb/common/operator/aggregate_operators.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/aggregate_operators.hpp @@ -18,14 +18,14 @@ namespace duckdb { struct Min { template - static inline T Operation(T left, T right) { + static inline T Operation(const T &left, const T &right) { return LessThan::Operation(left, right) ? left : right; } }; struct Max { template - static inline T Operation(T left, T right) { + static inline T Operation(const T &left, const T &right) { return GreaterThan::Operation(left, right) ? left : right; } }; @@ -66,22 +66,22 @@ inline T MaxFloatingPoint(T left, T right) { } template <> -inline float Min::Operation(float left, float right) { +inline float Min::Operation(const float &left, const float &right) { return MinFloatingPoint(left, right); } template <> -inline double Min::Operation(double left, double right) { +inline double Min::Operation(const double &left, const double &right) { return MinFloatingPoint(left, right); } template <> -inline float Max::Operation(float left, float right) { +inline float Max::Operation(const float &left, const float &right) { return MaxFloatingPoint(left, right); } template <> -inline double Max::Operation(double left, double right) { +inline double Max::Operation(const double &left, const double &right) { return MaxFloatingPoint(left, right); } 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 bba4e4a59..8cd08cb11 100644 --- a/src/duckdb/src/include/duckdb/common/owning_string_map.hpp +++ b/src/duckdb/src/include/duckdb/common/owning_string_map.hpp @@ -18,8 +18,9 @@ namespace duckdb { -//! The owning string map is equivalent to string_map_t, except that it manages ownership of all data using the -//! provided allocator +//! The owning string map is equivalent to string_map_t, except that it manages ownership of the keys. +//! Owning maps allocate and free keys through the allocator they are constructed with. Arena-backed maps retain no +//! allocator: inserting calls take the arena of the caller, so a map can be filled from several threads' arenas. template > class OwningStringMap { public: @@ -31,21 +32,30 @@ class OwningStringMap { using const_iterator = typename STRING_MAP_TYPE::const_iterator; public: - explicit OwningStringMap(Allocator &allocator) : allocator(allocator), free_type(AllocatorFreeType::REQUIRES_FREE) { + OwningStringMap() : free_type(AllocatorFreeType::DOES_NOT_REQUIRE_FREE) { } - explicit OwningStringMap(ArenaAllocator &allocator) - : allocator(allocator.GetAllocator()), free_type(AllocatorFreeType::DOES_NOT_REQUIRE_FREE) { + explicit OwningStringMap(Allocator &allocator) + : allocator(&allocator), free_type(AllocatorFreeType::REQUIRES_FREE) { } ~OwningStringMap() { Destroy(); } pair insert(value_type entry) { // NOLINT: match std style + D_ASSERT(allocator); if (entry.first.IsInlined()) { return map.insert(std::move(entry)); - } else { - return map.insert(make_pair(CopyString(entry.first), std::move(entry.second))); } + auto key = CopyString(entry.first, allocator->AllocateData(entry.first.GetSize())); + return map.insert(make_pair(key, std::move(entry.second))); + } + pair insert(value_type entry, ArenaAllocator &arena) { // NOLINT: match std style + D_ASSERT(!allocator); + if (entry.first.IsInlined()) { + return map.insert(std::move(entry)); + } + auto key = CopyString(entry.first, arena.Allocate(entry.first.GetSize())); + return map.insert(make_pair(key, std::move(entry.second))); } std::pair emplace(value_type &&entry) { // NOLINT: match std style auto it = find(entry.first); @@ -54,6 +64,13 @@ class OwningStringMap { } return insert(std::move(entry)); } + std::pair emplace(value_type &&entry, ArenaAllocator &arena) { // NOLINT: match std style + auto it = find(entry.first); + if (it != end()) { + return std::make_pair(it, false); + } + return insert(std::move(entry), arena); + } size_type erase(const key_type &k) { // NOLINT: match std style auto entry = map.find(k); if (entry == map.end()) { @@ -96,50 +113,36 @@ class OwningStringMap { } mapped_type &operator[](const key_type &k) { - return GetOrCreate(k); - } - mapped_type &operator[](key_type &&k) { - return GetOrCreate(std::move(k)); + auto entry = map.find(k); + if (entry != map.end()) { + return entry->second; + } + return insert(make_pair(k, mapped_type())).first->second; } - -private: - inline string_t GetInsertionString(string_t input_str) { - if (input_str.IsInlined()) { - // inlined strings can be inserted directly - return input_str; - } else { - return CopyString(input_str); + mapped_type &GetOrCreate(const key_type &k, ArenaAllocator &arena) { + auto entry = map.find(k); + if (entry != map.end()) { + return entry->second; } + return insert(make_pair(k, mapped_type()), arena).first->second; } - inline string_t CopyString(string_t input_str) { +private: + static string_t CopyString(string_t input_str, data_ptr_t string_memory) { D_ASSERT(!input_str.IsInlined()); - // if the string is not inlined we need to allocate space for it auto input_str_size = UnsafeNumericCast(input_str.GetSize()); - auto string_memory = allocator.AllocateData(input_str_size); - // copy over the string memcpy(string_memory, input_str.GetData(), input_str_size); - // now return the final string_t return string_t(char_ptr_cast(string_memory), input_str_size); } - mapped_type &GetOrCreate(key_type k) { - auto entry = map.find(k); - if (entry != map.end()) { - return entry->second; - } - auto result = insert(make_pair(k, mapped_type())); - return result.first->second; - } - - void DestroyString(const string_t &str) const { + void DestroyString(const string_t &str) { if (free_type != AllocatorFreeType::REQUIRES_FREE) { return; } if (str.IsInlined()) { return; } - allocator.FreeData(data_ptr_cast(str.GetDataWriteable()), str.GetSize()); + allocator->FreeData(data_ptr_cast(str.GetDataWriteable()), str.GetSize()); } void Destroy() { @@ -152,7 +155,8 @@ class OwningStringMap { } private: - Allocator &allocator; + //! Only set for owning maps + optional_ptr allocator; STRING_MAP_TYPE map; AllocatorFreeType free_type; }; 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 1c3281c33..53f0cb8b3 100644 --- a/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp +++ b/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp @@ -125,16 +125,12 @@ class shared_ptr { // NOLINT: invalid case style // Assign from shared_ptr copy shared_ptr &operator=(const shared_ptr &other) noexcept { - if (this == &other) { - return *this; - } - // Create a new shared_ptr using the copy constructor, then swap out the ownership to *this - shared_ptr(other).swap(*this); + internal = other.internal; return *this; } template ::value, int>::type = 0> shared_ptr &operator=(const shared_ptr &other) { - shared_ptr(other).swap(*this); + internal = other.internal; return *this; } diff --git a/src/duckdb/src/include/duckdb/common/string_util.hpp b/src/duckdb/src/include/duckdb/common/string_util.hpp index fdf17a5a7..bbdc9fd84 100644 --- a/src/duckdb/src/include/duckdb/common/string_util.hpp +++ b/src/duckdb/src/include/duckdb/common/string_util.hpp @@ -170,6 +170,10 @@ class StringUtil { return result; } + //! Returns the authority, including any userinfo and port. + //! Empty if there is no scheme:// prefix or authority. Does not validate or decode URI components. + DUCKDB_API static string GetURIAuthority(const string &str); + //! Encode special URL characters in a string DUCKDB_API static string URLEncode(const string &str, bool encode_slash = true); DUCKDB_API static idx_t URLEncodeSize(const char *input, idx_t input_size, bool encode_slash = true); diff --git a/src/duckdb/src/include/duckdb/common/swar.hpp b/src/duckdb/src/include/duckdb/common/swar.hpp index 0d29fd213..de1c4640e 100644 --- a/src/duckdb/src/include/duckdb/common/swar.hpp +++ b/src/duckdb/src/include/duckdb/common/swar.hpp @@ -106,6 +106,15 @@ struct SwarBlock { static constexpr idx_t MIN_PATTERNS = 2; static constexpr idx_t MAX_PATTERNS = 5; + //! Whether any byte of the block has its high bit set, so the block is not all ASCII + static inline bool HasHighBits(const_data_ptr_t block) { + uint64_t bits = 0; + for (idx_t i = 0; i < WORDS; i++) { + bits |= Load(block + i * SwarWord::SIZE); + } + return (bits & 0x8080808080808080ULL) != 0; + } + //! Mask of the bytes matching any pattern plus possibly bytes right above a match, no match is ever missed static inline uint64_t MaybeAnyMask(const_data_ptr_t block, const vector &patterns) { //! We have between 2 (delimiter/newline) and 5 (delimiter,newline,comment,quote,escape) patterns diff --git a/src/duckdb/src/include/duckdb/common/thread.hpp b/src/duckdb/src/include/duckdb/common/thread.hpp index ccf773c5c..ab8884458 100644 --- a/src/duckdb/src/include/duckdb/common/thread.hpp +++ b/src/duckdb/src/include/duckdb/common/thread.hpp @@ -27,10 +27,10 @@ using thread_id = uint64_t; namespace duckdb { -class ClientContext; +class Context; struct ThreadUtil { - static void SleepMs(idx_t ms, optional_ptr context = nullptr); + static void SleepMs(idx_t ms, optional_ptr context = nullptr); static void SleepMicroSeconds(idx_t micros); static thread_id GetThreadId(); static string GetThreadIdString(); diff --git a/src/duckdb/src/include/duckdb/common/tree_renderer.hpp b/src/duckdb/src/include/duckdb/common/tree_renderer.hpp index f7b619588..72f565bbb 100644 --- a/src/duckdb/src/include/duckdb/common/tree_renderer.hpp +++ b/src/duckdb/src/include/duckdb/common/tree_renderer.hpp @@ -67,6 +67,13 @@ class TreeRenderer { virtual void Configure(const unordered_map &settings) { } + //! The "profiling_renderer_settings" of the client, as passed to Configure + static unordered_map GetRendererSettings(ClientContext &context); + //! Overwrites the "profiling_renderer_settings" of the client without validating them + static void SetRendererSettings(ClientContext &context, const unordered_map &settings); + //! Converts renderer settings to the MAP(VARCHAR, VARCHAR) value of the setting, sorted by name + static Value RendererSettingsToValue(const unordered_map &settings); + virtual bool UsesRawKeyNames() { return false; } diff --git a/src/duckdb/src/include/duckdb/common/types.hpp b/src/duckdb/src/include/duckdb/common/types.hpp index c9c1945d0..bcc4da4c8 100644 --- a/src/duckdb/src/include/duckdb/common/types.hpp +++ b/src/duckdb/src/include/duckdb/common/types.hpp @@ -287,8 +287,12 @@ struct LogicalTypeInfo { explicit LogicalTypeInfo(LogicalTypeInfoType type, string alias); virtual ~LogicalTypeInfo(); - // the 1-byte fields and the ref count are declared first so they pack into one word after the vtable pointer - const LogicalTypeInfoType type; +private: + mutable atomic ref_count {0}; + +public: + //! Keep immutable metadata beyond the refcount's 128-byte region. + alignas(128) const LogicalTypeInfoType type; private: friend struct LogicalType; @@ -297,8 +301,6 @@ struct LogicalTypeInfo { PhysicalType physical_type = PhysicalType::INVALID; //! Immortal infos (e.g. the one behind LogicalType::INTEGER) are shared without ref-counting and never freed. bool immortal = false; - //! Atomic intrusive ref-count. This comes after the other members to avoid extra padding. - mutable atomic ref_count {0}; public: string alias; @@ -323,9 +325,11 @@ struct LogicalTypeInfo { if (immortal) { return; } - auto previous = ref_count.fetch_sub(1, std::memory_order_acq_rel); + auto previous = ref_count.fetch_sub(1, std::memory_order_release); D_ASSERT(previous > 0); if (previous == 1) { + // Synchronize with prior releases before destroying the info. + (void)ref_count.load(std::memory_order_acquire); delete this; } } @@ -406,7 +410,7 @@ struct LogicalType { //! look at child types - false for a bare LogicalTypeId::LIST, true for LIST(ANY). DUCKDB_API bool HasParameters() const; - //! Copies the logical type, making a new (unshared) LogicalTypeInfo + //! Copies type info, keeping immortal and enum infos shared. LogicalType Copy() const; bool EqualTypeInfo(const LogicalType &rhs) const; diff --git a/src/duckdb/src/include/duckdb/common/types/conflict_manager.hpp b/src/duckdb/src/include/duckdb/common/types/conflict_manager.hpp index 75450b1b9..5bddf11ac 100644 --- a/src/duckdb/src/include/duckdb/common/types/conflict_manager.hpp +++ b/src/duckdb/src/include/duckdb/common/types/conflict_manager.hpp @@ -11,6 +11,8 @@ #include "duckdb/common/identifier.hpp" #include "duckdb/common/common.hpp" #include "duckdb/common/vector.hpp" +#include "duckdb/common/types/vector.hpp" +#include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/execution/index/art/art.hpp" namespace duckdb { 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 f9edd0bd0..68fa67fb5 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 @@ -65,10 +65,11 @@ inline void VariantBuilderAppendBytes(string &blob, const_data_ptr_t data, idx_t blob.append(const_char_ptr_cast(data), size); } -inline uint32_t VariantBuilderGetOrCreateIndex(OrderedOwningStringMap &dictionary, const string_t &key) { +inline uint32_t VariantBuilderGetOrCreateIndex(OrderedOwningStringMap &dictionary, ArenaAllocator &keys_arena, + const string_t &key) { auto unsorted_idx = dictionary.size(); //! This will later be remapped to the sorted idx (see FinalizeVariantKeys in 'to_variant.cpp') - return dictionary.emplace(std::make_pair(key, unsorted_idx)).first->second; + return dictionary.emplace(std::make_pair(key, unsorted_idx), keys_arena).first->second; } //! The physical storage type of a DECIMAL of the given width (matches VariantDecimalData::GetPhysicalType) @@ -85,7 +86,8 @@ inline PhysicalType VariantDecimalPhysicalType(uint32_t width) { //! Accumulates the canonical representation of a single chunk while traversing the source once. struct VariantBuilder { - explicit VariantBuilder(OrderedOwningStringMap &dictionary) : dictionary(dictionary) { + VariantBuilder(OrderedOwningStringMap &dictionary, ArenaAllocator &keys_arena) + : dictionary(dictionary), keys_arena(keys_arena) { } //! values: (type_id, byte_offset) in pre-order @@ -100,6 +102,8 @@ struct VariantBuilder { string blob; //! maps a key string to its (unsorted) dictionary index, owned by the result's keys vector OrderedOwningStringMap &dictionary; + //! the result's keys arena, the dictionary's keys are allocated in + ArenaAllocator &keys_arena; static constexpr idx_t INIT_NESTING_DEPTH = 8; @@ -153,7 +157,7 @@ struct VariantBuilder { for (idx_t i = 0; i < n; i++) { child_value_ids[block + i] = LocalValue(); child_key_ids[block + i] = LocalKey(); - key_slots.push_back(VariantBuilderGetOrCreateIndex(dictionary, key_fn(i))); + key_slots.push_back(VariantBuilderGetOrCreateIndex(dictionary, keys_arena, key_fn(i))); emit_fn(i); } } @@ -484,7 +488,7 @@ struct VariantBuilder { void AssignObjectChild(idx_t block, idx_t i, string_t key) { child_value_ids[block + i] = LocalValue(); child_key_ids[block + i] = LocalKey(); - key_slots.push_back(VariantBuilderGetOrCreateIndex(dictionary, key)); + key_slots.push_back(VariantBuilderGetOrCreateIndex(dictionary, keys_arena, key)); } void AssignArrayChild(idx_t block, idx_t i) { @@ -629,8 +633,8 @@ void BuildVariant(SOURCE &source, idx_t count, Vector &result) { //! The dictionary is backed by the keys vector's string allocator so the finalized keys are owned //! by the result (see FinalizeVariantKeys). - OrderedOwningStringMap dictionary(StringVector::GetStringAllocator(keys_entry)); - VariantBuilder builder(dictionary); + OrderedOwningStringMap dictionary; + VariantBuilder builder(dictionary, StringVector::GetStringAllocator(keys_entry)); vector keys_entries(count); vector children_entries(count); diff --git a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp index 2024c1a3d..f3a6a1e0f 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp @@ -328,6 +328,12 @@ class VariantObjectIterator { return Iterator(*this, EndPos()); } + //! The entries sorted by key, only for LEXICOGRAPHIC order + const vector &GetOrderedEntries() const { + D_ASSERT(order == VariantIterationOrder::LEXICOGRAPHIC); + return ordered_entries; + } + private: //! Materializes the entry at the given raw position (before missing-field skipping) VariantObjectEntry RawEntry(idx_t raw_pos) const; diff --git a/src/duckdb/src/include/duckdb/common/types/vector.hpp b/src/duckdb/src/include/duckdb/common/types/vector.hpp index 060ce2932..cf53f3f5b 100644 --- a/src/duckdb/src/include/duckdb/common/types/vector.hpp +++ b/src/duckdb/src/include/duckdb/common/types/vector.hpp @@ -197,7 +197,10 @@ class Vector { inline const buffer_ptr &GetBufferRef() const { return buffer; } - void SetBuffer(buffer_ptr buffer_p) { + void SetBuffer(const buffer_ptr &buffer_p) { + buffer = buffer_p; + } + void SetBuffer(buffer_ptr &&buffer_p) { buffer = std::move(buffer_p); } diff --git a/src/duckdb/src/include/duckdb/common/weak_ptr_ipp.hpp b/src/duckdb/src/include/duckdb/common/weak_ptr_ipp.hpp index 2b6dad864..e8feac928 100644 --- a/src/duckdb/src/include/duckdb/common/weak_ptr_ipp.hpp +++ b/src/duckdb/src/include/duckdb/common/weak_ptr_ipp.hpp @@ -61,6 +61,14 @@ class weak_ptr { // NOLINT: invalid case style return *this; } + weak_ptr &operator=(weak_ptr &&other) noexcept { + if (this == &other) { + return *this; + } + internal = std::move(other.internal); + return *this; + } + template ::value, int>::type = 0> weak_ptr &operator=(const shared_ptr &ptr) { internal = ptr.internal; diff --git a/src/duckdb/src/include/duckdb/execution/executor.hpp b/src/duckdb/src/include/duckdb/execution/executor.hpp index 4b7271752..e743bda9c 100644 --- a/src/duckdb/src/include/duckdb/execution/executor.hpp +++ b/src/duckdb/src/include/duckdb/execution/executor.hpp @@ -153,6 +153,8 @@ class Executor { //! Whether this query's store can park a producer for the consumer at all. A store settled on //! retained never parks, so the retained hot path skips the readiness checks bool ResultStoreCanPark(); + //! The chunks a task slice run by ExecuteTask processes before control returns to the caller + idx_t PartialChunkCount(); void InitializeInternal(PhysicalOperator &physical_plan); void ScheduleEvents(const vector> &meta_pipelines, diff --git a/src/duckdb/src/include/duckdb/execution/expression_executor.hpp b/src/duckdb/src/include/duckdb/execution/expression_executor.hpp index e06aee6c9..94a464d72 100644 --- a/src/duckdb/src/include/duckdb/execution/expression_executor.hpp +++ b/src/duckdb/src/include/duckdb/execution/expression_executor.hpp @@ -17,6 +17,8 @@ namespace duckdb { class Allocator; class ClientContext; +class Context; +class DatabaseInstance; class ExecutionContext; //! ExpressionExecutor is responsible for executing a set of expressions and storing the result in a data chunk @@ -24,10 +26,18 @@ class ExpressionExecutor { friend class BoundIndex; public: + DUCKDB_API explicit ExpressionExecutor(Context &context); + DUCKDB_API ExpressionExecutor(Context &context, const Expression *expression); + DUCKDB_API ExpressionExecutor(Context &context, const Expression &expression); + DUCKDB_API ExpressionExecutor(Context &context, const vector> &expressions); DUCKDB_API explicit ExpressionExecutor(ClientContext &context); DUCKDB_API ExpressionExecutor(ClientContext &context, const Expression *expression); DUCKDB_API ExpressionExecutor(ClientContext &context, const Expression &expression); DUCKDB_API ExpressionExecutor(ClientContext &context, const vector> &expressions); + //! Creates an executor with database-wide services only (no client context) + DUCKDB_API explicit ExpressionExecutor(DatabaseInstance &db); + DUCKDB_API ExpressionExecutor(DatabaseInstance &db, const Expression &expression); + DUCKDB_API ExpressionExecutor(DatabaseInstance &db, const vector> &expressions); ExpressionExecutor(ExpressionExecutor &&) = delete; //! The expressions of the executor @@ -37,9 +47,12 @@ class ExpressionExecutor { DataChunk *chunk = nullptr; public: - bool HasContext(); - ClientContext &GetContext(); - optional_ptr GetContextPtr(); + Context &GetContext(); + //! Whether or not the executor runs in the context of a client + bool HasClientContext(); + //! The client context - throws if the executor has no client context + ClientContext &GetClientContext(); + optional_ptr TryGetClientContext(); Allocator &GetAllocator(); //! Add an expression to the set of to-be-executed expressions of the executor @@ -79,9 +92,11 @@ class ExpressionExecutor { //! Execute the expression with index `expr_idx` on the rows in 'sel'; the result holds those 'count' rows DUCKDB_API void ExecuteExpression(idx_t expr_idx, Vector &result, const SelectionVector &sel, idx_t count); //! Evaluate a scalar expression and fold it into a single value + DUCKDB_API static Value EvaluateScalar(Context &context, const Expression &expr, bool allow_unfoldable = false); DUCKDB_API static Value EvaluateScalar(ClientContext &context, const Expression &expr, bool allow_unfoldable = false); //! Try to evaluate a scalar expression and fold it into a single value, returns false if an exception is thrown + DUCKDB_API static bool TryEvaluateScalar(Context &context, const Expression &expr, Value &result); DUCKDB_API static bool TryEvaluateScalar(ClientContext &context, const Expression &expr, Value &result); //! Initialize the state of a given expression @@ -160,16 +175,10 @@ class ExpressionExecutor { void FillSwitch(const Vector &vector, Vector &result, const SelectionVector &sel, sel_t count); private: - //! Client context - optional_ptr context; + Context &context; //! The states of the expression executor; this holds any intermediates and temporary states of expressions vector> states; //! The vector verification (debug setting) DebugVectorVerification debug_vector_verification = DebugVectorVerification::NONE; - -private: - // it is possible to create an expression executor without a ClientContext - but it should be avoided - DUCKDB_API ExpressionExecutor(); - DUCKDB_API explicit ExpressionExecutor(const vector> &exprs); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/expression_executor_state.hpp b/src/duckdb/src/include/duckdb/execution/expression_executor_state.hpp index 07a4651b3..904b7ef3a 100644 --- a/src/duckdb/src/include/duckdb/execution/expression_executor_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/expression_executor_state.hpp @@ -37,8 +37,10 @@ struct ExpressionState { void AddChild(const Expression &child_expr); void Finalize(); Allocator &GetAllocator(); - bool HasContext(); - DUCKDB_API ClientContext &GetContext(); + DUCKDB_API Context &GetContext(); + bool HasClientContext(); + //! The client context - throws if the expression is executed without a client context + DUCKDB_API ClientContext &GetClientContext(); void Verify(ExpressionExecutorState &root); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp index 40a987c36..cbd4b1d0a 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp @@ -74,7 +74,7 @@ class ARTOperator { return current_ptr.GetRowId() == rowid.GetRowId(); } case NType::LEAF: { - throw InternalException("Invalid node type (LEAF) for ARTOperator::NestedLookup."); + throw InternalException("Invalid node type (LEAF) for ARTOperator::LookupInLeaf."); } case NType::NODE_7_LEAF: case NType::NODE_15_LEAF: @@ -99,16 +99,21 @@ class ARTOperator { return false; } case NType::PREFIX: { - Prefix prefix(art, current_ptr); - for (idx_t i = 0; i < prefix.data[art.PrefixCount()]; i++) { - if (prefix.data[i] != rowid[depth]) { + ConstNodeHandle handle(art, current_ptr); + auto data = handle.GetPtr(); + NodePtr child_ptr = ConstPrefixHandle::ChildRef(art, handle); + for (idx_t i = 0; i < data[art.PrefixCount()]; i++) { + if (data[i] != rowid[depth]) { // The key and the prefix don't match. return false; } depth++; } - current_ptr = *prefix.child_slot; + current_ptr = child_ptr; + break; } + default: + throw InternalException("Invalid node type for ARTOperator::LookupInLeaf: %d.", type); } } return false; @@ -248,14 +253,19 @@ class ARTOperator { //! Delete a key and its row ID. //! Assumes that deletion starts at the root of the tree. + //! The caller must keep the storage containing node_ptr valid for the duration of the call. static bool Delete(ART &art, NodePtr &node_ptr, const ARTKey &key, const ARTKey &row_id) { // If we need to compress a Node4 into a one-way node, // then we need the previous prefix before the Node4. + // The four handles form a fixed-size window: pins never accumulate with the depth of the descent. + // parent and current start at the root, which no node stores, so their handles are unpinned. + // At a root Node4, DeleteChild thus receives the Node4's own NodePtr as parent_ptr. + // empty_ptr is never read: that would require the root to be an inlined leaf. NodePtr empty_ptr; - reference great_grandparent_ptr_ref(empty_ptr); - reference grandparent_ptr_ref(empty_ptr); - reference parent_ptr_ref(node_ptr); - reference current_ptr_ref(node_ptr); + auto great_grandparent = NodePtrHandle::Unpinned(empty_ptr); + auto grandparent = NodePtrHandle::Unpinned(empty_ptr); + auto parent = NodePtrHandle::Unpinned(node_ptr); + auto current = NodePtrHandle::Unpinned(node_ptr); reference current_key_ref(key); idx_t grandparent_depth = 0; @@ -264,62 +274,80 @@ class ARTOperator { auto status = GateStatus::GATE_NOT_SET; auto passed_internal_node = false; - while (current_ptr_ref.get().HasMetadata()) { + // Moves the window one level down: each level takes the handle of the level below it, so current becomes the + // parent and the great-grandparent's pin is dropped. current is left empty; the caller sets it to a child. + auto move_window_down = [&]() { + great_grandparent = std::move(grandparent); + grandparent = std::move(parent); + parent = std::move(current); + grandparent_depth = parent_depth; + parent_depth = depth; + }; + + while (current.Get().HasMetadata()) { // Enter gate. - if (status == GateStatus::GATE_NOT_SET && current_ptr_ref.get().GetGateStatus() == GateStatus::GATE_SET) { + if (status == GateStatus::GATE_NOT_SET && current.Get().GetGateStatus() == GateStatus::GATE_SET) { status = GateStatus::GATE_SET; current_key_ref = row_id; depth = 0; continue; } - const auto type = current_ptr_ref.get().GetType(); + const auto type = current.Get().GetType(); switch (type) { case NType::LEAF_INLINED: { - if (current_ptr_ref.get().GetRowId() != row_id.GetRowId()) { + if (current.Get().GetRowId() != row_id.GetRowId()) { return false; } - if (!passed_internal_node && parent_ptr_ref.get().GetType() == NType::PREFIX) { + if (!passed_internal_node && parent.Get().GetType() == NType::PREFIX) { // The tree contains exactly one element with a prefix. - NodePtr::FreeTree(art, parent_ptr_ref); + // The freed chain stores the current NodePtr: release its pin first. + current.Release(); + NodePtr::FreeTree(art, parent.Get()); return true; } - if (parent_ptr_ref.get().GetType() == NType::PREFIX) { + if (parent.Get().GetType() == NType::PREFIX) { // We might have to compress: // PREFIX (greatgrandparent) - Node4 (grandparent) - PREFIX - INLINED_LEAF. // The parent does not have to be passed in, as it is a child of the possibly being compressed N4. // Then, when we delete that child, we also free it. - NodePtr::DeleteChild(art, grandparent_ptr_ref, great_grandparent_ptr_ref, + // DeleteChild frees the parent chain, and may free the grandparent node by compressing or + // shrinking it: release their pins first. + current.Release(); + parent.Release(); + NodePtr::DeleteChild(art, std::move(grandparent), great_grandparent.Get(), current_key_ref.get()[grandparent_depth], status, row_id); return true; } - NodePtr::DeleteChild(art, parent_ptr_ref, grandparent_ptr_ref, current_key_ref.get()[parent_depth], + // Compressing or shrinking the parent node frees the node pinned by current: release it first. + current.Release(); + NodePtr::DeleteChild(art, std::move(parent), grandparent.Get(), current_key_ref.get()[parent_depth], status, row_id); return true; } case NType::LEAF: { D_ASSERT(status == GateStatus::GATE_NOT_SET); - Leaf::TransformToNested(art, current_ptr_ref); + Leaf::TransformToNested(art, current.Get()); break; } case NType::PREFIX: { - great_grandparent_ptr_ref = grandparent_ptr_ref; - grandparent_ptr_ref = parent_ptr_ref; - parent_ptr_ref = current_ptr_ref; - grandparent_depth = parent_depth; - parent_depth = depth; - - // Traverse a prefix chain until the next non-prefix node or gate. - while (current_ptr_ref.get().GetType() == NType::PREFIX) { - Prefix prefix(art, current_ptr_ref, true); - for (idx_t i = 0; i < prefix.data[art.PrefixCount()]; i++) { - if (prefix.data[i] != current_key_ref.get()[depth]) { + move_window_down(); + + // Traverse a prefix chain until the next non-prefix node or gate, + // releasing each prefix node's pin once the next one is pinned. + NodePtr prefix_ptr = parent.Get(); + while (prefix_ptr.GetType() == NType::PREFIX) { + NodeHandle prefix_handle(art, prefix_ptr); + auto data = prefix_handle.GetPtr(); + for (idx_t i = 0; i < data[art.PrefixCount()]; i++) { + if (data[i] != current_key_ref.get()[depth]) { return false; } depth++; } - current_ptr_ref = *prefix.child_slot; - if (current_ptr_ref.get().GetGateStatus() == GateStatus::GATE_SET) { + current = NodePtrHandle::PrefixChild(art, std::move(prefix_handle)); + prefix_ptr = current.Get(); + if (prefix_ptr.GetGateStatus() == GateStatus::GATE_SET) { break; } } @@ -330,19 +358,16 @@ class ARTOperator { case NType::NODE_48: case NType::NODE_256: { passed_internal_node = true; - great_grandparent_ptr_ref = grandparent_ptr_ref; - grandparent_ptr_ref = parent_ptr_ref; - parent_ptr_ref = current_ptr_ref; - grandparent_depth = parent_depth; - parent_depth = depth; - - auto child_ptr_ref = current_ptr_ref.get().GetChildMutableUnsafe(art, current_key_ref.get()[depth]); - if (!child_ptr_ref) { + move_window_down(); + + auto child_ptr_handle = + NodePtrHandle::Child(NodeHandle(art, parent.Get()), current_key_ref.get()[depth]); + if (!child_ptr_handle) { // No child at the byte: nothing to erase. return false; } - current_ptr_ref = *child_ptr_ref; + current = std::move(*child_ptr_handle); depth++; break; } @@ -350,8 +375,8 @@ class ARTOperator { case NType::NODE_15_LEAF: case NType::NODE_256_LEAF: { const auto byte = current_key_ref.get()[depth]; - if (current_ptr_ref.get().HasByte(art, byte)) { - NodePtr::DeleteChild(art, current_ptr_ref, parent_ptr_ref, byte, status, row_id); + if (current.Get().HasByte(art, byte)) { + NodePtr::DeleteChild(art, std::move(current), parent.Get(), byte, status, row_id); return true; } return false; diff --git a/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp b/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp index 3cb0e5dd8..85e7c03a4 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp @@ -90,7 +90,8 @@ class Node7Leaf : public BaseLeaf<7, NType::NODE_7_LEAF> { //! Insert a byte. static void InsertByte(ART &art, NodePtr &node_ptr, const uint8_t byte); //! Delete a byte. - static void DeleteByte(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const uint8_t byte, const ARTKey &row_id); + static void DeleteByte(ART &art, NodePtrHandle node_ptr_handle, NodePtr &parent_ptr, const uint8_t byte, + const ARTKey &row_id); private: static void ShrinkNode15Leaf(ART &art, NodePtr &node7_leaf_ptr, NodePtr &node15_leaf_ptr); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp b/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp index 85a632c01..715a66762 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp @@ -169,7 +169,7 @@ class Node4 : public BaseNode<4, NType::NODE_4> { //! Insert a child at byte. static void InsertChild(ART &art, NodePtr &node_ptr, const uint8_t byte, const NodePtr child_ptr); //! Delete the child at byte. - static void DeleteChild(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const uint8_t byte, + static void DeleteChild(ART &art, NodePtrHandle node_ptr_handle, NodePtr &parent_ptr, const uint8_t byte, const GateStatus status); private: diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp index 439ef8463..c225d6fef 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp @@ -145,8 +145,12 @@ class NodePtr : public IndexPointer { void ReplaceChild(const ART &art, const uint8_t byte, const NodePtr child_ptr = NodePtr()) const; //! Insert the child at byte. static void InsertChild(ART &art, NodePtr &node_ptr, const uint8_t byte, const NodePtr child_ptr = NodePtr()); - //! Delete the child at byte. - static void DeleteChild(ART &art, NodePtr &node_ptr, NodePtr &parent_ptr, const uint8_t byte, + //! Delete the child at byte of the node that node_ptr_handle's NodePtr points to. + //! Takes over node_ptr_handle's pin and releases it before freeing the node that stores its NodePtr. + //! The caller must keep the storage containing parent_ptr valid for the duration of the call, + //! and must hold no other pins on nodes below parent_ptr, which this call may free. + //! At the root, parent_ptr is node_ptr_handle's NodePtr itself. + static void DeleteChild(ART &art, NodePtrHandle node_ptr_handle, NodePtr &parent_ptr, const uint8_t byte, const GateStatus status, const ARTKey &row_id); //! Get the child node at byte, if it exists. diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp index 50cc17942..4fa9e7a6a 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp @@ -10,6 +10,8 @@ #include "duckdb/common/assert.hpp" #include "duckdb/common/helper.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/optional_ptr.hpp" #include "duckdb/execution/index/fixed_size_allocator.hpp" #include "duckdb/execution/index/fixed_size_buffer.hpp" @@ -84,4 +86,42 @@ class ConstNodeHandle { NType type; }; +//! NodePtrHandle refers to a mutable NodePtr and owns the pin on the node storing it. +//! NodeHandle pins the node that a NodePtr points to; NodePtrHandle pins the node that contains the NodePtr. +//! Use it only to pass a NodePtr to a callee that may free the node storing it, as in Delete: the callee releases +//! the pin before that free. Otherwise, keep a NodeHandle in scope and use a NodePtr reference, as Insert does. +//! Only ARTOperator can create an unpinned NodePtrHandle, for a NodePtr that no node stores, e.g., the ART root. +class NodePtrHandle { + friend class ARTOperator; + +public: + NodePtrHandle(const NodePtrHandle &) = delete; + NodePtrHandle &operator=(const NodePtrHandle &) = delete; + NodePtrHandle(NodePtrHandle &&other) noexcept; + NodePtrHandle &operator=(NodePtrHandle &&other) noexcept; + +public: + //! Refers to the child NodePtr of the pinned prefix. + static NodePtrHandle PrefixChild(const ART &art, NodeHandle &&prefix_handle); + //! Refers to the NodePtr of the child at byte in the pinned inner node, if it exists. + static optional Child(NodeHandle &&node_handle, const uint8_t byte); + + //! The reference is valid until the handle is released, moved from, or destroyed. + NodePtr &Get(); + //! Releases the pin. Afterwards, the handle no longer refers to a NodePtr. + void Release(); + //! Moves the pin out of a pinned handle and releases the handle. + NodeHandle TakePin() &&; + +private: + //! Refers to a NodePtr that no node stores. The caller keeps its storage valid. + static NodePtrHandle Unpinned(NodePtr &node_ptr); + + NodePtrHandle(NodePtr &node_ptr_p, optional handle_p); + +private: + optional_ptr node_ptr; + optional handle; +}; + } // namespace duckdb 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 4789125b1..ed65a1279 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp @@ -44,10 +44,6 @@ class Prefix { //! 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); - //! Concatenates parent -> prev_node4 -> child. - static void Concat(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, uint8_t byte, - const GateStatus node4_status, const GateStatus status); - //! 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); @@ -56,33 +52,8 @@ class Prefix { static Prefix NewInternal(ART &art, NodePtr &node_ptr, const data_ptr_t data, const uint8_t count, const idx_t offset); - static Prefix GetTail(ART &art, const NodePtr &node_ptr); - - static void ConcatInternal(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, uint8_t byte, - const GateStatus status); - static void ConcatNode4WasGate(ART &art, NodePtr &node4_ptr, const NodePtr child_ptr, uint8_t byte); - static void ConcatChildIsGate(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, - uint8_t byte); - static void ConcatOutsideGate(ART &art, NodePtr &parent_ptr, NodePtr &node4_ptr, const NodePtr child_ptr, - uint8_t byte); - Prefix Append(ART &art, const uint8_t byte); void Append(ART &art, NodePtr other_ptr); Prefix TransformToDeprecatedAppend(ART &art, FixedSizeAllocator &allocator, uint8_t byte); - -private: - template - static void Iterator(ART &art, reference &node_ptr_ref, const bool exit_gate, const bool is_mutable, - F &&lambda) { - while (node_ptr_ref.get().HasMetadata() && node_ptr_ref.get().GetType() == PREFIX) { - Prefix prefix(art, node_ptr_ref, is_mutable); - lambda(prefix); - - node_ptr_ref = *prefix.child_slot; - if (exit_gate && node_ptr_ref.get().GetGateStatus() == GateStatus::GATE_SET) { - break; - } - } - } }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp b/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp index f002ec911..7e39700de 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp @@ -46,6 +46,15 @@ class PrefixHandle { //! is handled internally; the caller does not need to set it after splitting. static NodePtr Split(ART &art, NodePtr &prefix_ptr, NodePtr &branching_node4_ptr, const uint8_t pos); + //! Replaces a freed Node4 that had one remaining child: concatenates parent -> byte -> child. + //! parent_ptr points to the inner node above the Node4, or to the head of the prefix chain ending at the Node4. + //! node4_ptr_handle refers to the NodePtr that pointed to the freed Node4, which FreeNode cleared. + //! It pins the node storing that NodePtr: the inner node above the Node4, or the tail of parent_ptr's + //! prefix chain. At the root, it is unpinned, and parent_ptr is that same cleared NodePtr, so it is not a PREFIX. + //! node4_status is the Node4's gate status, and status is GATE_SET if the Node4 is the gate or inside one. + static void Concat(ART &art, NodePtr &parent_ptr, NodePtrHandle node4_ptr_handle, const NodePtr child_ptr, + const uint8_t byte, const GateStatus node4_status, const GateStatus status); + //! Create a new deprecated prefix node and return a handle to it. static NodeHandle NewDeprecated(FixedSizeAllocator &allocator, NodePtr &node_ptr); diff --git a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp index 7e4bb7749..90aefed24 100644 --- a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp @@ -19,6 +19,7 @@ #include "duckdb/common/types/row/tuple_data_layout.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/unique_ptr.hpp" +#include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/execution/ht_entry.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" @@ -33,15 +34,41 @@ 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 { +public: + explicit DictionaryOwnershipCache(idx_t column_count) : column_count(column_count) { + } + + const buffer_ptr &GetEntry(idx_t column, const buffer_ptr &entry); + void Reset(); + +private: + struct DictionaryOwner { + explicit DictionaryOwner(const buffer_ptr &entry) : entry(entry) { + } + + buffer_ptr entry; + }; + + const idx_t column_count; + //! Allocated once on first use; resetting owners does not invalidate references to these slots. + unique_array> entries; +}; struct JoinHTScanState { public: JoinHTScanState(TupleDataCollection &collection, idx_t chunk_idx_from, idx_t chunk_idx_to, + idx_t output_column_count, TupleDataPinProperties properties = TupleDataPinProperties::ALREADY_PINNED) - : iterator(collection, properties, chunk_idx_from, chunk_idx_to, false), offset_in_chunk(0), chunks_done(0) { + : iterator(collection, properties, chunk_idx_from, chunk_idx_to, false), + dictionary_gather_state(output_column_count), offset_in_chunk(0), chunks_done(0) { } TupleDataChunkIterator iterator; + DictionaryOwnershipCache dictionary_gather_state; idx_t offset_in_chunk; //! The number of chunks that have been scanned entirely idx_t chunks_done; @@ -118,6 +145,8 @@ struct DictSurvivingInfo { class JoinHashTable { public: using ValidityBytes = TemplatedValidityMask; + //! Prefix-range filter build states, indexed by key column + using PrefixRangeBuildStates = vector>; struct ResidualPredicateProbeState { //! Evaluation chunk @@ -155,6 +184,8 @@ class JoinHashTable { SelectionVector sel_vector; SelectionVector chain_match_sel_vector; SelectionVector chain_no_match_sel_vector; + //! Direct columnar lookup produces dictionary positions instead of row pointers. + unique_ptr dictionary_selection; // whether or not the given tuple has found a match unsafe_unique_array found_match; @@ -173,6 +204,7 @@ class JoinHashTable { // Thread-local probe match count, flushed when the current chunk's pointer scan is exhausted. idx_t local_probe_matches = 0; + DictionaryOwnershipCache dictionary_gather_state; explicit ScanStructure(JoinHashTable &ht, TupleDataChunkState &key_state); void Reset(); @@ -184,8 +216,11 @@ class JoinHashTable { void FlushProbeMatches(); private: + void ProjectProbeColumns(DataChunk &probe_data, const SelectionVector &sel, idx_t count, DataChunk &result, + bool full_identity); //! Next operator for the inner join void NextInnerJoin(DataChunk &keys, DataChunk &probe_data, DataChunk &result); + void NextDictionaryJoin(DataChunk &probe_data, DataChunk &result); void NextSemiJoin(DataChunk &keys, DataChunk &probe_data, DataChunk &result); void NextAntiJoin(DataChunk &keys, DataChunk &probe_data, DataChunk &result); void NextRightSemiOrAntiJoin(DataChunk &keys, DataChunk &probe_data); @@ -244,7 +279,6 @@ class JoinHashTable { string dictionary_id; DataChunk unique_values; TupleDataChunkState unique_key_state; - Vector hashes; Vector new_dictionary_pointers; SelectionVector unique_entries; //! Per-slot head-of-chain pointer cache; nullptr marks a miss @@ -259,6 +293,7 @@ class JoinHashTable { struct ProbeState : SharedState { ProbeState(); + Vector hashes; Vector ht_offsets_and_salts_v; Vector hashes_dense_v; SelectionVector non_empty_sel; @@ -329,7 +364,7 @@ class JoinHashTable { //! Finalize must be called before any call to Probe, and after Finalize is called Build should no longer be //! ever called. void Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool parallel, - optional_ptr prefix_range_state = nullptr, + optional_ptr prefix_range_states = nullptr, bool prefix_range_parallel = false); //! Probe the HT with the given input chunk, resulting in the given result void Probe(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state, @@ -346,17 +381,18 @@ class JoinHashTable { //! Fill the pointer with all the addresses from the hashtable for full scan static idx_t FillWithHTOffsets(JoinHTScanState &state, Vector &addresses); - //! Pre-materialize RHS output columns into dict_arrays and embed the dict index into NEXT_PTR; - //! called once from HashJoinFinalizeEvent::FinishEvent, after all finalize tasks have completed. + //! Materialize RHS dictionaries after all finalize tasks complete. void BuildDictionaryArrays(const PhysicalHashJoin &op); - //! Emit dictionary vectors for row_ptrs[ptr_sel[0..count)]; pass - //! *FlatVector::IncrementalSelectionVector() when row_ptrs is already compacted + //! 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) const; + 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) const; + 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 { @@ -400,6 +436,11 @@ class JoinHashTable { return null_values_are_equal[col_idx]; } + //! Choose direct lookup from the completed in-memory build. + bool TryInitializePerfectHashTable(); + //! Whether lookup produces row pointers for compressed-probe fan-out. + bool SupportsCompressedProbe() const; + ClientContext &context; const PhysicalOperator &op; //! BufferManager @@ -439,7 +480,7 @@ class JoinHashTable { //! If there is more than one element in the chain, we need to scan the next elements of the chain atomic chains_longer_than_one {false}; - //! The capacity of the HT. Is the same as hash_map.GetSize() / sizeof(ht_entry_t) + //! 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; @@ -513,6 +554,11 @@ class JoinHashTable { optional_ptr ¤t_sel); void Hash(DataChunk &keys, const SelectionVector &sel, idx_t count, Vector &hashes); + bool TryProbePerfectHashTable(ScanStructure &scan_structure, DataChunk &keys); + bool CanUsePerfectDictionaryLookup() const; + bool UsesDictionaryLookup() const; + void AllocateHashMap(bool use_radix_layout); + //! Dictionary-aware variant of Probe. Returns false if the LHS keys are not dictionary-eligible. bool TryProbeDictionary(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state); @@ -522,11 +568,10 @@ class JoinHashTable { bool UseSalt() const; - //! Gets a pointer to the entry in the HT for each of the hashes_v using linear probing. Will update the - //! key_match_sel vector and the count argument to the number and position of the matches - void GetRowPointers(DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, Vector &hashes_v, - optional_ptr sel, idx_t &count, Vector &pointers_result_v, - SelectionVector &match_sel, bool has_sel); + //! Resolve keys to equality-group heads and return their probe positions in match_sel. + void GetRowPointers(DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, + optional_ptr precomputed_hashes, optional_ptr sel, idx_t &count, + Vector &pointers_result_v, SelectionVector &match_sel, bool has_sel); private: //! Insert the given set of locations into the HT with the given set of hashes_v @@ -551,6 +596,11 @@ class JoinHashTable { //! The DataCollection holding the main data of the hash table unique_ptr data_collection; + //! Bounds collected during sink, before choosing the lookup representation. + unique_ptr perfect_hash_candidate; + //! An allocated direct lookup, published only after in-memory finalize chooses it. + unique_ptr perfect_hash_table; + //! The hash map of the HT, created after finalization HugeAllocation hash_map; //! Shift to align fully resident buckets with radix partitions; zero selects the external/low-bit layout. @@ -570,7 +620,14 @@ class JoinHashTable { //! Whether finalize should build the bloom filter from the materialized build side bool should_build_bloom_filter = false; - unique_ptr prefix_range_filter; + //! 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(); + + //! Prefix-range filters, indexed by key column + vector> prefix_range_filters; bool should_build_prefix_range_filter = false; //! Copying not allowed @@ -653,14 +710,20 @@ class JoinHashTable { void SetBloomFilter(shared_ptr filter) { bloom_filter = std::move(filter); } - //! Requests a filter built during finalize, from the materialized build side (in-memory joins only) - void SetBuildBloomFilter(const bool should_build) { - this->should_build_bloom_filter = should_build; + //! 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; + } + //! 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; } shared_ptr GetBloomFilter() { return bloom_filter; } + shared_ptr GetBloomFilter(idx_t key_idx); //! 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 @@ -668,38 +731,36 @@ class JoinHashTable { recycled_bloom_filter = std::move(filter); } //! Marks the bloom filter complete. The reference stays, because the thread-local tables hold it too - void SealBloomFilter() { - if (bloom_filter) { - bloom_filter->Seal(context); - } - } + void SealBloomFilter(); //! 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(unique_ptr filter) { - prefix_range_filter = std::move(filter); + void SetPrefixRangeFilter(idx_t key_idx, unique_ptr filter) { + D_ASSERT(key_idx < equality_predicate_columns.size()); + prefix_range_filters.resize(equality_predicate_columns.size()); + prefix_range_filters[key_idx] = std::move(filter); } void SetBuildPrefixRangeFilter() { should_build_prefix_range_filter = true; } - optional_ptr GetPrefixRangeFilter() { - return prefix_range_filter; + optional_ptr GetPrefixRangeFilter(idx_t key_idx) { + if (key_idx >= prefix_range_filters.size()) { + return nullptr; + } + return prefix_range_filters[key_idx].get(); } - bool ShouldBuildPrefixRangeFilter() const { - return should_build_prefix_range_filter && prefix_range_filter; - } + bool ShouldBuildPrefixRangeFilter() const; - void BuildPrefixRangeFilter(); - unique_ptr InitializePrefixRangeBuildState(); + //! One build state per key column with a prefix-range filter, null for the other key columns + PrefixRangeBuildStates InitializePrefixRangeBuildState(); idx_t GetPrefixRangeBuildStateSize() const; - void InsertPrefixRangeChunk(TupleDataChunkState &chunk_state, idx_t count, PrefixRangeFilter::BuildState &state, - bool parallel = false); - void MergePrefixRangeBuildState(PrefixRangeFilter::BuildState &state); + void MergePrefixRangeBuildState(PrefixRangeBuildStates &states); //! Get total size of HT if all partitions would be built idx_t GetTotalSize(const vector> &local_hts, idx_t &max_partition_size, @@ -736,6 +797,19 @@ class JoinHashTable { ProbeSpillLocalAppendState &spill_state, DataChunk &spill_chunk); private: + //! Buffers reused across chunks to fill the per-key-column filters + struct KeyFilterBuildScratch { + explicit KeyFilterBuildScratch(JoinHashTable &ht); + DataChunk keys; + Vector hashes; + }; + //! Gathers one key column of a chunk of materialized rows + void GatherKeyColumn(TupleDataChunkState &chunk_state, idx_t count, idx_t key_idx, Vector &result); + void InsertPrefixRangeChunk(TupleDataChunkState &chunk_state, idx_t count, PrefixRangeBuildStates &states, + KeyFilterBuildScratch &scratch, bool parallel); + //! Inserts a chunk into the per-key-column bloom filters + void InsertKeyBloomFilterChunk(TupleDataChunkState &chunk_state, idx_t count, KeyFilterBuildScratch &scratch); + //! True iff the residual predicate (if any) reads build payload column build_col_idx from its row slot bool ColumnReferencedByResidual(idx_t build_col_idx) const; //! Materialise the narrow index vector for a narrowed column: the dictionary indices of a chunk that wraps the diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp index 292e83028..5cd8bb053 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp @@ -93,6 +93,27 @@ class ScannerResult { return states.states[1] == state; } + //! Results that materialize values override these, so the block scan skips the values nobody asked for + template + static inline bool CanSkipValue(const T &result) { + return false; + } + template + static inline void SkipValue(T &result, const idx_t buffer_pos) { + } + template + static inline bool AddRowWithoutValue(T &result, const idx_t buffer_pos) { + return false; + } + //! Whether a value of this result may skip its UTF-8 check, so the block scan tracks ASCII blocks + template + static inline bool TracksAscii(const T &result) { + return false; + } + + //! Set by the block scan while it adds a value whose bytes all lie in blocks without high bits, so the value + //! needs no UTF-8 validation + bool ascii_value = false; //! Variable to keep information regarding quoted and escaped values bool quoted = false; //! If the current quoted value is unquoted @@ -343,23 +364,45 @@ class BaseScanner { candidates &= ~(((uint64_t(1) << (to - from)) - 1) << (from - pos)); } - //! The delimiter at `at`, `before` is the state before it - template - void BlockDelimiter(T &result, const idx_t at, const CSVState before) { + //! The delimiter at `at`, `before` is the state before it, `ascii` whether the value lies in ASCII blocks + template + void BlockDelimiter(T &result, const idx_t at, const CSVState before, const bool ascii) { states.states[0] = before; states.states[1] = CSVState::DELIMITER; iterator.pos.buffer_pos = at; - T::AddValue(result, at); + if (T::CanSkipValue(result)) { + T::SkipValue(result, at); + } else { + if (TRACK_ASCII) { + result.ascii_value = ascii; + } + T::AddValue(result, at); + if (TRACK_ASCII) { + result.ascii_value = false; + } + } } - //! The row end at `at`, `before` is the state before it. Returns true when the result is full - template + //! The row end at `at`, `before` is the state before it, `ascii` whether the last value lies in ASCII blocks. + //! Returns true when the result is full + template bool BlockRowEnd(T &result, const idx_t at, const CSVState before, const bool crlf, uint64_t &candidates, - const idx_t pos) { + const idx_t pos, const bool ascii) { states.states[0] = before; states.states[1] = crlf ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR; iterator.pos.buffer_pos = at; - const bool full = T::AddRow(result, at); + bool full; + if (T::CanSkipValue(result)) { + full = T::AddRowWithoutValue(result, at); + } else { + if (TRACK_ASCII) { + result.ascii_value = ascii; + } + full = T::AddRow(result, at); + if (TRACK_ASCII) { + result.ascii_value = false; + } + } lines_read++; if (full) { iterator.pos.buffer_pos = at + 1; @@ -394,10 +437,22 @@ class BaseScanner { return false; } + //! Chooses the ProcessBlocks instantiation of the dialect, TRACK_ASCII is the scan's + template + bool ProcessBlocksOfDialect(T &result, const idx_t to_pos) { + if (block_comment != '\0') { + return block_multi_byte_delimiter ? ProcessBlocks(result, to_pos) + : ProcessBlocks(result, to_pos); + } + return block_multi_byte_delimiter ? ProcessBlocks(result, to_pos) + : ProcessBlocks(result, to_pos); + } + //! Scans unquoted fields and quoted values in their canonical form, and preserves the states when handing back //! to Process. Returns true when the result is full. Repeated SetQuoted calls may be skipped because the setter - //! is idempotent. MULTI_BYTE_DELIMITER and COMMENT are the dialect's, so dialects without them pay nothing for them - template + //! is idempotent. MULTI_BYTE_DELIMITER and COMMENT are the dialect's and TRACK_ASCII the scan's (a projected string + //! column is validated), so dialects and scans without them pay nothing for them + template DUCKDB_BLOCK_SCAN_ALIGNED bool ProcessBlocks(T &result, const idx_t to_pos) { const auto buffer = buffer_handle_ptr; // the first byte not consumed, and the first byte after the last structural or special byte @@ -407,10 +462,18 @@ class BaseScanner { // inside a comment only a row end matters, `comment_before` is the state before the comment byte bool comment = false; CSVState comment_before = CSVState::NOT_SET; + // whether every block that holds a byte of the current value is ASCII, tracked only when a value can skip + // its UTF-8 check, a value that began before the block scan is validated as every other value of the byte loop + const bool track_ascii = TRACK_ASCII; + bool value_ascii = track_ascii && IsSeparatorState(states.states[1]); + bool block_ascii = false; uint64_t candidates; idx_t block_end; while (pos < to_pos && skipper.BlockCandidates(pos, candidates, block_end)) { const idx_t limit = MinValue(block_end, to_pos); + block_ascii = + track_ascii && !SwarBlock::HasHighBits(const_data_ptr_cast(buffer + block_end - SwarBlock::SIZE)); + value_ascii = value_ascii && block_ascii; while (candidates) { const idx_t at = pos + CountZeros::Trailing(candidates); if (at >= limit) { @@ -433,6 +496,7 @@ class BaseScanner { return true; } comment = false; + value_ascii = block_ascii; last = at + row_end_bytes; continue; } @@ -490,14 +554,18 @@ class BaseScanner { if (MULTI_BYTE_DELIMITER) { ClearCandidates(candidates, pos, at + 2, at + 1 + delimiter_bytes); } - BlockDelimiter(result, at + delimiter_bytes, - MULTI_BYTE_DELIMITER ? DelimiterPenultimateState() : CSVState::UNQUOTED); + BlockDelimiter( + result, at + delimiter_bytes, + MULTI_BYTE_DELIMITER ? DelimiterPenultimateState() : CSVState::UNQUOTED, value_ascii); + value_ascii = block_ascii; last = at + 1 + delimiter_bytes; continue; } - if (BlockRowEnd(result, at + 1, CSVState::UNQUOTED, row_end_bytes == 2, candidates, pos)) { + if (BlockRowEnd(result, at + 1, CSVState::UNQUOTED, row_end_bytes == 2, candidates, + pos, value_ascii)) { return true; } + value_ascii = block_ascii; last = at + 1 + row_end_bytes; continue; } @@ -512,13 +580,16 @@ class BaseScanner { D_ASSERT(ReplayStates(last, at + delimiter_bytes).states[1] == CSVState::DELIMITER); D_ASSERT(ReplayStates(last, at + delimiter_bytes).states[0] == DelimiterPenultimateState()); ClearCandidates(candidates, pos, at + 1, at + delimiter_bytes); - BlockDelimiter(result, at + delimiter_bytes - 1, DelimiterPenultimateState()); + BlockDelimiter(result, at + delimiter_bytes - 1, DelimiterPenultimateState(), + value_ascii); + value_ascii = block_ascii; last = at + delimiter_bytes; continue; } D_ASSERT(ReplayStates(last, at + 1).states[1] == CSVState::DELIMITER); D_ASSERT(ReplayStates(last, at + 1).states[0] == before); - BlockDelimiter(result, at, before); + BlockDelimiter(result, at, before, value_ascii); + value_ascii = block_ascii; last = at + 1; continue; } @@ -564,9 +635,10 @@ class BaseScanner { D_ASSERT(ReplayStates(last, at + 1).states[0] == before); D_ASSERT(ReplayStates(last, at + 1).states[1] == (row_end_bytes == 2 ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR)); - if (BlockRowEnd(result, at, before, row_end_bytes == 2, candidates, pos)) { + if (BlockRowEnd(result, at, before, row_end_bytes == 2, candidates, pos, value_ascii)) { return true; } + value_ascii = block_ascii; last = at + row_end_bytes; } pos = limit; @@ -601,11 +673,8 @@ class BaseScanner { skipper.SetBuffer(*cur_buffer_handle); while (iterator.pos.buffer_pos < to_pos) { if (T::BLOCK_SCAN && block_scan && BlockScanPossible(result)) { - const bool full = block_comment != '\0' - ? (block_multi_byte_delimiter ? ProcessBlocks(result, to_pos) - : ProcessBlocks(result, to_pos)) - : (block_multi_byte_delimiter ? ProcessBlocks(result, to_pos) - : ProcessBlocks(result, to_pos)); + const bool full = T::TracksAscii(result) ? ProcessBlocksOfDialect(result, to_pos) + : ProcessBlocksOfDialect(result, to_pos); if (full) { bytes_read = iterator.pos.buffer_pos - start_pos; return; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer.hpp index bf63f963a..9eabb7340 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer.hpp @@ -91,9 +91,8 @@ class CSVBuffer { return block && (!random_access || !block->GetMemory().IsUnloaded()); } - //! By default, we use CSV_BUFFER_SIZE to allocate each buffer - static constexpr idx_t ROWS_PER_BUFFER = 16; - static constexpr idx_t MIN_ROWS_PER_BUFFER = 4; + //! With the block header and alignment the allocation is exactly 32 MiB, a size the allocation cache reuses + static constexpr idx_t CSV_BUFFER_SIZE = 33550336; bool last_buffer = false; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_scanner.hpp index f8d3df880..b602978b1 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_scanner.hpp @@ -90,6 +90,8 @@ class CSVFileScan { //! Variables to handle projection pushdown set projected_columns; + //! No column of the file is projected: the scan reads the first column only to count rows + bool reads_first_column_to_count_rows = false; std::vector> projection_ids; //! Options for this CSV Reader 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 181485637..1592a2a21 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 @@ -119,7 +119,7 @@ struct CSVReaderOptions { //! The file path of the CSV file to read string file_path; //! Buffer Size (Parallel Scan) - CSVOption buffer_size_option = CSVBuffer::ROWS_PER_BUFFER * max_line_size_default; + CSVOption buffer_size_option = CSVBuffer::CSV_BUFFER_SIZE; //! Decimal separator when reading as numeric string decimal_separator = "."; //! Whether to pad rows that do not have enough columns with NULL values diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/scanner_boundary.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/scanner_boundary.hpp index 9d3c90aa5..06d7b46c6 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/scanner_boundary.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/scanner_boundary.hpp @@ -78,6 +78,8 @@ struct CSVIterator { static idx_t BytesPerThread(const CSVReaderOptions &reader_options); + //! A thread's boundary is ROWS_PER_THREAD / ROWS_PER_BUFFER of the buffer size, and at least one maximum line size + static constexpr idx_t ROWS_PER_BUFFER = 16; static constexpr idx_t ROWS_PER_THREAD = 4; CSVPosition pos; 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 ab4255cce..264df4437 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 @@ -221,8 +221,8 @@ class StringValueResult : public ScannerResult { CSVIterator &iterator; //! Line position of the current line FullLinePosition current_line_position; - //! Used for CSV line reconstruction on flushed errors - unordered_map line_positions_per_row; + //! Used for CSV line reconstruction on flushed errors, one entry per row of the result + vector line_positions_per_row; bool added_last_line = false; bool quoted_new_line = false; @@ -230,6 +230,8 @@ class StringValueResult : public ScannerResult { bool try_row = false; unsafe_unique_array parse_types; + //! Whether a column of the parse chunk is validated as UTF-8 + bool validates_utf8 = false; vector names; shared_ptr csv_file_scan; @@ -275,6 +277,16 @@ class StringValueResult : public ScannerResult { static inline void AddValue(StringValueResult &result, const idx_t buffer_pos); //! Adds a Row to the result static inline bool AddRow(StringValueResult &result, const idx_t buffer_pos); + //! Whether the current column is not projected, so its value needs no reading + static inline bool CanSkipValue(const StringValueResult &result) { + return result.projecting_columns && result.cur_col_id < result.number_of_columns && + !result.projected_columns[result.cur_col_id]; + } + static inline void SkipValue(StringValueResult &result, const idx_t buffer_pos); + static inline bool AddRowWithoutValue(StringValueResult &result, const idx_t buffer_pos); + static inline bool TracksAscii(const StringValueResult &result) { + return result.validates_utf8; + } //! Behavior when hitting an invalid state static inline void InvalidState(StringValueResult &result); //! Handles QuotedNewline State @@ -283,6 +295,12 @@ class StringValueResult : public ScannerResult { //! Handles EmptyLine states static inline bool EmptyLine(StringValueResult &result, const idx_t buffer_pos); inline bool AddRowInternal(); + //! The bookkeeping of a value that is not projected + inline void SkipValueInternal(); + //! Moves last_position past the newline that ends the row at buffer_pos + inline void SetLastPositionAfterNewline(idx_t buffer_pos); + //! Keeps the position of the current row for the error messages of Flush + inline void StoreLinePosition(); //! Marks the columns of a borked row that were never written as NULL void InvalidateUnwrittenColumns(idx_t first_unwritten_col); //! Force the throw of a Unicode error diff --git a/src/duckdb/src/include/duckdb/execution/operator/helper/physical_execute.hpp b/src/duckdb/src/include/duckdb/execution/operator/helper/physical_execute.hpp deleted file mode 100644 index ea62de16c..000000000 --- a/src/duckdb/src/include/duckdb/execution/operator/helper/physical_execute.hpp +++ /dev/null @@ -1,34 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/execution/operator/helper/physical_execute.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/execution/physical_operator.hpp" -#include "duckdb/main/prepared_statement_data.hpp" - -namespace duckdb { - -class PhysicalExecute : public PhysicalOperator { -public: - static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::EXECUTE; - -public: - PhysicalExecute(PhysicalPlan &physical_plan, PhysicalOperator &plan, shared_ptr prepared); - - PhysicalOperator &plan; - //! The prepared statement we are executing - kept alive here because it can own the plan we refer to - shared_ptr prepared; - -public: - vector> GetChildren() const override; - -public: - void BuildPipelines(Pipeline ¤t, MetaPipeline &meta_pipeline) override; -}; - -} // namespace duckdb 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 72d511a22..652e1e4d5 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 @@ -35,6 +35,22 @@ enum class JoinFilterPushdownMode : uint8_t { }; struct JoinFilterPushdownColumn { + JoinFilterPushdownColumn() = default; + JoinFilterPushdownColumn(const JoinFilterPushdownColumn &other) + : join_filter_idx(other.join_filter_idx), probe_column_index(other.probe_column_index), + storage_type(other.storage_type), mode(other.mode), + input_expression(other.input_expression ? other.input_expression->Copy() : nullptr) { + } + JoinFilterPushdownColumn &operator=(const JoinFilterPushdownColumn &other) { + if (this != &other) { + JoinFilterPushdownColumn copy(other); + *this = std::move(copy); + } + return *this; + } + JoinFilterPushdownColumn(JoinFilterPushdownColumn &&other) = default; + JoinFilterPushdownColumn &operator=(JoinFilterPushdownColumn &&other) = default; + //! Index into JoinFilterPushdownInfo::join_condition for this pushed column idx_t join_filter_idx = DConstants::INVALID_INDEX; //! The probe column index to which this filter should be applied @@ -43,8 +59,8 @@ struct JoinFilterPushdownColumn { LogicalType storage_type; //! Whether runtime filters can reconstruct the pushed expression, or whether only storage-domain filters are safe JoinFilterPushdownMode mode = JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION; - //! Casts from the raw scan value to the pushed probe expression, in evaluation order. - vector runtime_filter_casts; + //! Filter input over BoundReferenceExpression(0) in the existing scan projection's type. + unique_ptr input_expression; }; enum class DeferredRuntimeFilterType : uint8_t { BLOOM_FILTER, PREFIX_RANGE }; @@ -55,6 +71,8 @@ struct DeferredRuntimeFilterPushdown { shared_ptr dynamic_filters; JoinFilterPushdownColumn column; ProjectionIndex filter_col_idx; + //! The key column of the hash table the filter is built from + idx_t key_idx = 0; }; struct JoinFilterGlobalState { @@ -121,25 +139,24 @@ struct JoinFilterPushdownInfo { optional_ptr gstate = nullptr) const; private: + struct FilterFinalizer; + bool PushInFilter(ClientContext &context, const JoinFilterPushdownFilter &info, const JoinFilterPushdownColumn &column, JoinHashTable &ht, const PhysicalOperator &op, idx_t filter_idx, ProjectionIndex filter_col_idx) const; void DeferRuntimeFilter(DeferredRuntimeFilterType type, const PhysicalOperator &op, const JoinFilterPushdownFilter &info, const JoinFilterPushdownColumn &column, - ProjectionIndex filter_col_idx, JoinFilterGlobalState &gstate) const; + ProjectionIndex filter_col_idx, idx_t key_idx, JoinFilterGlobalState &gstate) const; bool TryRegisterPrefixRangeFilter(const JoinFilterPushdownFilter &info, ClientContext &context, JoinHashTable &ht, const PhysicalOperator &op, const JoinFilterPushdownColumn &column, - ProjectionIndex filter_col_idx, const Value &min_val, const Value &max_val, - idx_t max_bits, JoinFilterGlobalState &gstate) const; + ProjectionIndex filter_col_idx, idx_t key_idx, const Value &min_val, + const Value &max_val, idx_t max_bits, JoinFilterGlobalState &gstate) const; bool CanUseInFilter(const ClientContext &context, optional_ptr ht, const ExpressionType &cmp) const; bool CanUseBloomFilter(const JoinFilterPushdownFilter &info, const ClientContext &context, const PhysicalComparisonJoin &op, const ExpressionType &cmp, optional_ptr ht = nullptr) const; - bool CanUsePrefixRangeFilter(const JoinFilterPushdownFilter &info, const ClientContext &context, - const PhysicalComparisonJoin &op, optional_ptr ht, - const ExpressionType &cmp) const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/perfect_hash_join_executor.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/perfect_hash_join_executor.hpp deleted file mode 100644 index 744a8fb60..000000000 --- a/src/duckdb/src/include/duckdb/execution/operator/join/perfect_hash_join_executor.hpp +++ /dev/null @@ -1,78 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/execution/operator/join/perfect_hash_join_executor.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/row_operations/row_operations.hpp" -#include "duckdb/execution/execution_context.hpp" -#include "duckdb/execution/join_hashtable.hpp" -#include "duckdb/execution/physical_operator.hpp" - -namespace duckdb { - -class HashJoinOperatorState; -class HashJoinGlobalSinkState; -class PhysicalHashJoin; - -struct PerfectHashJoinStats { - Value build_min; - Value build_max; - bool is_build_small = false; - bool is_build_dense = false; - idx_t build_range = 0; -}; - -//! PhysicalHashJoin represents a hash loop join between two tables -class PerfectHashJoinExecutor { - using PerfectHashTable = vector>; - -public: - PerfectHashJoinExecutor(const PhysicalHashJoin &join, JoinHashTable &ht); - -public: - bool CanDoPerfectHashJoin(const PhysicalHashJoin &op, const Value &min, const Value &max); - - const LogicalType &GetKeyType() const; - bool BuildPerfectHashTable(); - - unique_ptr GetOperatorState(ExecutionContext &context); - OperatorResultType ProbePerfectHashTable(ExecutionContext &context, DataChunk &input, DataChunk &lhs_output_columns, - DataChunk &chunk, OperatorState &state); - - void FillSelectionVectorSwitchProbe(const Vector &source, const idx_t &count, SelectionVector &probe_sel_vec, - idx_t &probe_sel_count, optional_ptr build_sel_vec) const; - -private: - template - void FillSelectionVectorSwitchProbe(const Vector &source, const idx_t &count, SelectionVector &probe_sel_vec, - idx_t &probe_sel_count, SelectionVector *build_sel_vec) const; - template - void TemplatedFillSelectionVectorProbe(const Vector &source, const idx_t &count, SelectionVector &probe_sel_vec, - idx_t &probe_sel_count, SelectionVector *build_sel_vec) const; - - bool FillSelectionVectorSwitchBuild(const Vector &source, SelectionVector &sel_vec, SelectionVector &seq_sel_vec, - idx_t count); - template - bool TemplatedFillSelectionVectorBuild(const Vector &source, SelectionVector &sel_vec, SelectionVector &seq_sel_vec, - idx_t count); - bool FullScanHashTable(); - -private: - const PhysicalHashJoin &join; - JoinHashTable &ht; - //! Columnar perfect hash table - PerfectHashTable perfect_hash_table; - //! Build statistics - PerfectHashJoinStats perfect_join_statistics; - //! Stores the occurrences of each value in the build side - ValidityMask bitmap_build_idx; - //! Stores the number of unique keys in the build side - idx_t unique_keys = 0; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/batch_memory_manager.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/batch_memory_manager.hpp index 417af2d5d..717c3f339 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/batch_memory_manager.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/batch_memory_manager.hpp @@ -123,6 +123,10 @@ class BatchMemoryManager : public StateWithBlockableTasks { return batch_index <= min_batch_index; } + idx_t GetMinimumBatchIndex() const { + return min_batch_index; + } + void FinalCheck() { if (unflushed_memory_usage != 0) { throw InternalException("Unflushed memory usage is not zero at finalize but %llu", 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 4a573d560..5d851faa8 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 @@ -11,7 +11,6 @@ #include "duckdb/execution/physical_operator.hpp" #include "duckdb/planner/expression.hpp" #include "duckdb/planner/bound_constraint.hpp" -#include "duckdb/common/enums/row_id_handling.hpp" namespace duckdb { class DataTable; @@ -26,8 +25,8 @@ class PhysicalUpdate : public PhysicalOperator { PhysicalUpdate(PhysicalPlan &physical_plan, vector types, DuckTableEntry &tableref, DataTable &table, vector columns, vector> expressions, vector> bound_defaults, vector> bound_constraints, - idx_t estimated_cardinality, bool return_chunk, bool capture_old_rows, vector old_row_columns, - RowIdHandling row_id_handling); + idx_t estimated_cardinality, bool return_chunk, bool capture_old_rows, + vector old_row_columns); DuckTableEntry &tableref; DataTable &table; @@ -42,9 +41,6 @@ class PhysicalUpdate : public PhysicalOperator { bool capture_old_rows; //! Input-chunk index of each captured OLD physical column, in physical table order (only when capture_old_rows) vector old_row_columns; - //! How to handle a target row-id that appears more than once in the input (e.g. UPDATE ... FROM): keep the - //! lock-free path (ASSUME_UNIQUE), deduplicate keeping the first match (KEEP_FIRST), or error (ERROR). - RowIdHandling row_id_handling; //! Set to true, if we are updating an index column. bool index_update; 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 new file mode 100644 index 000000000..42908d805 --- /dev/null +++ b/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp @@ -0,0 +1,75 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/execution/perfect_hash_join_table.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/allocator.hpp" +#include "duckdb/common/array_ptr.hpp" +#include "duckdb/common/atomic.hpp" +#include "duckdb/common/types/vector.hpp" +#include "duckdb/common/unique_ptr.hpp" + +namespace duckdb { + +class TupleDataLayout; + +//! Direct integer lookup for JoinHashTable. +class PerfectHashJoinTable { +public: + enum class Type { BITMAP, ROWS, DICTIONARY }; + + PerfectHashJoinTable(Type type, bool nulls_equal) : nulls_equal(nulls_equal), type(type) { + D_ASSERT(type != Type::DICTIONARY); + } + virtual ~PerfectHashJoinTable(); + + static unique_ptr Create(PhysicalType key_type, Type type, bool nulls_equal); + + //! 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; + //! 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; + + void InitializeEntries(idx_t from, idx_t to); + void ConvertToDictionary(idx_t pointer_offset); + idx_t EntryCount() const { + return entries.GetSize() / sizeof(uint64_t); + } + Type GetType() const { + return type; + } + +protected: + bool IsBitmap() const { + return type == Type::BITMAP; + } + array_ptr GetEntries() { + return {reinterpret_cast(entries.get()), EntryCount()}; + } + array_ptr GetEntries() const { + return {reinterpret_cast(entries.get()), EntryCount()}; + } + array_ptr> GetAtomicEntries() { + return {reinterpret_cast *>(entries.get()), EntryCount()}; + } + + static constexpr idx_t MAX_BYTES = 8 * 1024 * 1024; + AllocatedData entries; + const bool nulls_equal; + +private: + Type type; +}; + +} // namespace duckdb 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 4e88cb2d3..684218fc1 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)...); } @@ -164,7 +164,6 @@ class PhysicalPlanGenerator { PhysicalOperator &CreatePlan(LogicalUpdate &op); PhysicalOperator &CreatePlan(LogicalPrepare &expr); PhysicalOperator &CreatePlan(LogicalWindow &expr); - PhysicalOperator &CreatePlan(LogicalExecute &op); PhysicalOperator &CreatePlan(LogicalPragma &op); PhysicalOperator &CreatePlan(LogicalSample &op); PhysicalOperator &CreatePlan(LogicalSecureView &op); 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 0c2f1ff81..8f7005668 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 @@ -110,6 +110,8 @@ class RadixHTGlobalSinkState : public GlobalSinkState { } //! Whether the aggregate arena alone approaches the thread memory limit bool StatePressureExceeded(GroupedAggregateHashTable &ht) const; + //! HT size without the arena when there is no spill plan: the arena then stays in memory whatever the sink does + idx_t SpillableSize(GroupedAggregateHashTable &ht) const; public: ClientContext &context; @@ -186,6 +188,8 @@ class RadixHTLocalSinkState : public LocalSinkState { bool spilling = false; //! Sink capacity for this thread idx_t local_sink_capacity; + //! Spillable size of the HT after it was last abandoned + idx_t size_after_abandon = 0; //! 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/cast/cast_function_set.hpp b/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp index 719e97f04..2308d2f94 100644 --- a/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp @@ -13,6 +13,7 @@ #include "duckdb/main/context.hpp" namespace duckdb { +class Context; struct MapCastInfo; struct MapCastNode; struct DBConfig; @@ -22,15 +23,28 @@ typedef BoundCastInfo (*bind_cast_function_t)(BindCastInput &input, const Logica typedef int64_t (*implicit_cast_cost_t)(const LogicalType &from, const LogicalType &to); struct GetCastFunctionInput { - explicit GetCastFunctionInput(optional_ptr context = nullptr) : context(context) { - } - explicit GetCastFunctionInput(ClientContext &context) : context(&context) { - } - explicit GetCastFunctionInput(Context &context) : context(context.TryGetClientContext()) { + DUCKDB_API explicit GetCastFunctionInput(Context &context); + DUCKDB_API explicit GetCastFunctionInput(ClientContext &context); + + //! Input for the default casts: there are no services, so GetContext() must not be called + DUCKDB_API static GetCastFunctionInput Default(); + + //! The services of the cast + DUCKDB_API Context &GetContext(); + //! The services of the cast (if any) + optional_ptr TryGetContext() const { + return context; } - optional_ptr context; + //! The client context - only present if the cast is bound for a client + optional_ptr client_context; QueryLocation query_location; + +private: + GetCastFunctionInput() = default; + +private: + optional_ptr context; }; struct BindCastFunction { @@ -73,6 +87,9 @@ class CastFunctionSet { //! Data-dependent VARIANT conversions are treated conservatively. DUCKDB_API bool CanOverrideDefaultCast(const LogicalType &source, const LogicalType &target) const; + //! Returns registered source types that can match this target, without invoking bind callbacks. + DUCKDB_API vector GetRegisteredCastSourceTypes(const LogicalType &target) const; + //! Register a combine rule for LogicalType::TryGetMaxLogicalType, consulted before previously registered rules //! and the built-in rules DUCKDB_API void RegisterCombineTypesRule(CombineTypesRule rule); 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 c0b09de41..1962b51b4 100644 --- a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp @@ -18,6 +18,8 @@ namespace duckdb { class CastFunctionSet; +class Context; +struct GetCastFunctionInput; class BaseStatistics; struct FunctionLocalState; struct BoundCastInfo; @@ -173,6 +175,9 @@ struct BoundCastInfo { bool HasStatisticsCallback() const { return statistics; } + bool HasSameStatisticsCallback(const BoundCastInfo &other) const { + return statistics && statistics == other.statistics; + } void SetStatisticsCallback(cast_statistics_t new_statistics) { statistics = new_statistics; } @@ -196,7 +201,10 @@ struct BoundCastInfo { struct BindCastInput { DUCKDB_API BindCastInput(CastFunctionSet &function_set, optional_ptr info, - optional_ptr context); + GetCastFunctionInput &get_input); + + //! The services of the cast - throws for the default casts, which have none + DUCKDB_API Context &GetContext(); CastFunctionSet &function_set; optional_ptr info; @@ -207,6 +215,9 @@ struct BindCastInput { public: DUCKDB_API BoundCastInfo GetCastFunction(const LogicalType &source, const LogicalType &target); + +private: + optional_ptr services; }; struct DefaultCasts { diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/to_variant_fwd.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/to_variant_fwd.hpp index 65ead7f16..89cd5021d 100644 --- a/src/duckdb/src/include/duckdb/function/cast/variant/to_variant_fwd.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/variant/to_variant_fwd.hpp @@ -47,16 +47,17 @@ struct OffsetData { struct ToVariantGlobalResultData { public: ToVariantGlobalResultData(VariantVectorData &variant, DataChunk &offsets, - OrderedOwningStringMap &dictionary, SelectionVector &keys_selvec, - Allocator &allocator) - : variant(variant), offsets(offsets), dictionary(dictionary), keys_selvec(keys_selvec), allocator(allocator) { + OrderedOwningStringMap &dictionary, ArenaAllocator &keys_arena, + SelectionVector &keys_selvec, Allocator &allocator) + : variant(variant), offsets(offsets), dictionary(dictionary), keys_arena(keys_arena), keys_selvec(keys_selvec), + allocator(allocator) { } public: uint32_t GetOrCreateIndex(const string_t &key) { auto unsorted_idx = dictionary.size(); //! This will later be remapped to the sorted idx (see FinalizeVariantKeys in 'to_variant.cpp') - return dictionary.emplace(std::make_pair(key, unsorted_idx)).first->second; + return dictionary.emplace(std::make_pair(key, unsorted_idx), keys_arena).first->second; } public: @@ -64,6 +65,8 @@ struct ToVariantGlobalResultData { DataChunk &offsets; //! The dictionary to populate with the (unique and sorted) keys OrderedOwningStringMap &dictionary; + //! The result's keys arena, the dictionary's keys are allocated in + ArenaAllocator &keys_arena; //! The selection vector to populate with mapping from keys index -> dictionary index SelectionVector &keys_selvec; //! Allocator for temporary conversion memory (e.g. JSON parsing), tracked by DuckDB's memory accounting diff --git a/src/duckdb/src/include/duckdb/function/compression_function.hpp b/src/duckdb/src/include/duckdb/function/compression_function.hpp index 10b53dde2..c3d36db46 100644 --- a/src/duckdb/src/include/duckdb/function/compression_function.hpp +++ b/src/duckdb/src/include/duckdb/function/compression_function.hpp @@ -309,6 +309,10 @@ class CompressionFunction { //! Whether persistent segments can be stored without a backing data block. bool supports_null_block = false; + + //! Whether new segments are zero-initialized before compression. A function that sets this to false must + //! initialize every byte it persists itself. + bool zero_initialize_segments = true; }; //! The set of compression functions diff --git a/src/duckdb/src/include/duckdb/function/function.hpp b/src/duckdb/src/include/duckdb/function/function.hpp index 4958a7a32..eee977d25 100644 --- a/src/duckdb/src/include/duckdb/function/function.hpp +++ b/src/duckdb/src/include/duckdb/function/function.hpp @@ -154,6 +154,15 @@ class FunctionParameter { } } + //! A positional-only parameter declared without a name. It is named "col" internally, as every parameter + //! needs one, but prints as its bare type: the name was never declared, so a caller cannot use it + static FunctionParameter Unnamed(LogicalType type, idx_t index) { + FunctionParameter result(Identifier(StringUtil::Format("col%d", index)), std::move(type), {}, + FunctionParameterKind::POSITIONAL_ONLY); + result.named = false; + return result; + } + string ToString() const; bool operator==(const FunctionParameter &other) const; @@ -164,6 +173,11 @@ class FunctionParameter { } auto SetName(Identifier name_p) -> void { name = std::move(name_p); + named = true; + } + //! Whether the parameter was declared with a name, see Unnamed + auto IsNamed() const -> bool { + return named; } auto GetType() const -> const LogicalType & { @@ -204,6 +218,7 @@ class FunctionParameter { LogicalType type; shared_ptr default_value; FunctionParameterKind kind; + bool named = true; }; //! An option a function receives through its "**kwargs" parameter @@ -343,11 +358,10 @@ class FunctionSignature { parameters.emplace_back(std::move(name), std::move(type), std::move(default_value), kind); return *this; } - //! Adds a positional-only parameter named "col", after its position - a caller cannot pass it by a name that - //! was never declared + //! Adds a positional-only parameter declared without a name, see FunctionParameter::Unnamed auto AddParameter(LogicalType type) -> FunctionSignature & { - auto name = Identifier(StringUtil::Format("col%d", parameters.size())); - return AddPositionalOnly(std::move(name), std::move(type)); + parameters.push_back(FunctionParameter::Unnamed(std::move(type), parameters.size())); + return *this; } auto AddKeywordOnly(Identifier name, LogicalType type, optional default_value = {}) -> FunctionSignature & { return AddParameter(std::move(name), std::move(type), std::move(default_value), diff --git a/src/duckdb/src/include/duckdb/function/function_binder.hpp b/src/duckdb/src/include/duckdb/function/function_binder.hpp index 86b232459..2617759a9 100644 --- a/src/duckdb/src/include/duckdb/function/function_binder.hpp +++ b/src/duckdb/src/include/duckdb/function/function_binder.hpp @@ -98,8 +98,8 @@ struct FunctionCallArgument { : type(std::move(type)), name(std::move(name)), location(location) { } //! For the type constants, e.g. LogicalType::INTEGER - FunctionCallArgument(LogicalTypeId id) - : FunctionCallArgument(LogicalType(id)) { // NOLINT: allow implicit conversion + FunctionCallArgument(LogicalTypeId id) // NOLINT: allow implicit conversion + : FunctionCallArgument(LogicalType(id)) { } LogicalType type; @@ -424,32 +424,32 @@ class FunctionBinder { //! whose type is not concrete, such as ANY, takes it as it is DUCKDB_API static Value CastToParameterType(ClientContext &context, Value value, const LogicalType ¶meter_type); - DUCKDB_API unique_ptr BindScalarFunction(const Identifier &schema, const Identifier &name, - vector> children, ErrorData &error, - bool is_operator = false, - optional_ptr binder = nullptr); + DUCKDB_API unique_ptr + BindScalarFunction(const Identifier &schema, const Identifier &name, vector> children, + ErrorData &error, bool is_operator = false, optional_ptr binder = nullptr, + Identifier alias = Identifier(), QueryLocation query_location = QueryLocation()); //! Throws the binding error instead of returning nullptr - DUCKDB_API unique_ptr BindScalarFunction(const Identifier &schema, const Identifier &name, - vector> children, - bool is_operator = false, - optional_ptr binder = nullptr); + DUCKDB_API unique_ptr + BindScalarFunction(const Identifier &schema, const Identifier &name, vector> children, + bool is_operator = false, optional_ptr binder = nullptr, Identifier alias = Identifier(), + QueryLocation query_location = QueryLocation()); - DUCKDB_API unique_ptr BindScalarFunction(const ScalarFunctionCatalogEntry &function, - vector> children, ErrorData &error, - bool is_operator = false, - optional_ptr binder = nullptr); + DUCKDB_API unique_ptr + BindScalarFunction(const ScalarFunctionCatalogEntry &function, vector> children, + ErrorData &error, bool is_operator = false, optional_ptr binder = nullptr, + Identifier alias = Identifier(), QueryLocation query_location = QueryLocation()); - DUCKDB_API unique_ptr BindScalarFunction(const shared_ptr &function, - vector> children, - bool is_operator = false, - optional_ptr binder = nullptr); + DUCKDB_API unique_ptr + BindScalarFunction(const shared_ptr &function, vector> children, + bool is_operator = false, optional_ptr binder = nullptr, Identifier alias = Identifier(), + QueryLocation query_location = QueryLocation()); //! Bind a function that does not come from a function set - the function is copied into a definition of its own - DUCKDB_API unique_ptr BindScalarFunction(const ScalarFunction &function, - vector> children, - bool is_operator = false, - optional_ptr binder = nullptr); + DUCKDB_API unique_ptr + BindScalarFunction(const ScalarFunction &function, vector> children, + bool is_operator = false, optional_ptr binder = nullptr, Identifier alias = Identifier(), + QueryLocation query_location = QueryLocation()); //! Bind a scalar function from a catalog entry given the full list of (maybe-named) bound arguments. The //! positional/named split is resolved per candidate overload (overloads flagged to capture argument aliases @@ -457,19 +457,21 @@ class FunctionBinder { DUCKDB_API unique_ptr BindScalarFunction(const ScalarFunctionCatalogEntry &function, vector>> arguments, ErrorData &error, bool is_operator = false, - optional_ptr binder = nullptr); - - DUCKDB_API unique_ptr BindScalarFunction(const shared_ptr &function, - vector> children, - vector>> keyword_args, - bool is_operator = false, - optional_ptr binder = nullptr); - - DUCKDB_API unique_ptr BindScalarFunction(const ScalarFunction &function, - vector> children, - vector>> keyword_args, - bool is_operator = false, - optional_ptr binder = nullptr); + optional_ptr binder = nullptr, + Identifier alias = Identifier(), + QueryLocation query_location = QueryLocation()); + + DUCKDB_API unique_ptr + BindScalarFunction(const shared_ptr &function, vector> children, + vector>> keyword_args, bool is_operator = false, + optional_ptr binder = nullptr, Identifier alias = Identifier(), + QueryLocation query_location = QueryLocation()); + + DUCKDB_API unique_ptr + BindScalarFunction(const ScalarFunction &function, vector> children, + vector>> keyword_args, bool is_operator = false, + optional_ptr binder = nullptr, Identifier alias = Identifier(), + QueryLocation query_location = QueryLocation()); DUCKDB_API unique_ptr BindAggregateFunction(const shared_ptr &function, vector> children, @@ -559,7 +561,8 @@ class FunctionBinder { unique_ptr BindScalarFunction(const FunctionBinding &binding, vector> children, vector>> keyword_args, - bool is_operator, optional_ptr binder); + bool is_operator, optional_ptr binder, Identifier alias, + QueryLocation query_location); unique_ptr BindAggregateFunction(FunctionBinding binding, vector> children, vector>> keyword_args, unique_ptr filter, diff --git a/src/duckdb/src/include/duckdb/function/function_serialization.hpp b/src/duckdb/src/include/duckdb/function/function_serialization.hpp index 60b222cd4..9db57431b 100644 --- a/src/duckdb/src/include/duckdb/function/function_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/function_serialization.hpp @@ -166,6 +166,30 @@ class FunctionSerializer { } } + //! Selects the overload of a v1.x aggregate whose bind lost the erased arguments, by its leading parameter types + template + static optional_idx SelectByLeadingArguments(const FUNCTION_SET &functions, vector &arguments, + const LogicalType &return_type) { + for (idx_t offset = 0; offset < functions.functions.size(); offset++) { + auto &signature = functions.functions[offset]->GetSignature(); + if (signature.GetParameterCount() <= arguments.size() || + signature.GetReturnType().id() != return_type.id()) { + continue; + } + bool leading = true; + for (idx_t i = 0; i < arguments.size() && leading; i++) { + leading = signature.GetParameter(i).GetType().id() == arguments[i].id(); + } + if (leading) { + for (idx_t i = arguments.size(); i < signature.GetParameterCount(); i++) { + arguments.push_back(signature.GetParameter(i).GetType()); + } + return offset; + } + } + return optional_idx(); + } + //! Splits the argument types a plan recorded into those passed by position and those passed by name static void SplitArgumentTypes(const QualifiedName &qualified_name, const vector &arguments, idx_t positional_count, const vector &named_arguments, @@ -311,7 +335,8 @@ class FunctionSerializer { //! a trailing alias there is a genuine alias, not an argument name. template static void RestoreNamesFromAliases(const FUNCTION_SET &functions, const vector> &children, - idx_t &positional_count, vector &named_arguments) { + const LogicalType &return_type, idx_t &positional_count, + vector &named_arguments) { bool takes_named = false; idx_t standard_count = 0; for (auto &function : functions.functions) { @@ -325,6 +350,15 @@ class FunctionSerializer { if (!takes_named || children.size() != positional_count) { return; } + // the fields of a v1.x struct_pack are its argument names, also where a rewrite dropped an argument's alias + if (standard_count == 0 && return_type.id() == LogicalTypeId::STRUCT && + StructType::GetChildCount(return_type) == children.size()) { + for (idx_t i = 0; i < children.size(); i++) { + named_arguments.push_back(StructType::GetChildName(return_type, i)); + } + positional_count = 0; + return; + } idx_t named_offset = children.size(); while (named_offset > standard_count && !children[named_offset - 1]->GetAlias().empty()) { named_offset--; @@ -363,6 +397,7 @@ class FunctionSerializer { auto positional_count = deserializer.ReadPropertyWithDefault(508, "positional_arguments"); auto named_arguments = deserializer.ReadPropertyWithDefault>(509, "named_arguments"); + const bool legacy_without_original_arguments = original_arguments.empty() && positional_count == 0; RestoreErasedArguments(arguments, original_arguments); if (arguments.empty() && !children.empty()) { @@ -392,7 +427,7 @@ class FunctionSerializer { const bool argument_names_serialized = positional_count != 0; positional_count = arguments.size(); if (!argument_names_serialized) { - RestoreNamesFromAliases(functions, children, positional_count, named_arguments); + RestoreNamesFromAliases(functions, children, return_type, positional_count, named_arguments); } } @@ -421,14 +456,22 @@ class FunctionSerializer { FunctionBinder binder(context); binder.arguments_collated = true; const auto func_idx = FunctionBinder::SelectFunction(context, functions, {positional_types, keyword_types}); + optional_idx overload; + if (func_idx.IsSuccess()) { + overload = func_idx.GetBinding().GetOverloadIndex(); + } else if (catalog_type == CatalogType::AGGREGATE_FUNCTION_ENTRY && legacy_without_original_arguments && + named_arguments.empty() && !arguments.empty()) { + overload = SelectByLeadingArguments(functions, arguments, return_type); + positional_count = arguments.size(); + } // Ensure the function overload was found - if (!func_idx.IsSuccess()) { + if (!overload.IsValid()) { throw SerializationException("Failed to find function %s(%s)\n%s", qualified_name.ToString(), StringUtil::ToString(arguments, ","), func_idx.GetError().RawMessage()); } - const auto function = functions.GetFunctionByOffset(func_idx.GetBinding().GetOverloadIndex()); + const auto function = functions.GetFunctionByOffset(overload.GetIndex()); // Does this function support serializing its bound data? if (!has_serialize) { diff --git a/src/duckdb/src/include/duckdb/function/macro_function.hpp b/src/duckdb/src/include/duckdb/function/macro_function.hpp index 015608d8d..493a6c4d9 100644 --- a/src/duckdb/src/include/duckdb/function/macro_function.hpp +++ b/src/duckdb/src/include/duckdb/function/macro_function.hpp @@ -68,6 +68,9 @@ class MacroFunction { InsertionOrderPreservingMap, Identifier, identifier_map_t> &named_arguments); + //! Whether this member's parameter types equal the given type list exactly (ANY names an untyped slot) + bool MatchesSignature(const vector &signature) const; + virtual string ToSQL() const; virtual void Serialize(Serializer &serializer) const; diff --git a/src/duckdb/src/include/duckdb/function/scalar/compressed_materialization_utils.hpp b/src/duckdb/src/include/duckdb/function/scalar/compressed_materialization_utils.hpp index ff8fb362b..68e75d137 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/compressed_materialization_utils.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/compressed_materialization_utils.hpp @@ -25,6 +25,8 @@ struct CMUtils { static CMExpressionType GetExpressionType(const BoundFunctionExpression &expression); //! The input wrapped by a compressed materialization expression, or nullptr for any other expression static optional_ptr GetWrappedInput(const Expression &expression); + //! Whether the expression compresses its input, which only the statistics of the input where it was placed allow + static bool CompressesInput(const Expression &expression); static void MarkCast(BoundFunctionExpression &expression); private: 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 33069456d..8b5c90240 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/crypto_hash.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/crypto_hash.hpp @@ -9,11 +9,13 @@ #pragma once #include "duckdb/common/encryption_state.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" +#include "duckdb/main/database.hpp" #include "duckdb/common/vector/string_vector.hpp" #include "duckdb/execution/expression_executor_state.hpp" #include "duckdb/function/scalar_function.hpp" #include "duckdb/main/database.hpp" +#include "duckdb/main/settings.hpp" namespace duckdb { namespace crypto_hash_scalar { @@ -32,12 +34,13 @@ struct LocalState : public FunctionLocalState { template unique_ptr InitLocalState(ExpressionState &state, const BoundFunctionExpression &, FunctionData *) { - auto &context = state.GetContext(); - auto &config = DBConfig::GetConfig(context); - if (!config.options.force_mbedtls && config.encryption_util && config.encryption_util->SupportsHash(FUNCTION)) { + auto &db = state.GetContext().GetDatabase(); + auto &config = DBConfig::GetConfig(db); + auto force_mbedtls = Settings::Get(config); + if (!force_mbedtls && config.encryption_util && config.encryption_util->SupportsHash(FUNCTION)) { return make_uniq(config.encryption_util, FUNCTION); } - return make_uniq(context.db->GetMbedTLSUtil(config.options.force_mbedtls), FUNCTION); + return make_uniq(db.GetMbedTLSUtil(force_mbedtls), FUNCTION); } struct StringData { diff --git a/src/duckdb/src/include/duckdb/function/table/system_functions.hpp b/src/duckdb/src/include/duckdb/function/table/system_functions.hpp index fc5bade64..03a1e8a16 100644 --- a/src/duckdb/src/include/duckdb/function/table/system_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/table/system_functions.hpp @@ -14,6 +14,8 @@ namespace duckdb { +class Context; + struct PragmaCollations { static void RegisterFunction(BuiltinFunctions &set); }; @@ -135,7 +137,7 @@ struct DuckDBExternalResourcesFun { //! An external resource callback's handle/result column is part of the contract: it must be a MAP. Validate //! and normalize to MAP(VARCHAR, VARCHAR), so a callback that returns something else gets a clear error //! instead of crashing when the value is later read or emitted. NULL passes through unchanged. -Value RequireResourceMap(const Value &value, const string &function_name, const string &column); +Value RequireResourceMap(Context &context, const Value &value, const string &function_name, const string &column); struct DuckDBPreparedStatementsFun { static void RegisterFunction(BuiltinFunctions &set); 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 3eed2f4a7..5b97ec1b9 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp @@ -8,7 +8,7 @@ namespace duckdb { struct VariantNormalizerState { public: VariantNormalizerState(idx_t result_row, VariantVectorData &source, OrderedOwningStringMap &dictionary, - SelectionVector &keys_selvec); + ArenaAllocator &keys_arena, SelectionVector &keys_selvec); public: data_ptr_t GetDestination(); @@ -22,6 +22,7 @@ struct VariantNormalizerState { VariantVectorData &source; OrderedOwningStringMap &dictionary; + ArenaAllocator &keys_arena; SelectionVector &keys_selvec; uint64_t keys_offset; diff --git a/src/duckdb/src/include/duckdb/logging/log_manager.hpp b/src/duckdb/src/include/duckdb/logging/log_manager.hpp index 2115d8bcb..77bc2810d 100644 --- a/src/duckdb/src/include/duckdb/logging/log_manager.hpp +++ b/src/duckdb/src/include/duckdb/logging/log_manager.hpp @@ -9,7 +9,7 @@ #pragma once #include "duckdb/logging/logger.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/case_insensitive_map.hpp" @@ -20,7 +20,7 @@ class LogType; // - Handles configuration changes // - Creates Loggers with cached configuration // - Main sink for logs (either by logging directly into this, or by syncing a pre-cached set of log entries) -// - Holds the log storage +// - Holds the log sink class LogManager { friend class ThreadSafeLogger; friend class ThreadLocalLogger; @@ -42,7 +42,7 @@ class LogManager { RegisteredLoggingContext RegisterLoggingContext(const LoggingContext &context); - DUCKDB_API bool RegisterLogStorage(const string &name, shared_ptr &storage); + DUCKDB_API bool RegisterLogSink(const string &name, shared_ptr &sink); //! The global logger can be used when DUCKDB_API Logger &GlobalLogger(); @@ -51,27 +51,27 @@ class LogManager { //! Flush everything DUCKDB_API void Flush(); - //! Get a shared_ptr to the log storage (For example, to scan it) - DUCKDB_API shared_ptr GetLogStorage(); + //! Get a shared_ptr to the log sink (For example, to scan it) + DUCKDB_API shared_ptr GetLogSink(); DUCKDB_API bool CanScan(LoggingTargetTable table); DUCKDB_API void SetConfig(DatabaseInstance &db, const LogConfig &config); - //! The config together with its storage, to put back with RestoreConfig when a change fails - DUCKDB_API pair> GetConfigAndStorage(); - //! Puts back a config and its storage as GetConfigAndStorage returned them - DUCKDB_API void RestoreConfig(const LogConfig &config, shared_ptr storage); + //! The config together with its sink, to put back with RestoreConfig when a change fails + DUCKDB_API pair> GetConfigAndSink(); + //! Puts back a config and its sink as GetConfigAndSink returned them + DUCKDB_API void RestoreConfig(const LogConfig &config, shared_ptr sink); DUCKDB_API void SetEnableLogging(bool enable); DUCKDB_API void SetLogMode(LogMode mode); DUCKDB_API void SetLogLevel(LogLevel level); DUCKDB_API void SetEnabledLogTypes(optional_ptr> enabled_log_types); DUCKDB_API void SetDisabledLogTypes(optional_ptr> disabled_log_types); - DUCKDB_API void SetLogStorage(DatabaseInstance &db, const string &storage_name); + DUCKDB_API void SetLogSink(DatabaseInstance &db, const string &sink_name); - DUCKDB_API void UpdateLogStorageConfig(DatabaseInstance &db, case_insensitive_map_t &config_value); + DUCKDB_API void UpdateLogSinkConfig(DatabaseInstance &db, case_insensitive_map_t &config_value); DUCKDB_API void SetEnableStructuredLoggers(vector &enabled_logger_types); - DUCKDB_API void TruncateLogStorage(); + DUCKDB_API void TruncateLogSink(); DUCKDB_API LogConfig GetConfig(); @@ -88,9 +88,8 @@ class LogManager { // This allows efficiently pushing a cached set of log entries into the log manager void FlushCachedLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context); - //! Switches the log storage and sets the storage of new_config accordingly - void SetLogStorageInternal(DatabaseInstance &db, LogConfig &new_config, const string &storage_name) - DUCKDB_REQUIRES(lock); + //! Switches the log sink and sets the storage of new_config accordingly + void SetLogSinkInternal(DatabaseInstance &db, LogConfig &new_config, const string &sink_name) DUCKDB_REQUIRES(lock); optional_ptr LookupLogTypeInternal(const string &type) DUCKDB_REQUIRES(lock); @@ -107,13 +106,13 @@ class LogManager { PaddedAtomic config_version {0}; shared_ptr global_logger; - shared_ptr log_storage DUCKDB_GUARDED_BY(lock); + shared_ptr log_sink DUCKDB_GUARDED_BY(lock); DatabaseInstance &db_instance; PaddedAtomic next_registered_logging_context_index {0}; - // Any additional LogStorages registered (by extensions for example) - case_insensitive_map_t> registered_log_storages DUCKDB_GUARDED_BY(lock); + // Any additional LogSinks registered (by extensions for example) + case_insensitive_map_t> registered_log_sinks DUCKDB_GUARDED_BY(lock); case_insensitive_map_t> registered_log_types DUCKDB_GUARDED_BY(lock); }; diff --git a/src/duckdb/src/include/duckdb/logging/log_storage.hpp b/src/duckdb/src/include/duckdb/logging/log_sink.hpp similarity index 75% rename from src/duckdb/src/include/duckdb/logging/log_storage.hpp rename to src/duckdb/src/include/duckdb/logging/log_sink.hpp index 7e05e0108..de10aeee8 100644 --- a/src/duckdb/src/include/duckdb/logging/log_storage.hpp +++ b/src/duckdb/src/include/duckdb/logging/log_sink.hpp @@ -1,7 +1,7 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/logging/log_storage.hpp +// duckdb/logging/log_sink.hpp // // //===----------------------------------------------------------------------===// @@ -26,14 +26,14 @@ struct RegisteredLoggingContext; class ColumnDataCollection; struct ColumnDataScanState; class MemoryStream; -struct LogStorageConfig; +struct LogSinkConfig; class CSVWriter; struct CSVWriterState; class BufferedFileWriter; struct CSVWriterOptions; struct CSVReaderOptions; -//! Logging storage can store entries normalized or denormalized. This enum describes what a single table/file/etc +//! Logging sink can store entries normalized or denormalized. This enum describes what a single table/file/etc //! contains enum class LoggingTargetTable : uint8_t { ALL_LOGS, // Denormalized: log entries consisting of both the full log entry and the context @@ -41,11 +41,11 @@ enum class LoggingTargetTable : uint8_t { LOG_CONTEXTS, // Normalized: contains only the log contexts }; -class LogStorageScanState { +class LogSinkScanState { public: - explicit LogStorageScanState(LoggingTargetTable table_p) : table(table_p) { + explicit LogSinkScanState(LoggingTargetTable table_p) : table(table_p) { } - virtual ~LogStorageScanState() = default; + virtual ~LogSinkScanState() = default; template TARGET &Cast() { @@ -61,14 +61,14 @@ class LogStorageScanState { LoggingTargetTable table; }; -// Interface for Log Storage -class LogStorage { +// Interface for Log Sink +class LogSink { public: - DUCKDB_API explicit LogStorage() { + DUCKDB_API explicit LogSink() { } - DUCKDB_API virtual ~LogStorage() = default; + DUCKDB_API virtual ~LogSink() = default; - virtual const string GetStorageName() = 0; + virtual const string GetSinkName() = 0; static vector GetSchema(LoggingTargetTable table); static vector GetColumnNames(LoggingTargetTable table); @@ -87,9 +87,9 @@ class LogStorage { return false; } // Reading interface 1: basic single-threaded scan - DUCKDB_API virtual unique_ptr CreateScanState(LoggingTargetTable table) const; - DUCKDB_API virtual bool Scan(LogStorageScanState &state, DataChunk &result) const; - DUCKDB_API virtual void InitializeScan(LogStorageScanState &state) const; + DUCKDB_API virtual unique_ptr CreateScanState(LoggingTargetTable table) const; + DUCKDB_API virtual bool Scan(LogSinkScanState &state, DataChunk &result) const; + DUCKDB_API virtual void InitializeScan(LogSinkScanState &state) const; //! The number of rows a scan of the table produces, if known (used for progress reporting) DUCKDB_API virtual optional_idx GetScanRowCount(LoggingTargetTable table) const; @@ -101,14 +101,14 @@ class LogStorage { DUCKDB_API virtual void UpdateConfig(DatabaseInstance &db, case_insensitive_map_t &config); }; -//! The buffering Log storage implements a buffering mechanism around the Base LogStorage class. It implements some -//! general features that most log storages will need. -class BufferingLogStorage : public LogStorage { +//! The buffering Log sink implements a buffering mechanism around the Base LogSink class. It implements some +//! general features that most log sinks will need. +class BufferingLogSink : public LogSink { public: - explicit BufferingLogStorage(DatabaseInstance &db_p, idx_t buffer_size, bool normalize); - ~BufferingLogStorage() override; + explicit BufferingLogSink(DatabaseInstance &db_p, idx_t buffer_size, bool normalize); + ~BufferingLogSink() override; - /// (Partially) Implements LogStorage API + /// (Partially) Implements LogSink API //! Write out the entry to the buffers void WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type, const string &log_message, @@ -119,11 +119,11 @@ class BufferingLogStorage : public LogStorage { void FlushAll() final; //! Flushes buffer for a specific table void Flush(LoggingTargetTable table) final; - //! Truncates log storage: both buffers and persistent storage (if applicable) + //! Truncates log sink: both buffers and persistent storage (if applicable) void Truncate() override; - //! Apply a new log storage configuration + //! Apply a new log sink configuration void UpdateConfig(DatabaseInstance &db, case_insensitive_map_t &config) override; - //! Returns whether the table is enabled for this storage + //! Returns whether the table is enabled for this sink bool IsEnabled(LoggingTargetTable table) override; protected: @@ -144,7 +144,7 @@ class BufferingLogStorage : public LogStorage { void FlushAllInternal(); //! Flushes one of the tables void FlushInternal(LoggingTargetTable table); - //! Whether a specific table is available in the log storage + //! Whether a specific table is available in the log sink bool IsEnabledInternal(LoggingTargetTable table); idx_t GetBufferLimit() const; @@ -175,23 +175,23 @@ class BufferingLogStorage : public LogStorage { bool flush_contexts_on_next_entry_flush = false; }; -//! The CSVLogStorage implements an additional layer on the BufferingLogStorage which will handle converting the log +//! The CSVLogSink implements an additional layer on the BufferingLogSink which will handle converting the log //! entries and contexts to CSV lines. It provides functionality to write log data in CSV format with automatic type //! casting and configuration of CSV writers. This class serves as a base for both file-based and stdout-based CSV //! logging. -class CSVLogStorage : public BufferingLogStorage { +class CSVLogSink : public BufferingLogSink { public: - explicit CSVLogStorage(DatabaseInstance &db, bool normalize, idx_t buffer_size); - ~CSVLogStorage() override; + explicit CSVLogSink(DatabaseInstance &db, bool normalize, idx_t buffer_size); + ~CSVLogSink() override; protected: - /// Implement the BufferingLogStorage interface + /// Implement the BufferingLogSink interface //! Flushes the Chunk to the CSV writers void FlushChunk(LoggingTargetTable table, DataChunk &chunk) final; //! Resets all buffers and state void ResetAllBuffers() override; - //! Implements CSVLogStorage specific config handling + //! Implements CSVLogSink specific config handling void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) override; /// Interface to child classes @@ -232,15 +232,15 @@ class CSVLogStorage : public BufferingLogStorage { unique_ptr reader_options; }; -//! Implements a stdout-based log storage using log lines written in CSV format to allow for easy parsing of the log +//! Implements a stdout-based log sink using log lines written in CSV format to allow for easy parsing of the log //! messages Note that this only supports denormalized logging since there is only 1 practical output stream. -class StdOutLogStorage : public CSVLogStorage { +class StdOutLogSink : public CSVLogSink { public: - explicit StdOutLogStorage(DatabaseInstance &db); - ~StdOutLogStorage() override; + explicit StdOutLogSink(DatabaseInstance &db); + ~StdOutLogSink() override; - const string GetStorageName() override { - return "StdOutLogStorage"; + const string GetSinkName() override { + return "StdOutLogSink"; } private: @@ -251,19 +251,19 @@ class StdOutLogStorage : public CSVLogStorage { StdOutWriteStream stdout_stream; }; -//! FileLogStorage implements a file-based logging system in CSV format. -//! It implements CSVLogStorage to provide persistent log storage in CSV files. The FileLogStorage can operate in +//! FileLogSink implements a file-based logging system in CSV format. +//! It implements CSVLogSink to provide persistent log sink in CSV files. The FileLogSink can operate in //! normalized (separate files for entries and contexts) or denormalized mode (single file) -class FileLogStorage : public CSVLogStorage { +class FileLogSink : public CSVLogSink { public: - explicit FileLogStorage(DatabaseInstance &db); - ~FileLogStorage() override; + explicit FileLogSink(DatabaseInstance &db); + ~FileLogSink() override; - const string GetStorageName() override { - return "FileLogStorage"; + const string GetSinkName() override { + return "FileLogSink"; } - /// Implement LogStorage interface + /// Implement LogSink interface //! Truncates the csv files void Truncate() override; @@ -272,13 +272,13 @@ class FileLogStorage : public CSVLogStorage { LoggingTargetTable table) override; protected: - /// Implement CSVLogStorage interface + /// Implement CSVLogSink interface - //! Handles the config related to the FileLogStorage + //! Handles the config related to the FileLogSink void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) override; //! Lazily initializes the CSV files before first flush void BeforeFlush(LoggingTargetTable table, DataChunk &chunk) override; - //! Calls `Sync` on the FileWriters to ensure a LogStorage Flush is flushed to disk immediately + //! Calls `Sync` on the FileWriters to ensure a LogSink Flush is flushed to disk immediately void AfterFlush(LoggingTargetTable table, DataChunk &chunk) override; private: @@ -316,34 +316,34 @@ class FileLogStorage : public CSVLogStorage { }; //! State for scanning the in memory buffers -class InMemoryLogStorageScanState : public LogStorageScanState { +class InMemoryLogSinkScanState : public LogSinkScanState { public: - explicit InMemoryLogStorageScanState(LoggingTargetTable table); - ~InMemoryLogStorageScanState() override; + explicit InMemoryLogSinkScanState(LoggingTargetTable table); + ~InMemoryLogSinkScanState() override; ColumnDataScanState scan_state; }; -//! The InMemoryLogStorage implements a log storage that is backed by ColumnDataCollection's. It only support normalized +//! The InMemoryLogSink implements a log sink that is backed by ColumnDataCollection's. It only support normalized //! mode and support a basic single-threaded scan. TODO: improve? -class InMemoryLogStorage : public BufferingLogStorage { +class InMemoryLogSink : public BufferingLogSink { public: - explicit InMemoryLogStorage(DatabaseInstance &db); - ~InMemoryLogStorage() override; + explicit InMemoryLogSink(DatabaseInstance &db); + ~InMemoryLogSink() override; - const string GetStorageName() override { - return "InMemoryLogStorage"; + const string GetSinkName() override { + return "InMemoryLogSink"; } - //! Implement LogStorage Single-threaded scan interface + //! Implement LogSink Single-threaded scan interface bool CanScan(LoggingTargetTable table) override; - unique_ptr CreateScanState(LoggingTargetTable table) const override; - bool Scan(LogStorageScanState &state, DataChunk &result) const override; - void InitializeScan(LogStorageScanState &state) const override; + unique_ptr CreateScanState(LoggingTargetTable table) const override; + bool Scan(LogSinkScanState &state, DataChunk &result) const override; + void InitializeScan(LogSinkScanState &state) const override; optional_idx GetScanRowCount(LoggingTargetTable table) const override; protected: - /// Implement BufferingLogStorage interface + /// Implement BufferingLogSink interface //! Flushes a chunk to the corresponding ColumnDataCollection void FlushChunk(LoggingTargetTable table, DataChunk &chunk) override; @@ -354,7 +354,7 @@ class InMemoryLogStorage : public BufferingLogStorage { //! Helper function to get the buffer ColumnDataCollection &GetBuffer(LoggingTargetTable table) const; - map> log_storage_buffers; + map> log_sink_buffers; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/logging/logger.hpp b/src/duckdb/src/include/duckdb/logging/logger.hpp index db96d9d72..980237f4e 100644 --- a/src/duckdb/src/include/duckdb/logging/logger.hpp +++ b/src/duckdb/src/include/duckdb/logging/logger.hpp @@ -19,9 +19,10 @@ class DatabaseInstance; class DataChunk; class LogManager; class ColumnDataCollection; +class Context; class ThreadContext; class FileOpener; -class LogStorage; +class LogSink; class ExecutionContext; struct FileHandle; @@ -83,6 +84,7 @@ class Logger { DUCKDB_API static Logger &Get(const ThreadContext &thread_context); DUCKDB_API static Logger &Get(const ExecutionContext &execution_context); DUCKDB_API static Logger &Get(const ClientContext &client_context); + DUCKDB_API static Logger &Get(const Context &context); DUCKDB_API static Logger &Get(const FileOpener &opener); DUCKDB_API static Logger &Get(const DatabaseInstance &db); DUCKDB_API static Logger &Get(const shared_ptr &logger); diff --git a/src/duckdb/src/include/duckdb/logging/logging.hpp b/src/duckdb/src/include/duckdb/logging/logging.hpp index 2631046a1..49b9dff60 100644 --- a/src/duckdb/src/include/duckdb/logging/logging.hpp +++ b/src/duckdb/src/include/duckdb/logging/logging.hpp @@ -1,7 +1,7 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/logging/log_storage.hpp +// duckdb/logging/logging.hpp // // //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/main/attached_database.hpp b/src/duckdb/src/include/duckdb/main/attached_database.hpp index 59fa7ee51..7287d53b0 100644 --- a/src/duckdb/src/include/duckdb/main/attached_database.hpp +++ b/src/duckdb/src/include/duckdb/main/attached_database.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/error_data.hpp" #include "duckdb/common/optional.hpp" #include "duckdb/common/prefetched_file_data.hpp" #include "duckdb/main/config.hpp" @@ -143,7 +144,17 @@ class AttachedDatabase : public CatalogEntry, public enable_shared_from_this GetStorageExtension() { return storage_extension; diff --git a/src/duckdb/src/include/duckdb/main/capi/capi_function_signature.hpp b/src/duckdb/src/include/duckdb/main/capi/capi_function_signature.hpp index 74dcaee5b..a3559acc6 100644 --- a/src/duckdb/src/include/duckdb/main/capi/capi_function_signature.hpp +++ b/src/duckdb/src/include/duckdb/main/capi/capi_function_signature.hpp @@ -8,7 +8,6 @@ #pragma once -#include "duckdb/common/string_util.hpp" #include "duckdb/function/function.hpp" #include @@ -25,11 +24,10 @@ struct CAPIFunctionSignature { SetParameters(signature, std::move(parameters)); } - //! Adds a positional-only parameter named "col", after the existing positional-only ones + //! Adds a positional-only parameter declared without a name, after the existing positional-only ones static void AddPositionalOnly(FunctionSignature &signature, LogicalType type) { - auto name = Identifier(StringUtil::Format("col%d", signature.GetPositionalOnlyParameterCount())); AddParameter(signature, - FunctionParameter(std::move(name), std::move(type), {}, FunctionParameterKind::POSITIONAL_ONLY)); + FunctionParameter::Unnamed(std::move(type), signature.GetPositionalOnlyParameterCount())); } //! Replaces the "*args" by one of the given type, or removes it if the type is INVALID. A named argument the 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 57312542b..f0fc3cf26 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 @@ -1496,6 +1496,20 @@ typedef struct { (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_ERROR(*duckdb_v2_table_function_add_virtual_column) + (duckdb_v2_table_function_handle function, DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_bind_data) + (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_global_state) + (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_user_data) + (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_set) + (duckdb_v2_table_function_metrics_info_handle info, const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_metrics_callback) + (duckdb_v2_table_function_handle function, duckdb_v2_table_function_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_check_statistics) (duckdb_v2_context_handle context, duckdb_v2_expression_handle expression, duckdb_v2_stats_handle stats, DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, duckdb_v2_error_info_handle *err); @@ -2192,6 +2206,12 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_query_metrics_node_get_metric_value = duckdb_v2_query_metrics_node_get_metric_value; result.duckdb_v2_query_metrics_node_get_name = duckdb_v2_query_metrics_node_get_name; result.duckdb_v2_statement_add_collection = duckdb_v2_statement_add_collection; + result.duckdb_v2_table_function_add_virtual_column = duckdb_v2_table_function_add_virtual_column; + result.duckdb_v2_table_function_metrics_get_bind_data = duckdb_v2_table_function_metrics_get_bind_data; + result.duckdb_v2_table_function_metrics_get_global_state = duckdb_v2_table_function_metrics_get_global_state; + result.duckdb_v2_table_function_metrics_get_user_data = duckdb_v2_table_function_metrics_get_user_data; + result.duckdb_v2_table_function_metrics_set = duckdb_v2_table_function_metrics_set; + result.duckdb_v2_table_function_set_metrics_callback = duckdb_v2_table_function_set_metrics_callback; result.duckdb_v2_expression_check_statistics = duckdb_v2_expression_check_statistics; result.duckdb_v2_stats_create = duckdb_v2_stats_create; result.duckdb_v2_stats_destroy = duckdb_v2_stats_destroy; diff --git a/src/duckdb/src/include/duckdb/main/client_config.hpp b/src/duckdb/src/include/duckdb/main/client_config.hpp index 8c3aa3067..c1229100e 100644 --- a/src/duckdb/src/include/duckdb/main/client_config.hpp +++ b/src/duckdb/src/include/duckdb/main/client_config.hpp @@ -44,21 +44,9 @@ struct ClientConfig { //! The format to print query profiling information in (default: query_tree), if enabled. //! This is the profiler format name passed to QueryProfiler::CreateProfiler. string profiler_print_format = "query_tree"; - //! The file to save query profiling information to, instead of printing it to the console - //! (empty = print to console) - string profiler_save_location; - //! Settings that are passed to the renderer of the profiler output (e.g. 'maximum_render_width' for the text - //! renderer). Settings that are not recognized by the active renderer are ignored. - unordered_map profiling_renderer_settings; //! system-wide progress bar disable. const char *system_progress_bar_disable_reason = nullptr; - //! If the progress bar is enabled or not. - bool enable_progress_bar = false; - //! If the print of the progress bar is enabled - bool print_progress_bar = true; - //! The wait time before showing the progress bar - int wait_time = 2000; //! Force parallelism of small tables, used for testing bool verify_parallelism = false; @@ -79,10 +67,6 @@ struct ClientConfig { //! Callback to create a progress bar display progress_bar_display_create_func_t display_create_func = nullptr; - //! The profiling coverage. SELECT is the default behavior, and ALL emits profiling information for all operator - //! types. - ProfilingCoverage profiling_coverage = ProfilingCoverage::SELECT; - //! Generic options LocalUserSettings user_settings; diff --git a/src/duckdb/src/include/duckdb/main/client_context_state.hpp b/src/duckdb/src/include/duckdb/main/client_context_state.hpp index 7e74d8883..0a704bcd6 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/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 8e611c76b..1c8804d43 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -115,50 +115,23 @@ struct DBConfigOptions { bool use_temporary_directory = true; //! Directory to store temporary structures that do not fit in memory string temporary_directory; - //! Whether or not to invoke filesystem trim on free blocks after checkpoint. This will reclaim - //! space for sparse files, on platforms that support it. - bool trim_free_blocks = false; - //! Record timestamps of buffer manager unpin() events. Usable by custom eviction policies. - bool buffer_manager_track_eviction_timestamps = false; - //! Force checkpoint when CHECKPOINT is called or on shutdown, even if no changes have been made - bool force_checkpoint = false; - //! Run a checkpoint on successful shutdown and delete the WAL, to leave only a single database file behind - bool checkpoint_on_shutdown = true; //! Serialize the metadata on checkpoint with compatibility for a given DuckDB version. StorageCompatibility storage_compatibility = StorageCompatibility::Default(); //! Initialize the database with the standard set of DuckDB functions //! You should probably not touch this unless you know what you are doing bool initialize_default_database = true; - //! Enable mbedtls explicitly (overrides OpenSSL if available) - bool force_mbedtls = false; //! The set of disabled optimizers (default empty) set disabled_optimizers; - //! Force a specific schema for VARIANT shredding - LogicalType force_variant_shredding = LogicalType::INVALID; //! Database configuration variable default values; case_insensitive_map_t set_variable_defaults; - //! Additional directories to store extension binaries in - vector extension_directories; - //! Debug setting - how to initialize blocks in the storage layer when allocating - DebugInitialize debug_initialize = DebugInitialize::NO_INITIALIZE; - //! Debug setting - how to verify ORDER BY results (e.g. by rewriting ORDER BY into create_sort_key) - DebugOrderVerification debug_order_verification = DebugOrderVerification::NONE; //! The set of user-provided options identifier_map_t user_options; //! The set of unrecognized (other) options identifier_map_t unrecognized_options; - //! If bulk deallocation larger than this occurs, flush outstanding allocations (1 << 30, ~1GB) - idx_t allocator_bulk_deallocation_flush_threshold = 536870912ULL; - //! Delta Only! - Fall back to recognizing Variant columns structurally - bool variant_legacy_encoding = false; - //! Metadata from DuckDB callers - string custom_user_agent; //! 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; - //! Whether or not to abort if a serialization exception is thrown during WAL playback (when reading truncated WAL) - bool abort_on_wal_failure = false; //! Paths that are explicitly allowed, even if enable_external_access is false unordered_set allowed_paths; //! Environment variables the embedder configures itself from, readable with OSUtil::GetEnvUnrestricted @@ -373,6 +346,8 @@ struct DBConfig { 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(const Identifier &key, optional_ptr option, + Value &result) const; //! The opener (if any) is used to expand "~" using the connection-specific home_directory bool CanAccessFile(const string &path, FileType type, optional_ptr opener = nullptr); diff --git a/src/duckdb/src/include/duckdb/main/context.hpp b/src/duckdb/src/include/duckdb/main/context.hpp index 2c4db4f2c..b9a7849b0 100644 --- a/src/duckdb/src/include/duckdb/main/context.hpp +++ b/src/duckdb/src/include/duckdb/main/context.hpp @@ -54,6 +54,8 @@ class Context { //! Null-safe variants for optional services DUCKDB_API static optional_ptr TryGetClientContext(optional_ptr services); DUCKDB_API static optional_ptr TryGetQueryProfiler(optional_ptr services); + //! 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; //! Whether the query of the client was interrupted (always false for database-wide services) diff --git a/src/duckdb/src/include/duckdb/main/database.hpp b/src/duckdb/src/include/duckdb/main/database.hpp index e40a13320..3670264c4 100644 --- a/src/duckdb/src/include/duckdb/main/database.hpp +++ b/src/duckdb/src/include/duckdb/main/database.hpp @@ -91,8 +91,8 @@ class DatabaseInstance : public enable_shared_from_this { DUCKDB_API SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) const; - //! Creates database-wide services (settings, logging, metrics, file system) - DUCKDB_API shared_ptr Services(); + //! The database-wide services (settings, logging, metrics, file system) - owned by the database + DUCKDB_API Context &GetContext(); DUCKDB_API shared_ptr GetEncryptionUtil(bool read_only = false); shared_ptr GetMbedTLSUtil(bool force_mbedtls) const; @@ -125,6 +125,8 @@ class DatabaseInstance : public enable_shared_from_this { unique_ptr connection_manager; unique_ptr extension_manager; ValidChecker db_validity; + //! Declared before the file systems: their openers reference it + unique_ptr services; unique_ptr db_file_system; unique_ptr local_db_file_system; unique_ptr log_manager; 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 3d8792f01..08caecc27 100644 --- a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp @@ -22,7 +22,7 @@ class DatabaseInstance; class DatabaseFileOpener : public FileOpener { public: - explicit DatabaseFileOpener(DatabaseInstance &db_p) : db(db_p), context(db_p.Services()) { + explicit DatabaseFileOpener(DatabaseInstance &db_p) : db(db_p), context(db_p.GetContext()) { } Logger &GetLogger() const override { @@ -38,7 +38,7 @@ class DatabaseFileOpener : public FileOpener { } Context &TryGetContext() override { - return *context; + return context; } optional_ptr TryGetDatabase() override { @@ -50,7 +50,7 @@ class DatabaseFileOpener : public FileOpener { private: DatabaseInstance &db; - shared_ptr context; + Context &context; }; class DatabaseFileSystem : public OpenerFileSystem { diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index b79f5f3cc..50319b328 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -1314,6 +1314,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"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"}, @@ -1463,6 +1464,7 @@ static constexpr ExtensionEntry EXTENSION_SETTINGS[] = { {"pg_connection_limit", "postgres_scanner"}, {"pg_debug_show_queries", "postgres_scanner"}, {"pg_enable_filter_pushdown", "postgres_scanner"}, + {"pg_enable_remote_pushdown", "postgres_scanner"}, {"pg_idle_in_transaction_timeout_millis", "postgres_scanner"}, {"pg_null_byte_replacement", "postgres_scanner"}, {"pg_numeric_as_varchar", "postgres_scanner"}, @@ -1529,6 +1531,9 @@ static constexpr ExtensionEntry EXTENSION_SETTINGS[] = { {"sqlite_all_varchar", "sqlite_scanner"}, {"sqlite_debug_show_queries", "sqlite_scanner"}, {"sqlite_disable_multithreaded_scans", "sqlite_scanner"}, + {"sqlite_enable_filter_pushdown", "sqlite_scanner"}, + {"sqlite_enable_remote_pushdown", "sqlite_scanner"}, + {"sqlite_keep_database_open", "sqlite_scanner"}, {"timezone", "icu"}, {"ui_local_port", "ui"}, {"ui_polling_interval", "ui"}, diff --git a/src/duckdb/src/include/duckdb/main/extension_helper.hpp b/src/duckdb/src/include/duckdb/main/extension_helper.hpp index e5f2470fb..6a7747763 100644 --- a/src/duckdb/src/include/duckdb/main/extension_helper.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_helper.hpp @@ -96,6 +96,11 @@ struct ExtensionInstallOptions { bool throw_on_origin_mismatch = false; }; +struct InstalledExtensionDirectory { + string path; + string repository; +}; + class ExtensionHelper { public: static void LoadAllExtensions(DuckDB &db); @@ -141,9 +146,14 @@ class ExtensionHelper { static string ExtensionDirectory(ClientContext &context); static string ExtensionDirectory(DatabaseInstance &db, FileSystem &fs); - // Get all extension directory paths + // Get all extension directory paths (flat) static vector GetExtensionDirectoryPath(ClientContext &context); static vector GetExtensionDirectoryPath(DatabaseInstance &db, FileSystem &fs); + + // Get all extension directory paths, including those in the 'repositories' subdirectory + static vector GetInstalledExtensionDirectories(ClientContext &context); + static vector GetInstalledExtensionDirectories(DatabaseInstance &db, FileSystem &fs); + //! Whether a file in an extension directory is an installed extension, and not the temporary file of an install static bool IsInstalledExtensionFile(const string &path); diff --git a/src/duckdb/src/include/duckdb/main/extension_install_info.hpp b/src/duckdb/src/include/duckdb/main/extension_install_info.hpp index 8047e9293..18a80b7fe 100644 --- a/src/duckdb/src/include/duckdb/main/extension_install_info.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_install_info.hpp @@ -27,16 +27,21 @@ enum class ExtensionInstallMode : uint8_t { NOT_INSTALLED = 4 }; -//! Whether the user has opted in to adding external extension repositories. This is a one-way ratchet: once FORBIDDEN -//! it cannot be moved back within a session. UNDECIDED (the default) blocks adding new repositories, but extensions -//! from repositories that were already created can still be installed and loaded +//! Which external extension repositories can be added, and which are trusted. This is a one-way ratchet: while the +//! database is running the setting can only tighten (HOSTS -> ALLOWED -> HOSTS_ONLY -> FORBIDDEN), never loosen. +//! HOSTS (the default) allows the repositories resolved from their host (CREATE EXTENSION REPOSITORY without a +//! prefix) and blocks adding repositories by prefix until the user opts in with ALLOWED; extensions from repositories +//! that were already created can still be installed and loaded enum class ExtensionRepositoryAccess : uint8_t { - //! No decision has been made yet - adding repositories fails until the user opts in explicitly - UNDECIDED = 0, + //! A repository resolved from its host can be added; adding one by prefix fails until the user opts in explicitly + HOSTS = 0, //! Adding external repositories is allowed ALLOWED = 1, //! Adding external repositories is forbidden - this cannot be undone in the same session - FORBIDDEN = 2 + FORBIDDEN = 2, + //! Only repositories resolved from their host can be added, and only those are trusted: a repository added by + //! prefix is distrusted like under FORBIDDEN + HOSTS_ONLY = 3 }; //! The type of a repository determines which public keys are trusted to sign the extensions that it serves. Keys of @@ -142,6 +147,9 @@ struct ExtensionRepository { vector public_keys; //! Which public keys are trusted to sign the extensions of this repository ExtensionRepositoryType type = ExtensionRepositoryType::CORE; + //! (optional) The host the repository was resolved from (CREATE EXTENSION REPOSITORY without a prefix: the + //! name); empty for a repository added by prefix + string host; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/extension_manager.hpp b/src/duckdb/src/include/duckdb/main/extension_manager.hpp index d45cc4e4b..7ab0c2dc3 100644 --- a/src/duckdb/src/include/duckdb/main/extension_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_manager.hpp @@ -25,6 +25,7 @@ class ExtensionInfo { atomic is_loaded; unique_ptr install_info; unique_ptr load_info; + string file_path; }; class ExtensionActiveLoad { @@ -48,7 +49,7 @@ class ExtensionActiveLoad { Identifier alias; public: - void FinishLoad(ExtensionInstallInfo &install_info); + void FinishLoad(ExtensionInstallInfo &install_info, const string &file_path = string()); void LoadFail(const ErrorData &error); }; 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 3cc882f3c..5f5945e5f 100644 --- a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp @@ -22,6 +22,14 @@ class FileSystem; //! locally unique name, a url prefix from which extensions are downloaded and one or more public keys that are trusted //! to sign the extensions that are served by the repository. The keys of a trusted repository are only trusted for the //! extensions that are installed from that repository. +//! What `CREATE EXTENSION REPOSITORY ` resolved the name to, from the host's metadata file +struct ExtensionRepositoryResolution { + //! The host: the normalized name + string host; + //! The repository url (prefix), as the host names it + string url; +}; + class ExtensionRepositoryManager { public: //! The file extension used for the stored repository definitions @@ -31,18 +39,23 @@ class ExtensionRepositoryManager { static constexpr const char *FILE_EXTENSION = ".duckdb_extension.repo.json"; //! The version of the repository file format static constexpr const idx_t FORMAT_VERSION = 1; - //! The metadata file that a repository serves under its prefix, describing its trusted signing keys + //! The metadata file: `{"version": 1, "repository_url": "", "signature_keys": [...]}`. Served under a prefix + //! it carries the keys WITH PREFIX pins. Served by a publisher's host (CREATE EXTENSION REPOSITORY ) only its + //! url is read: it names the prefix. A repository whose prefix is its host serves one file for both static constexpr const char *METADATA_FILE = ".well-known/duckdb-extension-repo.json"; public: //! The directory in which the trusted extension repositories are stored static string GetRepositoryDirectory(DatabaseInstance &db, FileSystem &fs); - //! Store a new trusted repository on disk. If the repository has no public keys, they are fetched from the - //! repository prefix and pinned. Returns the repository as it was stored + //! Store a new trusted repository on disk, from what was requested: a name, a prefix and optionally keys - or a + //! name alone, which is then the host that names the prefix (the 'hosts' default of + //! allow_extension_repositories permits that form; keys cannot be given with it). Keys that were not given are + //! fetched from the prefix and pinned. The conflict is decided before anything is fetched. Returns the repository + //! as it was stored, `host` set when it was resolved from one static ExtensionRepository CreateRepository(DatabaseInstance &db, FileSystem &fs, optional_ptr context, - const ExtensionRepository &repository, OnCreateConflict on_conflict); + const ExtensionRepository &requested, OnCreateConflict on_conflict); //! Remove a trusted repository from disk static void DropRepository(DatabaseInstance &db, FileSystem &fs, const string &name, OnEntryNotFound on_entry_not_found); @@ -55,11 +68,16 @@ class ExtensionRepositoryManager { //! Repository names are case insensitive and are used as file names - restrict them to a safe character set static string NormalizeRepositoryName(const string &name); static bool TryNormalizeRepositoryName(const string &name, string &result); + //! Whether a name is a host on the public internet, the only kind of name resolved without a prefix + static bool IsHostName(const string &name); //! Whether the user has opted in to adding external extension repositories static ExtensionRepositoryAccess GetAccess(DatabaseInstance &db); - //! Whether the repositories that were already created are trusted: their extensions can be installed and loaded + //! Whether any of the repositories that were already created may be trusted: their extensions can be installed and + //! loaded. Under 'hosts_only' only some are, see TrustsRepository static bool TrustsExistingRepositories(DatabaseInstance &db); + //! Whether this repository is trusted: under 'hosts_only' only a repository resolved from its host is + static bool TrustsRepository(DatabaseInstance &db, const ExtensionRepository &repository); //! Parse the access value of the allow_extension_repositories setting (throws on an invalid value) static ExtensionRepositoryAccess ParseAccess(const string &value); //! The string representation of an access value, as used by the allow_extension_repositories setting @@ -70,6 +88,9 @@ class ExtensionRepositoryManager { static vector FetchPublicKeys(DatabaseInstance &db, optional_ptr context, const string &prefix); + //! The keys in a metadata file's contents (see FetchPublicKeys); `metadata_path` names the file in errors + static vector ParsePublicKeys(const string &contents, const string &metadata_path); + //! The sha256 fingerprint of a public key, used to compare a key against the fingerprint published by a repository static string GetPublicKeyFingerprint(const string &compact_key); @@ -83,8 +104,15 @@ class ExtensionRepositoryManager { static string ToPEMPublicKey(const string &compact_key); private: + //! Resolve `CREATE EXTENSION REPOSITORY ` (no prefix): the name is the publisher's host, and the metadata + //! file it serves (https:///METADATA_FILE) names the repository url. Only the url is taken from the host; + //! the keys come from the prefix, as with WITH PREFIX. Called by CreateRepository after the access and conflict + //! checks + static ExtensionRepositoryResolution + 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); + static void CheckCanCreate(DatabaseInstance &db, 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_util.hpp b/src/duckdb/src/include/duckdb/main/http/http_util.hpp index 79217348c..04d350d90 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_util.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_util.hpp @@ -71,6 +71,9 @@ struct HTTPParams { public: void Initialize(optional_ptr opener); DUCKDB_API idx_t GetTransportReuseDomain() const; + //! Require server certificate verification for the requests made with these parameters, whatever the settings and + //! secrets they were initialized from said. The provider recaptures its connection-reuse domain from the new values + DUCKDB_API void RequireServerCertificateVerification(); template TARGET &Cast() { diff --git a/src/duckdb/src/include/duckdb/main/parse_iterator.hpp b/src/duckdb/src/include/duckdb/main/parse_iterator.hpp index b283c5c99..d3328bf56 100644 --- a/src/duckdb/src/include/duckdb/main/parse_iterator.hpp +++ b/src/duckdb/src/include/duckdb/main/parse_iterator.hpp @@ -82,6 +82,8 @@ class ParseIterator { optional_ptr held_lock; //! Tokenized view of `sql` and its current position. Populated once on the first Peek. unique_ptr token_iterator; + //! Byte offset in `sql` where the next statement's text starts: just past the previous one. + idx_t next_statement_offset = 0; //! Single-statement buffer holding the result of the most recent Peek. Cleared by //! GetStatement. unique_ptr current_statement; diff --git a/src/duckdb/src/include/duckdb/main/prepared_statement_data.hpp b/src/duckdb/src/include/duckdb/main/prepared_statement_data.hpp index 80d7618a8..4b2fde3e2 100644 --- a/src/duckdb/src/include/duckdb/main/prepared_statement_data.hpp +++ b/src/duckdb/src/include/duckdb/main/prepared_statement_data.hpp @@ -33,6 +33,8 @@ class PreparedStatementData { //! The physical plan. unique_ptr physical_plan; + //! The prepared statement whose physical plan is referenced by this plan - keeps that plan alive + shared_ptr reused_statement; //! The result names of the transaction vector names; @@ -59,6 +61,15 @@ class PreparedStatementData { DUCKDB_API bool TryGetType(const Identifier &identifier, LogicalType &result); }; +//! An EXECUTE statement with the prepared statement and the parameter values it is executed with resolved +struct PreparedExecution { + shared_ptr prepared; + identifier_map_t bind_values; + //! Whether the prepared statement has to be planned again instead of re-using its physical plan + bool rebind = false; + idx_t parameter_count = 0; +}; + DUCKDB_API bool CheckCatalogIdentity(ClientContext &context, const Identifier &catalog_name, StatementProperties::CatalogIdentity catalog_identity); diff --git a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp index f8e6d860b..50ee83f70 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp @@ -105,6 +105,9 @@ class SecretManager { //! Static Helper Functions DUCKDB_API static SecretManager &Get(ClientContext &context); DUCKDB_API static SecretManager &Get(DatabaseInstance &db); + //! Throws when enable_external_access is false; type and provider only decorate the message and may be empty + DUCKDB_API static void ThrowIfSecretCreationDisabled(DatabaseInstance &db, const Identifier &type, + const Identifier &provider); // Initialize the secret manager with the DB instance DUCKDB_API void Initialize(DatabaseInstance &db); diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index ebdda19c2..fb52ac070 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -21,6 +21,12 @@ struct IsSettingList : std::false_type {}; template struct IsSettingList> : std::true_type {}; +template +struct IsSettingMap : std::false_type {}; + +template +struct IsSettingMap> : std::true_type {}; + struct Settings { template static typename OP::RETURN_TYPE Get(const SOURCE &source) { @@ -82,6 +88,17 @@ struct Settings { return result; } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + T result; + for (auto &entry : MapValue::GetChildren(value)) { + auto &key_value = StructValue::GetChildren(entry); + result.emplace(FromValue(key_value[0]), + FromValue(key_value[1])); + } + return result; + } + //! Parses the default value of a setting template static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { @@ -115,6 +132,15 @@ struct Settings { } return result; } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + // only the empty map is supported as a default + if (!StringUtil::Equals(default_value, "{}")) { + throw InternalException("Default value \"%s\" of a map setting must be {}", default_value); + } + return T(); + } + //! Splits a list literal (e.g. "['a', 'b']") into its entries static vector SplitListDefault(const char *default_value); @@ -153,6 +179,17 @@ struct Settings { } return Value::LIST(SettingLogicalType(static_cast(nullptr)), std::move(children)); } + template + static Value ToSettingValue(const unordered_map &values) { + vector keys; + vector map_values; + for (auto &entry : values) { + keys.push_back(ToSettingValue(entry.first)); + map_values.push_back(ToSettingValue(entry.second)); + } + return Value::MAP(SettingLogicalType(static_cast(nullptr)), + SettingLogicalType(static_cast(nullptr)), std::move(keys), std::move(map_values)); + } //! The logical type of a setting value, selected by the (unused) pointer type static LogicalType SettingLogicalType(const string *) { @@ -240,9 +277,10 @@ struct AllocatorBulkDeallocationFlushThresholdSetting { 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 = "512.0 MiB"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct AllocatorFlushThresholdSetting { @@ -276,14 +314,16 @@ struct AllowExtensionRepositoriesSetting { using RETURN_TYPE = string; static constexpr const char *Name = "allow_extension_repositories"; static constexpr const char *Description = - "Whether custom trusted extension repositories are 'allowed', 'forbidden' (which also distrusts existing " - "repositories) or 'undecided' (the default: blocks adding new repositories, but keeps trusting existing ones). " - "While the database is running the setting can only move from 'undecided' to 'allowed' or 'forbidden', or from " - "'allowed' to 'forbidden'."; + "Which custom trusted extension repositories can be added, and which are trusted: 'hosts' (the default: a " + "repository named by its host can be added with CREATE EXTENSION REPOSITORY , adding one by prefix needs " + "'allowed', existing repositories stay trusted), 'allowed' (repositories can be added by host or by prefix), " + "'hosts_only' (only repositories resolved from their host can be added, and only those are trusted) or " + "'forbidden' (nothing can be added, and existing repositories are distrusted). While the database is running " + "the setting can only be tightened: 'hosts' -> 'allowed' -> 'hosts_only' -> 'forbidden'."; static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static constexpr const char *DefaultValue = "undecided"; + static constexpr const char *DefaultValue = "hosts"; static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); static void OnSet(SettingCallbackInfo &info, Value &input); @@ -539,6 +579,20 @@ struct AutoloadKnownExtensionsSetting { static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; +struct BufferManagerTrackEvictionTimestampsSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "buffer_manager_track_eviction_timestamps"; + static constexpr const char *Description = + "Record timestamps of buffer manager unpin() events. Usable by custom eviction policies."; + static constexpr const char *InputType = "BOOLEAN"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); +}; + struct CacheLocalFilesSetting { using RETURN_TYPE = bool; static constexpr const char *Name = "cache_local_files"; @@ -581,6 +635,19 @@ struct CheckpointOnDetachSetting { static void OnSet(SettingCallbackInfo &info, Value &input); }; +struct CheckpointOnShutdownSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "checkpoint_on_shutdown"; + static constexpr const char *Description = "Whether to run a checkpoint on successful shutdown and delete the WAL, " + "to leave only a single database file behind."; + static constexpr const char *InputType = "BOOLEAN"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "true"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct CheckpointThresholdSetting { using RETURN_TYPE = string; static constexpr const char *Name = "checkpoint_threshold"; @@ -589,9 +656,10 @@ struct CheckpointThresholdSetting { 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 = "16.0 MiB"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct CurrentDialectSetting { @@ -642,9 +710,10 @@ struct CustomUserAgentSetting { 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 = ""; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DebugAbortOnWalFailureSetting { @@ -655,9 +724,9 @@ struct DebugAbortOnWalFailureSetting { static constexpr const char *InputType = "BOOLEAN"; static constexpr bool IsDebug = true; 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 = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; struct DebugAsofIejoinSetting { @@ -717,9 +786,10 @@ struct DebugDeltaOnlyVariantEncodingEnabledSetting { static constexpr const char *InputType = "BOOLEAN"; static constexpr bool IsDebug = true; 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 = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DebugDisableOptimizerSetting { @@ -785,6 +855,19 @@ struct ForceBitpackingModeSetting { static void OnSet(SettingCallbackInfo &info, Value &input); }; +struct DebugForceCheckpointSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "debug_force_checkpoint"; + static constexpr const char *Description = + "Force a checkpoint when CHECKPOINT is called or on shutdown, even if no changes have been made."; + 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::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct DebugForceCommitFailureSetting { using RETURN_TYPE = bool; static constexpr const char *Name = "debug_force_commit_failure"; @@ -834,6 +917,19 @@ struct DebugForceFetchRowSetting { static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; +struct DebugForceFlushAppendFailureSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "debug_force_flush_append_failure"; + static constexpr const char *Description = "Force the commit-time flush of transaction-local storage to fail after " + "appending to the table. Can be used for testing commit error recovery."; + 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::GLOBAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct ForceMbedtlsUnsafeSetting { using RETURN_TYPE = bool; static constexpr const char *Name = "debug_force_mbedtls_unsafe"; @@ -841,9 +937,10 @@ struct ForceMbedtlsUnsafeSetting { static constexpr const char *InputType = "BOOLEAN"; static constexpr bool IsDebug = true; 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 = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DebugForceNoCrossProductSetting { @@ -880,9 +977,10 @@ struct ForceVariantShredding { static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = true; 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 = "INVALID"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DebugForceWalFsyncFailureSetting { @@ -898,6 +996,20 @@ struct DebugForceWalFsyncFailureSetting { static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; +struct DebugInitializeSetting { + using RETURN_TYPE = DebugInitialize; + static constexpr const char *Name = "debug_initialize"; + static constexpr const char *Description = "How to initialize blocks in the storage layer when allocating " + "(NO_INITIALIZE, DEBUG_ZERO_INITIALIZE or DEBUG_ONE_INITIALIZE)."; + static constexpr const char *InputType = "VARCHAR"; + static constexpr bool IsDebug = true; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "NO_INITIALIZE"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); +}; + struct DebugLocalFileSystemDelayMsSetting { using RETURN_TYPE = idx_t; static constexpr const char *Name = "debug_local_file_system_delay_ms"; @@ -918,9 +1030,10 @@ struct DebugOrderVerificationSetting { static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = true; 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 = "NONE"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DebugPhysicalTableScanExecutionStrategySetting { @@ -949,15 +1062,16 @@ struct DebugSkipCheckpointOnCommitSetting { }; struct DebugVerificationModeSetting { - using RETURN_TYPE = string; + using RETURN_TYPE = DebugVerificationMode; static constexpr const char *Name = "debug_verification_mode"; static constexpr const char *Description = "Toggle the verification mode."; static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = true; 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 = "NONE"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DebugVerificationProjectionSetting { @@ -1267,9 +1381,10 @@ struct DisabledCompressionMethodsSetting { 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 = ""; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DisabledFilesystemsSetting { @@ -1304,9 +1419,10 @@ struct DisabledOptimizersSetting { 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 = ""; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct DuckDBAPISetting { @@ -1489,11 +1605,10 @@ struct EnableProgressBarSetting { static constexpr const char *InputType = "BOOLEAN"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetLocal(ClientContext &context, const Value ¶meter); - static void ResetLocal(ClientContext &context); - static bool OnLocalSet(ClientContext &context, const Value &input); - static bool OnLocalReset(ClientContext &context); - static Value GetSetting(const ClientContext &context); + static constexpr const char *DefaultValue = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct EnableProgressBarPrintSetting { @@ -1504,9 +1619,10 @@ struct EnableProgressBarPrintSetting { static constexpr const char *InputType = "BOOLEAN"; 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 = "true"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct EnableViewDependenciesSetting { @@ -1591,9 +1707,10 @@ struct ExtensionDirectoriesSetting { 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 = "[]"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct ExtensionDirectorySetting { @@ -2068,11 +2185,11 @@ struct LoggingMode { static Value GetSetting(const ClientContext &context); }; -struct LoggingStorage { +struct LoggingSink { using RETURN_TYPE = string; - static constexpr const char *Name = "logging_storage"; + static constexpr const char *Name = "logging_sink"; static constexpr const char *Description = - "Set the logging storage, options are 'memory', 'stdout', 'file', ''."; + "Set the logging sink, options are 'memory', 'stdout', 'file', ''."; static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; @@ -2081,6 +2198,18 @@ struct LoggingStorage { static Value GetSetting(const ClientContext &context); }; +struct LoggingStorage { + using RETURN_TYPE = string; + static constexpr const char *Name = "logging_storage"; + static constexpr const char *Description = "Deprecated setting. Use logging_sink instead."; + static constexpr const char *InputType = "VARCHAR"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = true; + static void SetGlobal(DatabaseInstance *db, DBConfig &config, const Value ¶meter); + static void ResetGlobal(DatabaseInstance *db, DBConfig &config); + static Value GetSetting(const ClientContext &context); +}; + struct MatchRecognizeMaxStatesSetting { using RETURN_TYPE = idx_t; static constexpr const char *Name = "match_recognize_max_states"; @@ -2395,16 +2524,17 @@ struct ProduceArrowStringViewSetting { }; struct ProfilingCoverageSetting { - using RETURN_TYPE = string; + using RETURN_TYPE = ProfilingCoverage; static constexpr const char *Name = "profiling_coverage"; static constexpr const char *Description = "The profiling coverage, either SELECT (only SELECT queries) or ALL (all queries are profiled)."; 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 = "SELECT"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct ProfilingModeSetting { @@ -2428,9 +2558,10 @@ struct ProfilingOutputSetting { 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 = ""; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct ProfilingRendererSettingsSetting { @@ -2442,9 +2573,10 @@ struct ProfilingRendererSettingsSetting { static constexpr const char *InputType = "MAP(VARCHAR, 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 = "{}"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct ProgressBarTimeSetting { @@ -2455,9 +2587,10 @@ struct ProgressBarTimeSetting { static constexpr const char *InputType = "BIGINT"; 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 = "2000"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct ReadAheadDepthSetting { @@ -2703,6 +2836,19 @@ struct TrackedMetricsSetting { static void OnSet(SettingCallbackInfo &info, Value &input); }; +struct TrimFreeBlocksSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "trim_free_blocks"; + static constexpr const char *Description = "Whether to invoke filesystem trim on free blocks after checkpoint. " + "This reclaims space for sparse files, on platforms that support it."; + static constexpr const char *InputType = "BOOLEAN"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct UsernameSetting { using RETURN_TYPE = string; static constexpr const char *Name = "username"; diff --git a/src/duckdb/src/include/duckdb/main/valid_checker.hpp b/src/duckdb/src/include/duckdb/main/valid_checker.hpp index 219085455..52e8b0bbf 100644 --- a/src/duckdb/src/include/duckdb/main/valid_checker.hpp +++ b/src/duckdb/src/include/duckdb/main/valid_checker.hpp @@ -14,6 +14,7 @@ namespace duckdb { class AttachedDatabase; +class ErrorData; class DatabaseInstance; class MetaTransaction; @@ -26,6 +27,8 @@ class ValidChecker { DUCKDB_API static ValidChecker &Get(MetaTransaction &transaction); DUCKDB_API void Invalidate(string error); + //! Invalidate unless already invalidated, keeping the original error + DUCKDB_API void InvalidateIfValid(string error); DUCKDB_API bool IsInvalidated(); DUCKDB_API string InvalidatedMessage(); @@ -33,6 +36,8 @@ class ValidChecker { static bool IsInvalidated(T &o) { return Get(o).IsInvalidated(); } + //! Invalidate the instance after a fatal error, unless an attached database already handled it (ScopeFatalError) + DUCKDB_API static void Invalidate(DatabaseInstance &db, const ErrorData &error); template static void Invalidate(T &o, string error) { Get(o).Invalidate(std::move(error)); diff --git a/src/duckdb/src/include/duckdb/optimizer/build_probe_side_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/build_probe_side_optimizer.hpp index b59229bb1..f38a41185 100644 --- a/src/duckdb/src/include/duckdb/optimizer/build_probe_side_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/build_probe_side_optimizer.hpp @@ -36,20 +36,19 @@ class BuildProbeSideOptimizer : LogicalOperatorVisitor { void VisitOperator(LogicalOperator &op) override; void VisitExpression(unique_ptr *expression) override {}; + static double GetBuildSize(vector types, idx_t cardinality); + private: bool TryFlipJoinChildren(LogicalOperator &op) const; static idx_t ChildHasJoins(LogicalOperator &op); - bool ContainsActiveRecursiveReference(const LogicalOperator &op) const; - bool ContainsCorrelationSensitiveOperators(const LogicalOperator &op) const; RecursiveProbeSidePreference GetRecursiveProbeSidePreference(const LogicalOperator &op) const; static BuildSize GetBuildSizes(const LogicalOperator &op, idx_t lhs_cardinality, idx_t rhs_cardinality); - static double GetBuildSize(vector types, idx_t cardinality); private: ClientContext &context; vector preferred_on_probe_side; - vector active_recursive_cte_indexes; + unordered_set active_recursive_cte_indexes; }; } // 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 new file mode 100644 index 000000000..f777a7eba --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/column_binding_replacer.hpp" + +namespace duckdb { +class Optimizer; +class LogicalAggregate; +class LogicalMaterializedCTE; + +//! Restrict local grouped aggregates to their consumer's demand keys. +class DuplicateEliminatedDomainOptimizer : public LogicalOperatorVisitor { +public: + explicit DuplicateEliminatedDomainOptimizer(Optimizer &optimizer); + +public: + void Optimize(unique_ptr &op); + +private: + void VisitOperator(unique_ptr &op) override; + 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); + +private: + Optimizer &optimizer; + BindingReplacementGraph replacements; + vector> cte_scopes; +}; +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_build_properties.hpp b/src/duckdb/src/include/duckdb/optimizer/join_build_properties.hpp new file mode 100644 index 000000000..6fccc8e89 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_build_properties.hpp @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_build_properties.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +struct JoinBuildProperties { + bool correlation_sensitive = false; + //! Safe to treat the subtree as repeatable for unchanged inputs. + bool repeatable = true; + + static JoinBuildProperties Extract(LogicalOperator &op); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp index bd32a07fb..f98e1400e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp @@ -11,6 +11,7 @@ #include "duckdb/optimizer/join_order/cardinality_value.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" +#include "duckdb/optimizer/join_order/join_order_source_stats.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" namespace duckdb { @@ -30,14 +31,14 @@ class CardinalityEstimator { public: //! Initialize immutable logical statistics before estimating any relation set. - void Initialize(const vector &relations, - const vector> &operators = {}); + void Initialize(const vector &relations, const vector> &operators = {}, + const join_column_sources_t &sources = {}); //! All equivalent plans in a memo group share this estimate. CardinalityValue EstimateCardinality(JoinRelationSet &set); private: void InitEquivalentRelations(); - void UpdateTotalDomains(RelationIndex relation, const RelationStats &stats); + void UpdateTotalDomains(RelationIndex relation, const RelationStats &stats, const join_column_sources_t &sources); void RestrictFilterDomains(const vector &relation_stats); bool IsFilterApplicable(const FilterInfo &filter, JoinRelationSet &set) const; CardinalityValue GetNumerator(JoinRelationSet &set); @@ -71,6 +72,9 @@ class CardinalityEstimator { reference_map_t &inner_join_pair_stats, reference_set_t &capped_join_pairs); double GetJoinPairCap(JoinRelationSet &join_pair); + //! The number of key combinations of a join pair whose equalities cover a unique key of one of its relations, + //! or 0 if they cover neither relation's key. + double GetUniqueJoinPairDomain(JoinRelationSet &join_pair); void AddRelationStats(const FilterInfo &filter_info); bool EmptyFilter(const FilterInfo &filter_info); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp index 34e7050a2..e9cd817a1 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp @@ -12,6 +12,20 @@ namespace duckdb { +class RelationManager; + +struct JoinPlanCost { + double work; + double memory_excess; + + bool operator<(const JoinPlanCost &other) const { + return memory_excess != other.memory_excess ? memory_excess < other.memory_excess : work < other.work; + } + bool operator==(const JoinPlanCost &other) const { + return memory_excess == other.memory_excess && work == other.work; + } +}; + class CostModel { public: explicit CostModel(CardinalityEstimator &cardinality_estimator); @@ -21,9 +35,18 @@ class CostModel { double ComputeCost(const DPJoinNode &left, const DPJoinNode &right, optional_ptr join_operator, double output_rows); CardinalityEstimator &GetCardinalityEstimator(); + void InitializeRecursiveMemory(ClientContext &context, RelationManager &relations); + void UpdateBuildMemory(DPJoinNode &result, const DPJoinNode &left, const DPJoinNode &right); + JoinPlanCost GetCost(const DPJoinNode &node) const; + +private: + double GetBuildSize(const DPJoinNode &node); private: CardinalityEstimator &cardinality_estimator; + optional_ptr recursive_relations; + reference_map_t row_widths; + double memory_budget = 0; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp index f56cd1ef7..7b5c5127f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp @@ -9,6 +9,7 @@ #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/optimizer/join_order/cardinality_value.hpp" +#include "duckdb/optimizer/recursive_join_planning.hpp" namespace duckdb { @@ -46,6 +47,9 @@ class DPJoinNode { double cost; //! Candidate output used when composing parent estimates and costs. CardinalityValue cardinality {0}; + RecursiveJoinProperties recursive_properties; + double retained_build_size = 0; + double peak_build_size = 0; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp index 25407233e..81690dc6a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp @@ -16,6 +16,8 @@ namespace duckdb { +class JoinOrderSourceStats; + class JoinOrderOptimizer { public: explicit JoinOrderOptimizer(ClientContext &context); @@ -36,6 +38,7 @@ class JoinOrderOptimizer { //! Adds/gets delim scan stats void AddDelimScanStats(RelationStats &stats); RelationStats GetDelimScanStats(); + const shared_ptr &GetSourceStats() const; private: ClientContext &context; @@ -58,6 +61,7 @@ class JoinOrderOptimizer { //! Stats of Delim Scans of the Delim Join that is currently being optimized optional_ptr delim_scan_stats; idx_t depth; + shared_ptr source_stats; public: unordered_set recursive_cte_indexes; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp new file mode 100644 index 000000000..be7602282 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp @@ -0,0 +1,59 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/join_order_source_stats.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics.hpp" + +namespace duckdb { + +class ClientContext; +class LogicalGet; +class LogicalOperator; + +struct JoinColumnSource { + ColumnBinding binding; + idx_t source_cardinality; + idx_t scan_cardinality; + DistinctCount domain; +}; + +struct JoinColumnSources { + explicit JoinColumnSources(JoinColumnSource direct) : direct(std::move(direct)) { + } + + JoinColumnSource direct; + vector equivalents; +}; + +using join_column_sources_t = column_binding_map_t; + +//! Immutable source evidence captured before any join-order subtree is optimized. +class JoinOrderSourceStats { +public: + JoinOrderSourceStats(ClientContext &context, LogicalOperator &root); + +public: + //! Capture additional read-only roots, such as externally supplied CTE definitions. + void AddPlan(ClientContext &context, LogicalOperator &root); + optional_ptr FindScanStats(const LogicalGet &get) const; + //! Resolve the visible columns of one relation, respecting statistics boundaries. + join_column_sources_t Resolve(LogicalOperator &root) const; + +private: + struct ScanStats { + idx_t cardinality; + RelationStats stats; + }; + + unordered_map scans; + unordered_map projections; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp index 9a6fbb80a..5fcc4e9d5 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp @@ -128,6 +128,7 @@ class JoinPredicateModel { void AddEqualityClass(JoinEqualityClass equality_class); void AddDirectEqualityPairClass(JoinRelationSet &pair, idx_t equality_class_index, ColumnBinding first_binding, ColumnBinding second_binding); + optional_ptr GetDirectEqualityPair(JoinRelationSet &pair) const; optional_ptr GetPredicateByFilterIndex(idx_t filter_index) const; const vector> &GetPredicates() const; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp index 1d1b0469c..befc53a68 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp @@ -54,6 +54,9 @@ class PlanEnumerator { const vector> &GetConnections(JoinRelationSet &left, JoinRelationSet &right); const vector> &GetAllNeighborRelationSets(vector neighbors); + //! Estimated cardinality of the recursive frontier when planning inside a recursive member + double recursive_frontier_estimate = 0; + bool EnumerateCmpRecursive(JoinRelationSet &left, JoinRelationSet &right, unordered_set &exclusion_set); //! Emit a relation set node diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp index f83d2f7ea..cb28deb6d 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp @@ -11,9 +11,11 @@ #include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/recursive_join_planning.hpp" #include "duckdb/optimizer/join_order/cardinality_estimator.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" +#include "duckdb/optimizer/join_order/join_order_source_stats.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" #include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/column_binding_map.hpp" @@ -41,6 +43,7 @@ struct SingleJoinRelation { LogicalOperator &op; optional_ptr parent; RelationStats stats; + RecursiveJoinProperties recursive_properties; }; class RelationManager { @@ -71,12 +74,16 @@ class RelationManager { bool TryNormalizeBinding(ColumnBinding binding, ColumnBinding &normalized) const; bool HasCompleteStats() const; bool AddRelation(LogicalOperator &op, optional_ptr parent, const RelationStats &stats); + bool HasRecursiveRelations() const; + const SingleJoinRelation &GetRelation(RelationIndex index) const; //! Add an unnest relation which can come from a logical unnest or a logical get which has an unnest function bool AddRelationWithChildren(JoinOrderOptimizer &optimizer, LogicalOperator &op, LogicalOperator &input_op, optional_ptr parent, RelationStats &child_stats); vector> GetRelations(); const vector GetRelationStats(); + void SetSourceStats(shared_ptr stats); + const join_column_sources_t &GetColumnSources() const; //! A mapping of base table index -> index into relations array (relation number) unordered_map relation_mapping; @@ -106,7 +113,11 @@ class RelationManager { vector> relations; reference_map_t operator_relations; column_binding_map_t normalized_bindings; + unordered_set active_recursive_ctes; + bool has_recursive_relations = false; bool stats_complete = true; + shared_ptr source_stats; + join_column_sources_t column_sources; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/optimizer.hpp index e5f4cc930..b90a9fa98 100644 --- a/src/duckdb/src/include/duckdb/optimizer/optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/optimizer.hpp @@ -53,9 +53,10 @@ class Optimizer { public: // helper functions - unique_ptr BindScalarFunction(const Identifier &name, unique_ptr c1); unique_ptr BindScalarFunction(const Identifier &name, unique_ptr c1, - unique_ptr c2); + Identifier alias = Identifier()); + unique_ptr BindScalarFunction(const Identifier &name, unique_ptr c1, + unique_ptr c2, Identifier alias = Identifier()); unique_ptr BindScalarFunction(const Identifier &name, unique_ptr c1, unique_ptr c2, unique_ptr c3); @@ -63,7 +64,8 @@ class Optimizer { unique_ptr plan; private: - unique_ptr BindScalarFunction(const Identifier &name, vector> children); + unique_ptr BindScalarFunction(const Identifier &name, vector> children, + Identifier alias = Identifier()); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/partial_aggregate_pushdown.hpp b/src/duckdb/src/include/duckdb/optimizer/partial_aggregate_pushdown.hpp index 3f182ae55..94f81735e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/partial_aggregate_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/partial_aggregate_pushdown.hpp @@ -13,6 +13,7 @@ namespace duckdb { class Optimizer; +class LogicalMaterializedCTE; //! The PartialAggregatePushdown optimizer pushes partial aggregate states below joins when this can reduce join work class PartialAggregatePushdown : public LogicalOperatorVisitor { @@ -35,6 +36,7 @@ class PartialAggregatePushdown : public LogicalOperatorVisitor { private: Optimizer &optimizer; + unordered_map> cte_definitions; column_binding_map_t replacement_map; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/recursive_join_planning.hpp b/src/duckdb/src/include/duckdb/optimizer/recursive_join_planning.hpp new file mode 100644 index 000000000..94efe4f0b --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/recursive_join_planning.hpp @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/recursive_join_planning.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/enums/join_type.hpp" +#include "duckdb/common/unordered_set.hpp" +#include "duckdb/optimizer/join_build_properties.hpp" + +namespace duckdb { + +struct RecursiveJoinProperties { + JoinBuildProperties build; + bool depends_on_recursive_input = false; + + static RecursiveJoinProperties Extract(LogicalOperator &op, const unordered_set &active_ctes); +}; + +bool CanPlaceRecursiveProbe(JoinType type, const RecursiveJoinProperties &probe_side, + const RecursiveJoinProperties &build_side); + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp index ec79ba2b9..9349fe725 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp @@ -29,14 +29,15 @@ struct DistinctCount { struct SemiAntiJoinDomainEvidence { public: - void TightenFilterDomainBound(idx_t bound); + //! A bound established by predicates or a closed input, independent of estimated row retention. + void TightenDomainBound(idx_t bound); void MarkUnique(); void Invalidate(); optional_idx GetSupportedDomainSize(idx_t current_domain) const; - optional_idx GetFilterDomainBound() const; + optional_idx GetDomainBound() const; private: - optional_idx filter_domain_bound; + optional_idx domain_bound; bool is_unique = false; }; @@ -76,6 +77,9 @@ struct RelationStats { //! Cumulative estimated fraction of rows retained from the most recent statistics source. //! Aggregation and DISTINCT establish a new source. double row_retention = 1; + //! Indexes of the columns that together identify a row of a join-order relation, e.g. the groups of an + //! aggregate. Empty when no such key is known. + vector unique_key; bool stats_initialized = false; Identifier table_name; }; 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 f988bcb36..d99845d99 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 @@ -19,6 +19,7 @@ namespace duckdb { class ClientContext; class LogicalCTERef; class LogicalOperator; +class JoinOrderSourceStats; using relation_stats_cte_callback_t = std::function(TableIndex)>; @@ -26,10 +27,13 @@ class RelationStatsExtractor { public: explicit RelationStatsExtractor(ClientContext &context); RelationStatsExtractor(ClientContext &context, relation_stats_cte_callback_t cte_callback); + RelationStatsExtractor(ClientContext &context, shared_ptr source_stats); public: optional_ptr Extract(LogicalOperator &op); + optional_ptr GetCTEDefinition(const LogicalCTERef &cte_ref) const; idx_t ExtractedOperatorCount() const; + shared_ptr GetSourceStats(LogicalOperator &root); private: optional ExtractInternal(LogicalOperator &op); @@ -43,6 +47,9 @@ class RelationStatsExtractor { reference_set_t active_operators; reference_set_t failed_operators; idx_t extracted_operator_count = 0; + shared_ptr source_stats; + //! A join-order caller has already captured all sources before rewriting the plan. + shared_ptr inherited_source_stats; }; } // namespace duckdb 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 b66db90b3..3ec7d3c2d 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 @@ -51,6 +51,7 @@ class RelationStatisticsHelper { public: static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context); + static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context, idx_t source_cardinality); static RelationStats ExtractDelimGetStats(LogicalDelimGet &delim_get, ClientContext &context); static RelationStats ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context); static RelationStats ExtractExpressionGetStats(LogicalExpressionGet &expression_get, ClientContext &context); @@ -65,7 +66,8 @@ class RelationStatisticsHelper { //! Reuse the caller snapshot for aggregate input refinements. static optional ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, - RelationStatsExtractor &extractor); + RelationStatsExtractor &extractor, + bool use_operator_cardinality = false); static optional ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats); static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats); static optional ExtractLimitStats(LogicalLimit &limit, const RelationStats &child_stats); @@ -77,6 +79,9 @@ class RelationStatisticsHelper { const RelationStats &right, RelationStats &result); static idx_t CardinalityFromDouble(double cardinality); static idx_t EstimateDistinctCardinality(const vector &distinct_counts, idx_t input_cardinality); + static idx_t EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, + vector groups, RelationStatsExtractor &extractor, + bool use_operator_cardinality = false); static DistinctCount EstimateCurrentDomain(const DistinctCount ¤t_domain, idx_t input_cardinality, idx_t output_cardinality); static void ApplyCardinality(RelationStats &stats, idx_t output_cardinality); 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 32a5bfdaa..6be475719 100644 --- a/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp @@ -61,8 +61,8 @@ class ReferencedColumn { void AddPath(const ColumnIndex &path); public: - //! The BoundColumnRefExpressions in the operator that reference the same ColumnBinding - vector> bindings; + //! The slots holding the BoundColumnRefExpressions in the operator that reference the same ColumnBinding + vector>> bindings; vector struct_extracts; vector child_columns; //! Whether we can create a pushdown extract for the children of this column (if any) @@ -95,12 +95,12 @@ class BaseColumnPruner : public LogicalOperatorVisitor { unique_ptr VisitReplace(BoundReferenceExpression &expr, unique_ptr *expr_ptr) override; protected: - //! Add a reference to the column in its entirety - void AddBinding(BoundColumnRefExpression &col); + //! Add a reference to the column in its entirety - col holds a BoundColumnRefExpression + void AddBinding(unique_ptr &col); //! Add a reference to a sub-section of the column - void AddBinding(BoundColumnRefExpression &col, ColumnIndex child_column); + void AddBinding(unique_ptr &col, ColumnIndex child_column); //! Add a reference to a sub-section of the column used in a struct extract, with the parent expression - void AddBinding(BoundColumnRefExpression &col, ColumnIndex child_column, + void AddBinding(unique_ptr &col, ColumnIndex child_column, const vector &parent); //! Perform a replacement of the ColumnBinding, iterating over all the currently found column references and //! replacing the bindings @@ -110,11 +110,11 @@ class BaseColumnPruner : public LogicalOperatorVisitor { bool HandleExtractExpression(unique_ptr *expression, optional_ptr> cast_expression = nullptr); - bool HandleStructExtract(unique_ptr &expr, optional_ptr &colref, + bool HandleStructExtract(unique_ptr &expr, optional_ptr> &colref, reference &path_ref, vector &expressions); - bool HandleVariantExtract(unique_ptr &expr, optional_ptr &colref, + bool HandleVariantExtract(unique_ptr &expr, optional_ptr> &colref, reference &path_ref, vector &expressions); - bool HandleExtractRecursive(unique_ptr &expr, optional_ptr &colref, + bool HandleExtractRecursive(unique_ptr &expr, optional_ptr> &colref, reference &path_ref, vector &expressions); void SetMode(BaseColumnPrunerMode mode); BaseColumnPrunerMode GetMode() const; @@ -129,8 +129,6 @@ class BaseColumnPruner : public LogicalOperatorVisitor { private: //! The current mode of the pruner, enables/disables certain behaviors BaseColumnPrunerMode mode = BaseColumnPrunerMode::DEFAULT; - //! True while visiting the child of OPERATOR_TRY or OPERATOR_HAS_ERROR. Do not push throwing CASTs (#25236). - bool inside_try = false; }; //! The RemoveUnusedColumns optimizer traverses the logical operator tree and removes any columns that are not required diff --git a/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp b/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp index 8f2188424..74f69877b 100644 --- a/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp @@ -16,33 +16,26 @@ class ClientContext; class Expression; struct JoinFilterPushdownColumn; -enum class RuntimeFilterCastMode : uint8_t { DEFAULT_CAST, TRY_CAST }; - -struct RuntimeFilterCastStep { - RuntimeFilterCastStep(LogicalType target_type_p, RuntimeFilterCastMode mode_p) - : target_type(std::move(target_type_p)), mode(mode_p) { - } - - LogicalType target_type; - RuntimeFilterCastMode mode; -}; - -//! Utilities for the cast chains recorded on pushed runtime filter columns. +//! Utilities for expressions recorded on pushed runtime filter columns. //! Shared by the join filter pushdown (physical_hash_join) and the TopN dynamic filter pushdown. struct RuntimeFilterCastUtil { //! Whether a cast from source_type to target_type can fail at runtime static bool RuntimeFilterCastCanFail(const LogicalType &source_type, const LogicalType &target_type); - //! Whether the cast chain of this column contains (or requires) a try cast + //! Whether a bound cast uses the built-in implementation without custom bind data + static bool IsBuiltinCast(const Expression &expr); + //! Whether the expression contains (or requires) a try cast static bool RuntimeFilterUsesTryCast(const JoinFilterPushdownColumn &column); + //! Whether the expression preserves the ordering of the raw projected column + static bool PreservesStorageOrdering(const JoinFilterPushdownColumn &column); //! The type that CreateRuntimeFilterInputExpression evaluates to for this column static LogicalType GetRuntimeFilterInputType(const JoinFilterPushdownColumn &column, const LogicalType &runtime_type); //! Whether evaluating the pushed runtime filter requires reconstructing the pushed expression - //! on top of the raw scan value (i.e. the cast chain contains a cast that can fail) + //! on top of the projected scan value static bool RequiresRuntimeFilterExpressionReconstruction(const JoinFilterPushdownColumn &column, const LogicalType &runtime_type); //! Build the input expression for evaluating a pushed runtime filter on top of the raw scan column: - //! a BoundReferenceExpression(0) in the storage type, followed by the recorded cast chain. + //! a copy of the bound input expression, with potentially failing casts made non-throwing. //! Set `preserves_cast_errors` when a default (non-try) cast in the chain can fail. static unique_ptr CreateRuntimeFilterInputExpression(ClientContext &context, const JoinFilterPushdownColumn &column, diff --git a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp index 2d680c3f6..c71e97e15 100644 --- a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp @@ -30,12 +30,33 @@ struct FunctionStatisticsInput; enum class StatisticsPropagationMode : uint8_t { FILTER_SIMPLIFICATION, FULL }; +//! Suspends attaching verification statistics to propagated expressions for the lifetime of the guard +struct VerificationStatsGuard { + explicit VerificationStatsGuard(bool &attach_p) : attach(attach_p), previous(attach_p) { + attach = false; + } + ~VerificationStatsGuard() { + Release(); + } + //! Restores attaching before the guard goes out of scope + void Release() { + attach = previous; + } + + bool &attach; + bool previous; +}; + class StatisticsPropagator { public: StatisticsPropagator(Optimizer &optimizer, unique_ptr &root, StatisticsPropagationMode mode = StatisticsPropagationMode::FULL); unique_ptr PropagateStatistics(unique_ptr &node_ptr); + //! Propagate statistics through a standalone expression, given the statistics of the columns it references + unique_ptr + PropagateExpressionStatistics(unique_ptr &expr, + column_binding_map_t> column_statistics); column_binding_map_t> GetStatisticsMap() { return std::move(statistics_map); @@ -84,6 +105,7 @@ class StatisticsPropagator { unique_ptr PropagateStatistics(LogicalLimit &op, unique_ptr &node_ptr); unique_ptr PropagateStatistics(LogicalOrder &op, unique_ptr &node_ptr); unique_ptr PropagateStatistics(LogicalWindow &op, unique_ptr &node_ptr); + unique_ptr PropagateStatistics(LogicalUnnest &op, unique_ptr &node_ptr); unique_ptr PropagateChildren(LogicalOperator &node, unique_ptr &node_ptr); diff --git a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp index 221e3cef4..9be3a56ca 100644 --- a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp @@ -41,6 +41,11 @@ class TopNWindowElimination : public LogicalOperatorVisitor { unique_ptr Optimize(unique_ptr op); + //! Whether a rewrite used late materialization, which leaves the input of its aggregate to be pruned afterwards + bool UsedLateMaterialization() const { + return any_late_materialization; + } + // Returns the <= index for TopN, if any // Note that it can return 0 if the filter removes all rows! static optional_idx CanOptimize(LogicalOperator &op); @@ -91,5 +96,6 @@ class TopNWindowElimination : public LogicalOperatorVisitor { ClientContext &context; Optimizer &optimizer; optional_ptr>> stats; + bool any_late_materialization = false; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp index 1fb0222dc..4c53f1ca3 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp @@ -49,9 +49,21 @@ enum class ExternalInputEventState : uint8_t { }; class PipelineTask : public ExecutorTask { +public: static constexpr const idx_t PARTIAL_CHUNK_COUNT = 50; -public: + //! Bounds the chunks per PROCESS_PARTIAL slice of the result collector pipeline tasks the constructing thread + //! executes, for the lifetime of the scope. Other pipelines, and any thread outside a scope, process + //! PARTIAL_CHUNK_COUNT chunks per slice + class PartialChunkBound { + public: + explicit PartialChunkBound(idx_t chunk_count); + ~PartialChunkBound(); + + private: + idx_t previous; + }; + explicit PipelineTask(Pipeline &pipeline_p, shared_ptr event_p); Pipeline &pipeline; @@ -64,6 +76,10 @@ class PipelineTask : public ExecutorTask { public: TaskExecutionResult ExecuteTask(TaskExecutionMode mode) override; + +private: + //! The chunks this task's PROCESS_PARTIAL slice processes on the current thread + idx_t PartialChunkCount() const; }; class PipelineBuildState { 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 275fd1f8b..b74ddce4d 100644 --- a/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp +++ b/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp @@ -210,6 +210,8 @@ class ScanReadAhead { bool HasActiveProducers() const; //! Pop the oldest queued job unique_ptr ClaimJob(); + //! Return the memory governor's reservation once the scan is exhausted + void ReleaseMemoryReservation(); //! Mark the scan as done, i.e., no more jobs to produce void SetDone(); //! Whether jobs are held back from admission, used to detect gaps in the batch indexes on exhaustion diff --git a/src/duckdb/src/include/duckdb/parser/parsed_data/alter_info.hpp b/src/duckdb/src/include/duckdb/parser/parsed_data/alter_info.hpp index d55a8a45e..ea5a0cbb2 100644 --- a/src/duckdb/src/include/duckdb/parser/parsed_data/alter_info.hpp +++ b/src/duckdb/src/include/duckdb/parser/parsed_data/alter_info.hpp @@ -29,7 +29,8 @@ enum class AlterType : uint8_t { SET_COMMENT = 7, SET_COLUMN_COMMENT = 8, ALTER_DATABASE = 9, - ALTER_SCHEMA = 10 + ALTER_SCHEMA = 10, + ALTER_MACRO = 11 }; enum class AlterBindMode { BIND_ON_ALTER, SKIP_BINDING }; @@ -95,6 +96,12 @@ struct AlterInfo : public ParseInfo { virtual Identifier GetColumnName() const { return Identifier(); }; + //! Types the binder resolves against the altered entry's catalog and schema + virtual vector> GetTypesToBind(); + //! The catalog types the altered entry may have, tried in order when binding + virtual vector GetEntryLookupTypes() const; + //! Records the type of the entry the binder resolved, for an alter that accepts several + virtual void SetResolvedEntryType(CatalogType type); AlterEntryData GetAlterEntryData() const; bool IsAddPrimaryKey() const; diff --git a/src/duckdb/src/include/duckdb/parser/parsed_data/alter_macro_info.hpp b/src/duckdb/src/include/duckdb/parser/parsed_data/alter_macro_info.hpp new file mode 100644 index 000000000..6f84aff61 --- /dev/null +++ b/src/duckdb/src/include/duckdb/parser/parsed_data/alter_macro_info.hpp @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/parser/parsed_data/alter_macro_info.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/parser/parsed_data/alter_info.hpp" +#include "duckdb/common/types.hpp" + +namespace duckdb { + +enum class AlterMacroType : uint8_t { INVALID = 0, REMOVE_OVERLOAD = 1 }; + +//===--------------------------------------------------------------------===// +// Alter Macro +//===--------------------------------------------------------------------===// +struct AlterMacroInfo : public AlterInfo { +public: + AlterMacroInfo(AlterMacroType alter_macro_type, const AlterEntryData &data, CatalogType entry_catalog_type); + ~AlterMacroInfo() override; + + AlterMacroType alter_macro_type; + //! MACRO_ENTRY or TABLE_MACRO_ENTRY + CatalogType entry_catalog_type; + +public: + CatalogType GetCatalogType() const override; + //! DROP MACRO also names a table macro + vector GetEntryLookupTypes() const override; + void SetResolvedEntryType(CatalogType type) override; + + void Serialize(Serializer &serializer) const override; + static unique_ptr Deserialize(Deserializer &deserializer); + +protected: + explicit AlterMacroInfo(AlterMacroType alter_macro_type); +}; + +//===--------------------------------------------------------------------===// +// RemoveMacroOverloadInfo +//===--------------------------------------------------------------------===// +struct RemoveMacroOverloadInfo : public AlterMacroInfo { + RemoveMacroOverloadInfo(const AlterEntryData &data, CatalogType entry_catalog_type, vector signature); + ~RemoveMacroOverloadInfo() override; + + //! The parameter types identifying the overload to remove (ANY names an untyped slot) + vector signature; + +public: + unique_ptr Copy() const override; + string ToString() const override; + vector> GetTypesToBind() override; + + void Serialize(Serializer &serializer) const override; + static unique_ptr Deserialize(Deserializer &deserializer); + +private: + RemoveMacroOverloadInfo(); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parser/parsed_data/load_info.hpp b/src/duckdb/src/include/duckdb/parser/parsed_data/load_info.hpp index ce197e5d5..7369e87ae 100644 --- a/src/duckdb/src/include/duckdb/parser/parsed_data/load_info.hpp +++ b/src/duckdb/src/include/duckdb/parser/parsed_data/load_info.hpp @@ -32,7 +32,8 @@ struct LoadInfo : public ParseInfo { //! Whether to load the extension immediately after installing it (INSTALL AND LOAD) bool load_after_install = false; Identifier alias; - //! The url prefix of the repository (CREATE_REPOSITORY only) + //! The url prefix of the repository (CREATE_REPOSITORY only). Empty when none was given: the name is then the host + //! of the publisher, which names the prefix in its .well-known metadata file string repository_url; //! The public keys that are trusted to sign the extensions of the repository (CREATE_REPOSITORY only) vector public_keys; diff --git a/src/duckdb/src/include/duckdb/parser/parser_options.hpp b/src/duckdb/src/include/duckdb/parser/parser_options.hpp index 65bb77f87..6b106ea9d 100644 --- a/src/duckdb/src/include/duckdb/parser/parser_options.hpp +++ b/src/duckdb/src/include/duckdb/parser/parser_options.hpp @@ -16,6 +16,7 @@ namespace duckdb { class ClientContext; +class Context; class ExtensionCallbackManager; class ParserExtension; struct CompiledGrammar; @@ -38,8 +39,8 @@ struct ParserOptions { optional_ptr extensions; AllowParserOverride parser_override_setting = AllowParserOverride::DEFAULT_OVERRIDE; shared_ptr compiled_grammar; - //! The client context the statement is parsed for (not set when parsing without a client context) - optional_ptr context; + //! The services the statement is parsed for (not set when parsing without a context) + optional_ptr context; }; } // 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 04867892b..6115a963d 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -16,6 +16,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 9, 80, 114, 97, 103, 109, 97, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 9, 67, 97, 108, 108, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 9, 73, 110, 115, 101, 114, 116, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, + 9, 68, 114, 111, 112, 77, 101, 109, 98, 101, 114, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 9, 68, 114, 111, 112, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 9, 67, 111, 112, 121, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 9, 69, 120, 112, 108, 97, 105, 110, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, @@ -1448,6 +1449,10 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 68, 101, 115, 99, 82, 117, 108, 101, 32, 60, 45, 32, 39, 68, 69, 83, 67, 39, 10, 68, 101, 116, 97, 99, 104, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 39, 68, 69, 84, 65, 67, 72, 39, 32, 68, 97, 116, 97, 98, 97, 115, 101, 63, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 67, 97, 116, 97, 108, 111, 103, 78, 97, 109, 101, 10, 68, 114, 111, 112, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 39, 68, 82, 79, 80, 39, 32, 68, 114, 111, 112, 69, 110, 116, 114, 105, 101, 115, 32, 68, 114, 111, 112, 66, 101, 104, 97, 118, 105, 111, 114, 63, 10, + 68, 114, 111, 112, 77, 101, 109, 98, 101, 114, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 39, 68, 82, 79, 80, 39, 32, 68, 114, 111, 112, 77, 101, 109, 98, 101, 114, 32, 68, 114, 111, 112, 66, 101, 104, 97, 118, 105, 111, 114, 63, 10, + 68, 114, 111, 112, 77, 101, 109, 98, 101, 114, 32, 60, 45, 32, 68, 114, 111, 112, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 77, 101, 109, 98, 101, 114, 32, 47, 32, 68, 114, 111, 112, 70, 117, 110, 99, 116, 105, 111, 110, 77, 101, 109, 98, 101, 114, 10, + 68, 114, 111, 112, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 77, 101, 109, 98, 101, 114, 32, 60, 45, 32, 67, 111, 109, 109, 101, 110, 116, 77, 97, 99, 114, 111, 84, 97, 98, 108, 101, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 68, 114, 111, 112, 70, 117, 110, 99, 116, 105, 111, 110, 83, 105, 103, 110, 97, 116, 117, 114, 101, 10, + 68, 114, 111, 112, 70, 117, 110, 99, 116, 105, 111, 110, 77, 101, 109, 98, 101, 114, 32, 60, 45, 32, 70, 117, 110, 99, 116, 105, 111, 110, 84, 121, 112, 101, 77, 97, 99, 114, 111, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 70, 117, 110, 99, 116, 105, 111, 110, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 32, 68, 114, 111, 112, 70, 117, 110, 99, 116, 105, 111, 110, 83, 105, 103, 110, 97, 116, 117, 114, 101, 10, 68, 114, 111, 112, 69, 110, 116, 114, 105, 101, 115, 32, 60, 45, 10, 9, 68, 114, 111, 112, 84, 97, 98, 108, 101, 32, 47, 10, 9, 68, 114, 111, 112, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 47, 10, @@ -1463,6 +1468,9 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 68, 114, 111, 112, 84, 97, 98, 108, 101, 32, 60, 45, 32, 84, 97, 98, 108, 101, 79, 114, 86, 105, 101, 119, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 66, 97, 115, 101, 84, 97, 98, 108, 101, 78, 97, 109, 101, 41, 10, 68, 114, 111, 112, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 60, 45, 32, 67, 111, 109, 109, 101, 110, 116, 77, 97, 99, 114, 111, 84, 97, 98, 108, 101, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 41, 10, 68, 114, 111, 112, 70, 117, 110, 99, 116, 105, 111, 110, 32, 60, 45, 32, 70, 117, 110, 99, 116, 105, 111, 110, 84, 121, 112, 101, 77, 97, 99, 114, 111, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 70, 117, 110, 99, 116, 105, 111, 110, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 41, 10, + 68, 114, 111, 112, 70, 117, 110, 99, 116, 105, 111, 110, 83, 105, 103, 110, 97, 116, 117, 114, 101, 32, 60, 45, 32, 80, 97, 114, 101, 110, 115, 40, 76, 105, 115, 116, 40, 68, 114, 111, 112, 83, 105, 103, 110, 97, 116, 117, 114, 101, 84, 121, 112, 101, 41, 63, 41, 10, + 68, 114, 111, 112, 83, 105, 103, 110, 97, 116, 117, 114, 101, 84, 121, 112, 101, 32, 60, 45, 32, 68, 114, 111, 112, 83, 105, 103, 110, 97, 116, 117, 114, 101, 65, 110, 121, 84, 121, 112, 101, 32, 47, 32, 84, 121, 112, 101, 10, + 68, 114, 111, 112, 83, 105, 103, 110, 97, 116, 117, 114, 101, 65, 110, 121, 84, 121, 112, 101, 32, 60, 45, 32, 39, 65, 78, 89, 39, 10, 68, 114, 111, 112, 83, 99, 104, 101, 109, 97, 32, 60, 45, 32, 39, 83, 67, 72, 69, 77, 65, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 81, 117, 97, 108, 105, 102, 105, 101, 100, 78, 97, 109, 101, 41, 10, 68, 114, 111, 112, 73, 110, 100, 101, 120, 32, 60, 45, 32, 39, 73, 78, 68, 69, 88, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 81, 117, 97, 108, 105, 102, 105, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 41, 10, 81, 117, 97, 108, 105, 102, 105, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 32, 60, 45, 32, 67, 97, 116, 97, 108, 111, 103, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 73, 110, 100, 101, 120, 32, 47, 32, 83, 99, 104, 101, 109, 97, 82, 101, 115, 101, 114, 118, 101, 100, 73, 110, 100, 101, 120, 32, 47, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 83, 116, 114, 105, 110, 103, 10, @@ -1498,6 +1506,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 32, 32, 32, 32, 67, 114, 101, 97, 116, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 32, 32, 32, 32, 68, 101, 97, 108, 108, 111, 99, 97, 116, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 32, 32, 32, 32, 68, 101, 108, 101, 116, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, + 32, 32, 32, 32, 68, 114, 111, 112, 77, 101, 109, 98, 101, 114, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 32, 32, 32, 32, 68, 114, 111, 112, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 32, 32, 32, 32, 69, 120, 101, 99, 117, 116, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, 32, 32, 32, 32, 73, 110, 115, 101, 114, 116, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 47, 10, @@ -1930,14 +1939,24 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 73, 110, 115, 116, 97, 108, 108, 65, 110, 100, 76, 111, 97, 100, 32, 60, 45, 32, 39, 65, 78, 68, 39, 32, 39, 76, 79, 65, 68, 39, 10, 85, 112, 100, 97, 116, 101, 69, 120, 116, 101, 110, 115, 105, 111, 110, 115, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 39, 85, 80, 68, 65, 84, 69, 39, 32, 39, 69, 88, 84, 69, 78, 83, 73, 79, 78, 83, 39, 32, 80, 97, 114, 101, 110, 115, 40, 76, 105, 115, 116, 40, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 41, 41, 63, 10, 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, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 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, 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, 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, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 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, + 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, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 80, 114, 101, 102, 105, 120, 32, 60, 45, 32, 39, 87, 73, 84, 72, 39, 63, 32, 39, 80, 82, 69, 70, 73, 88, 39, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 10, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 80, 117, 98, 108, 105, 99, 75, 101, 121, 32, 60, 45, 32, 39, 85, 83, 73, 78, 71, 39, 63, 32, 39, 80, 85, 66, 76, 73, 67, 39, 32, 40, 39, 75, 69, 89, 83, 39, 32, 47, 32, 39, 75, 69, 89, 39, 41, 32, 76, 105, 115, 116, 40, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 41, 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, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 10, + 35, 32, 34, 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, 99, 97, 114, 108, 111, 112, 105, 46, 103, 105, 116, 104, 117, 98, 46, 105, 111, 34, 58, 32, 119, 105, 116, 104, 111, 117, 116, 32, 97, 32, 112, 114, 101, 102, 105, 120, 32, 116, 104, 101, 32, 110, 97, 109, 101, 32, 105, 115, 32, 116, 104, 101, 32, 104, 111, 115, 116, 32, 111, 102, 32, 116, 104, 101, 32, 112, 117, 98, 108, 105, 115, 104, 101, 114, 44, 32, 97, 110, 100, 32, 116, 104, 101, 32, 104, 111, 115, 116, 10, + 35, 32, 115, 97, 121, 115, 32, 119, 104, 101, 114, 101, 32, 105, 116, 115, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 105, 115, 58, 32, 104, 116, 116, 112, 115, 58, 47, 47, 60, 110, 97, 109, 101, 62, 47, 46, 119, 101, 108, 108, 45, 107, 110, 111, 119, 110, 47, 100, 117, 99, 107, 100, 98, 45, 101, 120, 116, 101, 110, 115, 105, 111, 110, 45, 114, 101, 112, 111, 46, 106, 115, 111, 110, 32, 110, 97, 109, 101, 115, 32, 116, 104, 101, 32, 112, 114, 101, 102, 105, 120, 32, 40, 97, 110, 100, 32, 109, 97, 121, 32, 99, 97, 114, 114, 121, 10, + 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, 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, @@ -2107,7 +2126,9 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 66, 97, 115, 101, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 63, 32, 66, 97, 115, 101, 84, 97, 98, 108, 101, 78, 97, 109, 101, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 32, 65, 116, 67, 108, 97, 117, 115, 101, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 32, 60, 45, 32, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 32, 39, 58, 39, 10, 86, 97, 108, 117, 101, 115, 82, 101, 102, 32, 60, 45, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 63, 32, 86, 97, 108, 117, 101, 115, 67, 108, 97, 117, 115, 101, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, - 80, 97, 114, 101, 110, 115, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 63, 32, 80, 97, 114, 101, 110, 115, 40, 84, 97, 98, 108, 101, 82, 101, 102, 41, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, + 80, 97, 114, 101, 110, 115, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 63, 32, 80, 97, 114, 101, 110, 115, 40, 74, 111, 105, 110, 101, 100, 84, 97, 98, 108, 101, 82, 101, 102, 41, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, + 74, 111, 105, 110, 101, 100, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 74, 111, 105, 110, 101, 100, 84, 97, 98, 108, 101, 82, 101, 102, 67, 104, 97, 105, 110, 32, 47, 32, 80, 97, 114, 101, 110, 115, 84, 97, 98, 108, 101, 82, 101, 102, 10, + 74, 111, 105, 110, 101, 100, 84, 97, 98, 108, 101, 82, 101, 102, 67, 104, 97, 105, 110, 32, 60, 45, 32, 73, 110, 110, 101, 114, 84, 97, 98, 108, 101, 82, 101, 102, 32, 74, 111, 105, 110, 79, 114, 80, 105, 118, 111, 116, 43, 10, 74, 111, 105, 110, 79, 114, 80, 105, 118, 111, 116, 32, 60, 45, 32, 74, 111, 105, 110, 67, 108, 97, 117, 115, 101, 32, 47, 32, 84, 97, 98, 108, 101, 80, 105, 118, 111, 116, 67, 108, 97, 117, 115, 101, 32, 47, 32, 84, 97, 98, 108, 101, 85, 110, 112, 105, 118, 111, 116, 67, 108, 97, 117, 115, 101, 32, 47, 32, 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, 10, 84, 97, 98, 108, 101, 80, 105, 118, 111, 116, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 39, 80, 73, 86, 79, 84, 39, 32, 80, 97, 114, 101, 110, 115, 40, 84, 97, 98, 108, 101, 80, 105, 118, 111, 116, 67, 108, 97, 117, 115, 101, 66, 111, 100, 121, 41, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 10, 84, 97, 98, 108, 101, 80, 105, 118, 111, 116, 67, 108, 97, 117, 115, 101, 66, 111, 100, 121, 32, 60, 45, 32, 84, 97, 114, 103, 101, 116, 76, 105, 115, 116, 32, 39, 70, 79, 82, 39, 32, 80, 105, 118, 111, 116, 86, 97, 108, 117, 101, 76, 105, 115, 116, 43, 32, 80, 105, 118, 111, 116, 71, 114, 111, 117, 112, 66, 121, 76, 105, 115, 116, 63, 10, @@ -2162,7 +2183,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 78, 101, 97, 114, 101, 115, 116, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 60, 45, 32, 76, 97, 116, 101, 114, 97, 108, 63, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 115, 32, 87, 105, 116, 104, 79, 114, 100, 105, 110, 97, 108, 105, 116, 121, 63, 10, 78, 101, 97, 114, 101, 115, 116, 84, 97, 98, 108, 101, 83, 117, 98, 113, 117, 101, 114, 121, 32, 60, 45, 32, 76, 97, 116, 101, 114, 97, 108, 63, 32, 83, 117, 98, 113, 117, 101, 114, 121, 82, 101, 102, 101, 114, 101, 110, 99, 101, 10, 78, 101, 97, 114, 101, 115, 116, 66, 97, 115, 101, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 66, 97, 115, 101, 84, 97, 98, 108, 101, 78, 97, 109, 101, 32, 65, 116, 67, 108, 97, 117, 115, 101, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, - 78, 101, 97, 114, 101, 115, 116, 80, 97, 114, 101, 110, 115, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 80, 97, 114, 101, 110, 115, 40, 84, 97, 98, 108, 101, 82, 101, 102, 41, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, + 78, 101, 97, 114, 101, 115, 116, 80, 97, 114, 101, 110, 115, 84, 97, 98, 108, 101, 82, 101, 102, 32, 60, 45, 32, 80, 97, 114, 101, 110, 115, 40, 74, 111, 105, 110, 101, 100, 84, 97, 98, 108, 101, 82, 101, 102, 41, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, 65, 112, 112, 114, 111, 120, 79, 114, 69, 120, 97, 99, 116, 32, 60, 45, 32, 78, 101, 97, 114, 101, 115, 116, 65, 112, 112, 114, 111, 120, 32, 47, 32, 78, 101, 97, 114, 101, 115, 116, 69, 120, 97, 99, 116, 10, 78, 101, 97, 114, 101, 115, 116, 65, 112, 112, 114, 111, 120, 32, 60, 45, 32, 39, 65, 80, 80, 82, 79, 88, 39, 10, 78, 101, 97, 114, 101, 115, 116, 69, 120, 97, 99, 116, 32, 60, 45, 32, 39, 69, 88, 65, 67, 84, 39, 10, diff --git a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp index 8f5e99fef..ca3a9686c 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 @@ -461,11 +461,18 @@ enum class PEGRuleId : uint32_t { DescRule, DetachStatement, DropStatement, + DropMemberStatement, + DropMember, + DropTableFunctionMember, + DropFunctionMember, DropEntries, DropTrigger, DropTable, DropTableFunction, DropFunction, + DropFunctionSignature, + DropSignatureType, + DropSignatureAnyType, DropSchema, DropIndex, QualifiedIndexName, @@ -843,12 +850,16 @@ enum class PEGRuleId : uint32_t { FromSource, FromSourceIdentifier, FromSourceString, + FromSourceName, VersionNumber, ExtensionRepositoryStatement, CreateExtensionRepositoryStmt, RepositoryPrefix, RepositoryPublicKey, + CreateExtensionRepositoryFromHostStmt, DropExtensionRepositoryStmt, + ExtensionRepositoryName, + ExtensionRepositoryHostName, TableMatchRecognizeClause, MatchRecognizeBody, MatchRecognizeClause, @@ -1013,6 +1024,8 @@ enum class PEGRuleId : uint32_t { TableAliasColon, ValuesRef, ParensTableRef, + JoinedTableRef, + JoinedTableRefChain, JoinOrPivot, TablePivotClause, TablePivotClauseBody, diff --git a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/highlight_tokenizer.hpp b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/highlight_tokenizer.hpp index 1828c28a9..8fc3a85ed 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/highlight_tokenizer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/highlight_tokenizer.hpp @@ -5,7 +5,7 @@ namespace duckdb { class HighlightTokenizerBehavior : public TokenizerBehavior { public: - HighlightTokenizerBehavior(const string &sql, vector &tokens); + explicit HighlightTokenizerBehavior(const string &sql); ~HighlightTokenizerBehavior() override = default; void PushToken(idx_t start, idx_t end, TokenType type, bool unterminated) override; 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 758dfc5c9..7b20d9ea6 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 @@ -5,7 +5,7 @@ namespace duckdb { class ParserTokenizerBehavior : public TokenizerBehavior { public: - ParserTokenizerBehavior(const string &sql, vector &tokens); + explicit ParserTokenizerBehavior(const string &sql); ~ParserTokenizerBehavior() override = default; void PushToken(idx_t start, idx_t end, TokenType type, bool unterminated = false) 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 c2e3dcb5f..fd5c497c5 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/tokenizer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/tokenizer.hpp @@ -30,7 +30,7 @@ class Tokenizer; class TokenizerBehavior { public: - TokenizerBehavior(const string &sql, vector &tokens); + explicit TokenizerBehavior(const string &sql); virtual ~TokenizerBehavior() = default; public: @@ -47,7 +47,7 @@ class TokenizerBehavior { public: const string &sql; - vector &tokens; + vector tokens; bool has_block_comment = false; idx_t last_block_comment_position = 0; }; 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 a5825dccd..c60f260a8 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 @@ -1529,6 +1529,12 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeDropStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeDropMemberStatementTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr + FinalizeDropTableFunctionMemberTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeDropFunctionMemberTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeDropTriggerTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropTableTrampoline(PEGTransformer &transformer, @@ -1537,6 +1543,10 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeDropFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeDropFunctionSignatureTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeDropSignatureAnyTypeTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeDropSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropIndexTrampoline(PEGTransformer &transformer, @@ -2145,6 +2155,8 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeFromSourceStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeFromSourceNameTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeVersionNumberTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr @@ -2154,8 +2166,15 @@ class PEGTransformerFactory { static arena_ptr FinalizeRepositoryPublicKeyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr + FinalizeCreateExtensionRepositoryFromHostStmtTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeDropExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); 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); @@ -2393,6 +2412,8 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeJoinedTableRefChainTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeTablePivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTablePivotClauseBodyTrampoline(PEGTransformer &transformer, @@ -3357,6 +3378,19 @@ class PEGTransformerFactory { static unique_ptr TransformDropStatement(PEGTransformer &transformer, unique_ptr drop_entries, const optional &drop_behavior); + static unique_ptr TransformDropMemberStatement(PEGTransformer &transformer, + unique_ptr drop_member, + const optional &drop_behavior); + static unique_ptr TransformDropTableFunctionMember(PEGTransformer &transformer, + const CatalogType &comment_macro_table, + const optional &if_exists, + const QualifiedName &qualified_table_function, + const vector &drop_function_signature); + static unique_ptr TransformDropFunctionMember(PEGTransformer &transformer, + const bool &function_type_macro, + const optional &if_exists, + const QualifiedName &function_identifier, + const vector &drop_function_signature); static unique_ptr TransformDropTrigger(PEGTransformer &transformer, const optional &if_exists, const Identifier &trigger_name, unique_ptr base_table_name); @@ -3370,6 +3404,9 @@ class PEGTransformerFactory { static unique_ptr TransformDropFunction(PEGTransformer &transformer, const bool &function_type_macro, const optional &if_exists, const vector &function_identifier); + static vector TransformDropFunctionSignature(PEGTransformer &transformer, + const optional> &type); + static LogicalType TransformDropSignatureAnyType(PEGTransformer &transformer); static unique_ptr TransformDropSchema(PEGTransformer &transformer, const optional &if_exists, const vector &qualified_name); static unique_ptr TransformDropIndex(PEGTransformer &transformer, const optional &if_exists, @@ -4011,9 +4048,15 @@ class PEGTransformerFactory { const string &string_literal); static vector TransformRepositoryPublicKey(PEGTransformer &transformer, const bool &has_result, const vector &string_literal); + static unique_ptr + TransformCreateExtensionRepositoryFromHostStmt(PEGTransformer &transformer, const optional &or_replace, + const optional &if_not_exists, + const Identifier &extension_repository_name); 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); @@ -4264,6 +4307,9 @@ class PEGTransformerFactory { unique_ptr table_ref, const optional &table_alias, optional> sample_clause); + static unique_ptr TransformJoinedTableRefChain(PEGTransformer &transformer, + unique_ptr inner_table_ref, + vector> join_or_pivot); static unique_ptr TransformTablePivotClause(PEGTransformer &transformer, unique_ptr table_pivot_clause_body, const optional &table_alias); diff --git a/src/duckdb/src/include/duckdb/parser/token_iterator.hpp b/src/duckdb/src/include/duckdb/parser/token_iterator.hpp index f7256d685..39caea5d7 100644 --- a/src/duckdb/src/include/duckdb/parser/token_iterator.hpp +++ b/src/duckdb/src/include/duckdb/parser/token_iterator.hpp @@ -15,14 +15,20 @@ namespace duckdb { struct SimpleToken; +class TokenizerBehavior; //! Iterates over an already-tokenized query. A root iterator can own its tokens; child iterators //! reference the same tokens and carry an independent position for speculative parsing. class TokenIterator { public: DUCKDB_API explicit TokenIterator(unique_ptr> owned_tokens); + //! Takes ownership of the tokens the behavior produced (leaving its vector empty) and keeps a pointer to + //! `behavior.sql`, so Source() is always the string their offsets index into. That string has to outlive the + //! iterator and its children, the behavior itself does not. + DUCKDB_API explicit TokenIterator(TokenizerBehavior &behavior); DUCKDB_API explicit TokenIterator(vector &tokens); - DUCKDB_API TokenIterator(const TokenIterator &other) : tokens(other.tokens), position(other.position) { + DUCKDB_API TokenIterator(const TokenIterator &other) + : tokens(other.tokens), source(other.source), position(other.position) { } DUCKDB_API TokenIterator(TokenIterator &&other) noexcept; TokenIterator &operator=(const TokenIterator &) = delete; @@ -40,6 +46,12 @@ class TokenIterator { return tokens.size(); } DUCKDB_API idx_t EndOffset() const; + //! Byte offset just past the last consumed token, or 0 if no token has been consumed yet + DUCKDB_API idx_t ConsumedEndOffset() const; + //! The text the tokens were cut from (token offsets index into it), when built from a TokenizerBehavior + DUCKDB_API optional_ptr Source() const { + return source; + } DUCKDB_API optional_ptr Current() const { if (position >= tokens.size()) { @@ -67,6 +79,7 @@ class TokenIterator { private: unique_ptr> owned_tokens; vector &tokens; + optional_ptr source; idx_t position = 0; }; diff --git a/src/duckdb/src/include/duckdb/planner/binder.hpp b/src/duckdb/src/include/duckdb/planner/binder.hpp index 746079f3f..4ebe14b0c 100644 --- a/src/duckdb/src/include/duckdb/planner/binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/binder.hpp @@ -43,6 +43,7 @@ class RE2; namespace duckdb { class BoundResultModifier; +struct PreparedExecution; class BoundSelectNode; class ClientContext; class ExpressionBinder; @@ -278,6 +279,11 @@ class Binder : public enable_shared_from_this { DUCKDB_API BoundStatement Bind(SQLStatement &statement); DUCKDB_API BoundStatement Bind(QueryNode &node); + //! Resolve the prepared statement and the parameter values of an EXECUTE statement + PreparedExecution ResolveExecute(ExecuteStatement &stmt); + //! Plan the prepared statement of an EXECUTE from its unbound statement, using the resolved parameter values + BoundStatement BindExecute(PreparedExecution &execution); + unique_ptr BindCreateTableInfo(unique_ptr info); unique_ptr BindCreateTableInfo(unique_ptr info, SchemaCatalogEntry &schema, AlterBindMode bind_mode = AlterBindMode::BIND_ON_ALTER); 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 18b800c63..e6aaa29e5 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 @@ -12,6 +12,7 @@ #include "duckdb/function/cast/default_casts.hpp" namespace duckdb { +class Context; //! The BoundCastExpression has been moved to a function expression (the __cast scalar function). //! This class exists only as a set of helper methods. @@ -45,10 +46,9 @@ struct BoundCastExpression { const BaseStatistics &child_stats, optional_ptr context = nullptr); - //! Cast an expression to the specified SQL type, using only the built-in SQL casts - static unique_ptr AddDefaultCastToType(unique_ptr expr, const LogicalType &target_type, - bool try_cast = false); //! Cast an expression to the specified SQL type if required + DUCKDB_API static unique_ptr AddCastToType(Context &context, unique_ptr expr, + const LogicalType &target_type, bool try_cast = false); DUCKDB_API static unique_ptr AddCastToType(ClientContext &context, unique_ptr expr, const LogicalType &target_type, bool try_cast = false); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_columnref_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_columnref_expression.hpp index 941834719..3d86d4d89 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_columnref_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_columnref_expression.hpp @@ -22,7 +22,8 @@ class BoundColumnRefExpression : public Expression { public: BoundColumnRefExpression(LogicalType type, ColumnBinding binding, idx_t depth = 0); - BoundColumnRefExpression(Identifier alias, LogicalType type, ColumnBinding binding, idx_t depth = 0); + BoundColumnRefExpression(Identifier alias, LogicalType type, ColumnBinding binding, idx_t depth = 0, + QueryLocation location = QueryLocation()); public: bool IsScalar() const override { @@ -35,15 +36,19 @@ class BoundColumnRefExpression : public Expression { const ColumnBinding &Binding() const { return binding; } - ColumnBinding &BindingMutable() { - return binding; - } idx_t Depth() const { return depth; } - idx_t &DepthMutable() { - return depth; - } + //! Create a column reference with a different binding + unique_ptr WithBinding(ColumnBinding new_binding) const; + //! Create a column reference with a different binding and depth + unique_ptr WithBinding(ColumnBinding new_binding, idx_t new_depth) const; + //! Create a column reference with a different binding and return type + unique_ptr WithBinding(ColumnBinding new_binding, LogicalType new_type) const; + //! Create a column reference with a different return type + unique_ptr WithReturnType(LogicalType new_type) const; + //! Create a column reference with a different depth + unique_ptr WithDepth(idx_t new_depth) const; string ToString() const override; Identifier GetName() const override; diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_constant_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_constant_expression.hpp index 28342b237..d99925613 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_constant_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_constant_expression.hpp @@ -19,13 +19,14 @@ class BoundConstantExpression : public Expression { public: explicit BoundConstantExpression(Value value); + BoundConstantExpression(Value value, Identifier alias, QueryLocation location = QueryLocation()); public: const Value &GetValue() const { return value; } - void SetValue(Value value_p); - Value TakeValue(); + //! Create a constant with a different value (and the type of that value) + unique_ptr WithValue(Value new_value) const; void SetReturnType(LogicalType type) override; string ToString() const override; diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_default_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_default_expression.hpp index 2ed9622d4..760fd00e5 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_default_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_default_expression.hpp @@ -17,8 +17,11 @@ class BoundDefaultExpression : public Expression { static constexpr const ExpressionClass TYPE = ExpressionClass::BOUND_DEFAULT; public: - explicit BoundDefaultExpression(LogicalType type = LogicalType()) + explicit BoundDefaultExpression(LogicalType type = LogicalType(), Identifier alias_p = Identifier(), + QueryLocation location = QueryLocation()) : Expression(ExpressionType::VALUE_DEFAULT, ExpressionClass::BOUND_DEFAULT, std::move(type)) { + alias = std::move(alias_p); + query_location = location; } public: 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 575b8b0f2..f208ebbab 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,7 +21,8 @@ class BoundFunctionExpression : public Expression { public: BoundFunctionExpression(BoundScalarFunction bound_function, vector> arguments, - unique_ptr bind_info, bool is_operator = false); + unique_ptr bind_info, bool is_operator = false, + Identifier alias = Identifier(), QueryLocation location = QueryLocation()); public: const BoundScalarFunction &Function() const { diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_lambdaref_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_lambdaref_expression.hpp index ac857cd0a..474e49c03 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_lambdaref_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_lambdaref_expression.hpp @@ -30,21 +30,12 @@ class BoundLambdaRefExpression : public Expression { const ColumnBinding &Binding() const { return binding; } - ColumnBinding &BindingMutable() { - return binding; - } idx_t LambdaIndex() const { return lambda_idx; } - idx_t &LambdaIndexMutable() { - return lambda_idx; - } idx_t Depth() const { return depth; } - idx_t &DepthMutable() { - return depth; - } bool IsScalar() const override { return false; } diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_operator_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_operator_expression.hpp index 84cb9936c..c0c6b197f 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_operator_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_operator_expression.hpp @@ -18,6 +18,10 @@ class BoundOperatorExpression : public Expression { public: BoundOperatorExpression(ExpressionType type, LogicalType return_type); + BoundOperatorExpression(ExpressionType type, LogicalType return_type, unique_ptr child); + BoundOperatorExpression(ExpressionType type, LogicalType return_type, unique_ptr left, + unique_ptr right); + BoundOperatorExpression(ExpressionType type, LogicalType return_type, vector> children); public: const vector> &GetChildren() const { diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_parameter_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_parameter_expression.hpp index ed472fdd3..5fce78764 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_parameter_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_parameter_expression.hpp @@ -18,7 +18,8 @@ class BoundParameterExpression : public Expression { static constexpr const ExpressionClass TYPE = ExpressionClass::BOUND_PARAMETER; public: - explicit BoundParameterExpression(const duckdb::Identifier &identifier); + explicit BoundParameterExpression(const duckdb::Identifier &identifier, + duckdb::Identifier alias = duckdb::Identifier()); public: const duckdb::Identifier &Identifier() const { diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_reference_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_reference_expression.hpp index f5c5a3a05..7c78cf21a 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_reference_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_reference_expression.hpp @@ -25,9 +25,8 @@ class BoundReferenceExpression : public Expression { idx_t Index() const { return index; } - idx_t &IndexMutable() { - return index; - } + //! Create a reference to a different index + unique_ptr WithIndex(idx_t new_index) const; bool IsScalar() const override { return false; } diff --git a/src/duckdb/src/include/duckdb/planner/expression_binder.hpp b/src/duckdb/src/include/duckdb/planner/expression_binder.hpp index 5a3d93ccb..1715cdf4a 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_binder.hpp @@ -140,7 +140,9 @@ class ExpressionBinder { void SetCatalogLookupCallback(catalog_entry_callback_t callback); //! Bind the expression at the given depth, returning the bound expression or the error - [[nodiscard]] BindResult Bind(unique_ptr &expr, idx_t depth, bool root_expression = false); + //! Binds the expression - the bound expression gets the given alias, or that of the parsed expression if empty + [[nodiscard]] BindResult Bind(unique_ptr &expr, idx_t depth, bool root_expression = false, + const Identifier &alias = Identifier()); //! Returns the STRUCT_EXTRACT operator expression unique_ptr CreateStructExtract(unique_ptr base, const Identifier &field_name); @@ -227,7 +229,8 @@ class ExpressionBinder { //! Bind a child expression, returning it. A null child, or one that fails to bind, returns null; //! the first error encountered is recorded in the accumulator. - [[nodiscard]] unique_ptr BindChild(unique_ptr &expr, idx_t depth, ErrorData &error); + [[nodiscard]] unique_ptr BindChild(unique_ptr &expr, idx_t depth, ErrorData &error, + const Identifier &alias = Identifier()); static void ExtractCorrelatedExpressions(Binder &binder, Expression &expr); static bool ContainsNullType(const LogicalType &type); diff --git a/src/duckdb/src/include/duckdb/planner/expression_iterator.hpp b/src/duckdb/src/include/duckdb/planner/expression_iterator.hpp index ed7be0786..09a74224a 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_iterator.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_iterator.hpp @@ -35,6 +35,21 @@ class ExpressionIterator { static unique_ptr ReplaceExpression(const Expression &expr, const Expression &target, const Expression &replacement); + //! Returns the replacement of an expression, or nullptr to keep the expression + using ReplaceFunction = std::function(const Expression &expr)>; + + //! Replace expressions in a tree in pre-order and return the new root - replacements are not visited + static unique_ptr PreorderReplace(unique_ptr expr, const ReplaceFunction &callback); + //! Replace expressions of a class in a tree - the children of these expressions are not visited + static unique_ptr PreorderReplaceClass(unique_ptr expr, ExpressionClass expr_class, + const ReplaceFunction &callback); + template + static unique_ptr + PreorderReplace(unique_ptr expr, const std::function(const T &expr)> &callback) { + return PreorderReplaceClass(std::move(expr), T::TYPE, + [&](const Expression &child) { return callback(child.Cast()); }); + } + template static void VisitExpressionMutable(unique_ptr &expr, const std::function &)> &callback) { 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 330300db7..91b060325 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 @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/common/limits.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/enums/expression_type.hpp" @@ -93,7 +94,9 @@ struct TableFilterFunctions { class BloomFilter { public: BloomFilter() = default; - void Initialize(ClientContext &context_p, idx_t number_of_rows); + //! 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()); //! 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 diff --git a/src/duckdb/src/include/duckdb/planner/logical_operator_deep_copy.hpp b/src/duckdb/src/include/duckdb/planner/logical_operator_deep_copy.hpp index 1d2547cfe..e261ebfaa 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_operator_deep_copy.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_operator_deep_copy.hpp @@ -28,7 +28,7 @@ class LogicalOperatorDeepCopy : public LogicalOperatorVisitor { public: LogicalOperatorDeepCopy(Binder &binder, optional_ptr parameter_data); - unique_ptr DeepCopy(unique_ptr &op); + unique_ptr DeepCopy(const unique_ptr &op); private: void VisitOperator(LogicalOperator &op) override; diff --git a/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp b/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp index 122f2b41e..c0ed45bfa 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp @@ -30,7 +30,6 @@ class LogicalDelimGet; class LogicalDistinct; class LogicalDummyScan; class LogicalEmptyResult; -class LogicalExecute; class LogicalExplain; class LogicalExport; class LogicalExpressionGet; diff --git a/src/duckdb/src/include/duckdb/planner/operator/list.hpp b/src/duckdb/src/include/duckdb/planner/operator/list.hpp index 2b7a50ff3..7df2c6522 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/list.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/list.hpp @@ -17,7 +17,6 @@ #include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_dummy_scan.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" -#include "duckdb/planner/operator/logical_execute.hpp" #include "duckdb/planner/operator/logical_explain.hpp" #include "duckdb/planner/operator/logical_export.hpp" #include "duckdb/planner/operator/logical_expression_get.hpp" diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_execute.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_execute.hpp deleted file mode 100644 index 7d909287e..000000000 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_execute.hpp +++ /dev/null @@ -1,47 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/planner/operator/logical_execute.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/prepared_statement_data.hpp" -#include "duckdb/planner/logical_operator.hpp" - -namespace duckdb { - -class LogicalExecute : public LogicalOperator { -public: - static constexpr const LogicalOperatorType TYPE = LogicalOperatorType::LOGICAL_EXECUTE; - -public: - explicit LogicalExecute(shared_ptr prepared_p) - : LogicalOperator(LogicalOperatorType::LOGICAL_EXECUTE), prepared(std::move(prepared_p)) { - D_ASSERT(prepared); - types = prepared->types; - } - - shared_ptr prepared; - -public: - //! Skips the serialization check in VerifyPlan - bool SupportSerialization() const override { - return false; - } - //! Without a rebound child plan, the prepared plan is executed as-is and was already optimized - bool RequireOptimizer() const override { - return !children.empty(); - } - -protected: - void ResolveTypes() override { - types = prepared->types; - } - vector GetColumnBindings() override { - return GenerateColumnBindings(TableIndex(0), types.size()); - } -}; -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_update.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_update.hpp index 2a85e5909..fbeeda7f5 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_update.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_update.hpp @@ -11,7 +11,6 @@ #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/bound_constraint.hpp" #include "duckdb/common/index_map.hpp" -#include "duckdb/common/enums/row_id_handling.hpp" namespace duckdb { struct CreateInfo; @@ -40,9 +39,6 @@ class LogicalUpdate : public LogicalOperator { vector> bound_defaults; vector> bound_constraints; bool update_is_del_and_insert; - //! how to handle a target row-id appearing more than once in the input (e.g. UPDATE ... FROM): keep the - //! lock-free path (ASSUME_UNIQUE), deduplicate keeping the first match (KEEP_FIRST), or error (ERROR) - RowIdHandling row_id_handling = RowIdHandling::ASSUME_UNIQUE; public: void Serialize(Serializer &serializer) const override; diff --git a/src/duckdb/src/include/duckdb/planner/planner.hpp b/src/duckdb/src/include/duckdb/planner/planner.hpp index 9d0e0914a..e73823cd3 100644 --- a/src/duckdb/src/include/duckdb/planner/planner.hpp +++ b/src/duckdb/src/include/duckdb/planner/planner.hpp @@ -16,6 +16,11 @@ namespace duckdb { class ClientContext; class PreparedStatementData; +class ExecuteStatement; + +//! FULL plans for execution; BIND_ONLY stops after the bind, which already decides names, types, parameters and +//! properties +enum class PlanningMode : uint8_t { FULL, BIND_ONLY }; //! The planner creates a logical query plan from the parsed SQL statements //! using the Binder and LogicalPlanGenerator. @@ -23,7 +28,7 @@ class Planner { friend class Binder; public: - explicit Planner(ClientContext &context); + explicit Planner(ClientContext &context, PlanningMode mode = PlanningMode::FULL); public: unique_ptr plan; @@ -33,10 +38,16 @@ class Planner { shared_ptr binder; ClientContext &context; + const PlanningMode mode; StatementProperties properties; bound_parameter_map_t value_map; + //! Whether a top-level EXECUTE may re-use the physical plan of its prepared statement + bool reuse_prepared_plans = false; + //! The prepared statement whose physical plan is re-used - set instead of plan + shared_ptr reused_statement; + public: void CreatePlan(unique_ptr statement); //! Apply the execution planner's optimizer policy, including mandatory rewrites. @@ -46,6 +57,7 @@ class Planner { private: void CreatePlan(SQLStatement &statement); + void CreateExecutePlan(ExecuteStatement &statement); shared_ptr PrepareSQLStatement(unique_ptr statement); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/table_binding.hpp b/src/duckdb/src/include/duckdb/planner/table_binding.hpp index 4b8d87272..75d9c5b03 100644 --- a/src/duckdb/src/include/duckdb/planner/table_binding.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_binding.hpp @@ -174,7 +174,8 @@ struct DummyBinding : public Binding { unique_ptr ParamToArg(ColumnRefExpression &col_ref); }; -enum class CTEType { CAN_BE_REFERENCED, CANNOT_BE_REFERENCED }; +//! CANNOT_BE_REFERENCED_RECURSIVE is the binding of a recursive CTE outside its recursive term +enum class CTEType { CAN_BE_REFERENCED, CANNOT_BE_REFERENCED, CANNOT_BE_REFERENCED_RECURSIVE }; struct CTEBinding; struct CTEBindState { @@ -205,6 +206,7 @@ struct CTEBinding : public Binding { public: bool CanBeReferenced() const; + bool IsRecursiveSelfReference() const; bool IsReferenced() const; void Reference(); 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 f10e202ad..f3328b8b4 100644 --- a/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp @@ -51,10 +51,10 @@ struct TableFilterState { struct ExpressionFilterState : public TableFilterState { public: - ExpressionFilterState(ClientContext &context, const Expression &expression); + ExpressionFilterState(Context &context, const Expression &expression); ~ExpressionFilterState() override; - ClientContext &GetContext() { + Context &GetContext() { D_ASSERT(executor); return executor->GetContext(); } diff --git a/src/duckdb/src/include/duckdb/storage/allocator_cache_retention.hpp b/src/duckdb/src/include/duckdb/storage/allocator_cache_retention.hpp new file mode 100644 index 000000000..329f689db --- /dev/null +++ b/src/duckdb/src/include/duckdb/storage/allocator_cache_retention.hpp @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/storage/allocator_cache_retention.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/array.hpp" +#include "duckdb/common/atomic.hpp" +#include "duckdb/common/typedefs.hpp" + +namespace duckdb { + +//! Approximate recent returns minus reuse, decaying linearly after each time bucket ends. +class AllocatorCacheRetention { + friend class BlockAllocatorTestHelper; + +public: + static constexpr idx_t INTERVAL_MS = 500; + static constexpr idx_t DECAY_MS = 1000; + static constexpr idx_t BUCKET_COUNT = DECAY_MS / INTERVAL_MS + 1; + + AllocatorCacheRetention() { + Reset(0); + } + + //! Reset only before publication or when callers are quiescent. + void Reset(idx_t now_ms); + void Return(idx_t count, idx_t capacity, idx_t now_ms); + void Reuse(idx_t count, idx_t now_ms); + idx_t Target(idx_t now_ms) const; + +private: + //! Generation and count share one atomic word so slot reuse cannot race a stale update. + array, BUCKET_COUNT> buckets; +}; + +} // 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 4981f3a47..80bea9939 100644 --- a/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp +++ b/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp @@ -133,18 +133,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)...)); } diff --git a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp index 9aea74a32..5cac17bae 100644 --- a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp @@ -17,6 +17,7 @@ #include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/unique_ptr.hpp" +#include "duckdb/storage/allocator_cache_retention.hpp" namespace duckdb { @@ -74,6 +75,9 @@ class BlockAllocator { bool TryFlushDeallocated(idx_t threshold, idx_t memory_headroom) const noexcept DUCKDB_EXCLUDES(flush_lock); private: + //! Explicit pool geometry for tests; production construction uses the CPU-count heuristic. + 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; @@ -84,21 +88,22 @@ class BlockAllocator { bool TryUsePool() const DUCKDB_EXCLUDES(pool_init_lock); bool InitializePool() const DUCKDB_EXCLUDES(pool_init_lock); + bool ProtectPoolGuards(data_ptr_t pointer) const; bool IsInitialized() const; bool IsInPool(data_ptr_t pointer) const; + bool IsGuardBlock(uint32_t block_id) const; + idx_t GetGuardBlockCount() const; + idx_t GetUsableBlockCount() const; 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; void VerifyBlockID(uint32_t block_id) const; - void InitializeRetention(idx_t now_ms) const; - void AddRetention(idx_t count, idx_t now_ms) const; - void ReuseRetention(idx_t count, idx_t now_ms) const; - idx_t RetentionTarget(idx_t now_ms) const; void UpdateCachedBlocks(int64_t count, idx_t slot) const; idx_t GetCachedPoolMemory() const; void ReturnThreadLocalBlocks() const; @@ -139,7 +144,7 @@ class BlockAllocator { //! Shift for dividing by block size const idx_t block_size_div_shift; - //! Fixed capacity, rounded down to whole blocks; zero on 32-bit. + //! Virtual reservation, including guards, rounded down to whole blocks; zero on 32-bit. const idx_t pool_size; //! Allocation permission is independent of the lifetime of the mapping. atomic enabled {true}; @@ -153,6 +158,8 @@ class BlockAllocator { mutable unsafe_unique_ptr untouched; //! Touched by block IDs unsafe_unique_ptr touched; + //! Rotates maintenance across the immutable pool ranges. + mutable idx_t reclaim_shard DUCKDB_GUARDED_BY(flush_lock) = 0; struct alignas(64) CachedBlockCount { //! Cross-thread reuse can make individual balances negative. @@ -167,8 +174,8 @@ class BlockAllocator { //! Synchronizes returning cached blocks with allocator destruction. shared_ptr lifetime_state; - //! Approximate retention volume, with a generation and count packed into each bucket. - mutable array, 3> retention_buckets; + //! Recently returned volume retained for reuse before gradual decay. + mutable AllocatorCacheRetention retention; //! Protect maintenance decisions and background scheduling. mutable annotated_mutex flush_lock; //! Scheduler queue destruction invalidates this token before allocator destruction. diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp index e5b62dc53..99c461055 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp @@ -25,7 +25,6 @@ class ClientContext; class ColumnSegment; class DatabaseInstance; class Deserializer; -class Connection; class DuckTransaction; class DuckTransactionManager; class IndexCatalogEntry; @@ -46,25 +45,22 @@ class PendingPublication; struct BoundCreateTableInfo; struct CheckpointOptions; -//! Wrapper to manage the lifetime of a checkpoint connection and transaction. +//! Wrapper to manage the lifetime of a checkpoint transaction. class ActiveCheckpointWrapper { public: - //! Creates a connection if we have a context. - //! If there is no context, we are on shutdown and a checkpoint connection/transaction is not created. - ActiveCheckpointWrapper(Context &context, AttachedDatabase &db, DuckTransactionManager &transaction_manager); + //! Without a checkpoint context, we are on shutdown and a checkpoint transaction is not created. + ActiveCheckpointWrapper(optional_ptr checkpoint_context, AttachedDatabase &db, + DuckTransactionManager &transaction_manager); ~ActiveCheckpointWrapper(); //! Registers the checkpoint (id, bound, active checkpoint), through a checkpoint transaction if there is a context void Begin(CheckpointOptions &options); void Commit(); - //! The context of the checkpoint connection, null when there is none (shutdown path) - optional_ptr GetCheckpointContext() const; private: AttachedDatabase &db; DuckTransactionManager &transaction_manager; - unique_ptr checkpoint_connection; optional_ptr checkpoint_context; optional_ptr checkpoint_transaction; //! Whether Begin registered an active checkpoint that Commit has not reset yet @@ -73,8 +69,8 @@ class ActiveCheckpointWrapper { class CheckpointWriter { public: - //! The client context is only set for explicit checkpoints, which bind buffered index operations before writing - CheckpointWriter(AttachedDatabase &db, QueryContext context, optional_ptr client_context = nullptr); + CheckpointWriter(AttachedDatabase &db, QueryContext context, + optional_ptr checkpoint_context = nullptr); virtual ~CheckpointWriter(); //! The database @@ -84,10 +80,6 @@ class CheckpointWriter { Context &GetContext() const { return context; } - //! The client that triggered an explicit checkpoint (null for checkpoints on commit and on shutdown) - optional_ptr TryGetClientContext() const { - return client_context; - } virtual void CreateCheckpoint() = 0; virtual MetadataManager &GetMetadataManager() = 0; @@ -95,11 +87,12 @@ class CheckpointWriter { virtual unique_ptr GetTableDataWriter(TableCatalogEntry &table) = 0; private: - shared_ptr owned_context; Context &context; - optional_ptr client_context; protected: + //! The context the checkpoint transaction runs in (null on shutdown and DETACH) + optional_ptr checkpoint_context; + virtual void WriteEntry(CatalogEntry &entry, Serializer &serializer); virtual void WriteSchema(SchemaCatalogEntry &schema, Serializer &serializer); virtual void WriteTable(TableCatalogEntry &table, Serializer &serializer) = 0; @@ -159,7 +152,7 @@ class SingleFileCheckpointWriter final : public CheckpointWriter { public: SingleFileCheckpointWriter(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, - CheckpointOptions options, optional_ptr client_context = nullptr); + CheckpointOptions options, optional_ptr checkpoint_context = nullptr); ~SingleFileCheckpointWriter() override; void CreateCheckpoint() override; @@ -183,9 +176,6 @@ class SingleFileCheckpointWriter final : public CheckpointWriter { void AddPendingPublication(unique_ptr publication); private: - //! Context of the checkpoint transaction, used for catalog lookups during the checkpoint. - //! Only set while CreateCheckpoint runs, which owns the connection it belongs to. - optional_ptr checkpoint_context; //! The metadata writer is responsible for writing schema information unique_ptr metadata_writer; //! The table data writer is responsible for writing the DataPointers used by the table chunks diff --git a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_analyze.hpp b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_analyze.hpp index a1f9ee015..e8dc3d8dc 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_analyze.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_analyze.hpp @@ -23,61 +23,32 @@ struct AlpAnalyzeState : public AnalyzeState { public: using EXACT_TYPE = typename FloatingToExact::TYPE; - explicit AlpAnalyzeState(BlockManager &block_manager) : AnalyzeState(block_manager), compression_data() { + AlpAnalyzeState(BlockManager &block_manager, bool has_fallback) + : AnalyzeState(block_manager), has_fallback(has_fallback) { } - idx_t total_bytes_used = 0; - idx_t current_bytes_used_in_segment = 0; + //! Flag indicating support for uncompressed storage in case of many exceptions. + const bool has_fallback; idx_t vectors_sampled_count = 0; idx_t total_values_count = 0; idx_t vectors_count = 0; vector> rowgroup_sample; vector> complete_vectors_sampled; alp::AlpCompressionData compression_data; - StorageVersion storage_version = StorageVersion::INVALID; - -public: - // Returns the required space to hyphotetically store the compressed segment - void FlushSegment() { - // We add the size of the segment header (the pointer to the metadata) - total_bytes_used += current_bytes_used_in_segment + AlpConstants::METADATA_POINTER_SIZE; - current_bytes_used_in_segment = 0; - } - - void FlushVector(idx_t vector_size) { - current_bytes_used_in_segment += vector_size; - compression_data.Reset(); - } - - // Check if we have enough space in the segment to hyphotetically store the compressed vector - bool HasEnoughSpace(idx_t vector_size) { - idx_t bytes_to_be_used = AlignValue(current_bytes_used_in_segment + vector_size); - // We have enough space if the already used space + the required space for a new vector - // does not exceed the space of the block - the segment header (the pointer to the metadata) - return bytes_to_be_used <= (info.GetBlockSize() - AlpConstants::METADATA_POINTER_SIZE); - } - - idx_t TotalUsedBytes() const { - return AlignValue(total_bytes_used); - } }; template unique_ptr AlpInitAnalyze(ColumnData &col_data, PhysicalType type) { - auto &storage_manager = col_data.GetStorageManager(); auto &block_manager = col_data.GetBlockManager(); - const auto storage_version = storage_manager.GetStorageVersion(); + const auto storage_version = col_data.GetStorageManager().GetStorageVersion(); + const bool has_fallback = !StorageManager::IsPriorToVersion(StorageVersion::V1_5_0, storage_version); - if (block_manager.GetBlockSize() + block_manager.GetBlockHeaderSize() < DEFAULT_BLOCK_ALLOC_SIZE) { - if (StorageManager::IsPriorToVersion(StorageVersion::V1_5_0, storage_version)) { - // Before v1.5.0, blocks cannot use uncompressed-vector fallback - return nullptr; - } + if (!has_fallback && + block_manager.GetBlockSize() + block_manager.GetBlockHeaderSize() < AlpConstants::MIN_BLOCK_SIZE) { + return nullptr; } - auto state = make_uniq>(block_manager); - state->storage_version = storage_version; - return unique_ptr(std::move(state)); + return make_uniq>(block_manager, has_fallback); } /* @@ -152,42 +123,46 @@ bool AlpAnalyze(AnalyzeState &state, const Vector &input) { template idx_t AlpFinalAnalyze(AnalyzeState &state) { auto &analyze_state = state.Cast>(); - - // Finding the Top K combinations of Exponent and Factor - alp::AlpCompression::FindTopKCombinations(analyze_state.rowgroup_sample, analyze_state.compression_data); - - // Encode the entire sampled vectors to estimate a compression size - idx_t compressed_values = 0; - for (auto &vector_to_compress : analyze_state.complete_vectors_sampled) { - alp::AlpCompression::Compress(vector_to_compress.data(), vector_to_compress.size(), - analyze_state.compression_data); - const idx_t uncompressed_size = AlpConstants::EXPONENT_SIZE + sizeof(T) * vector_to_compress.size(); - const idx_t compressed_size = analyze_state.compression_data.RequiredSpace(); - const bool should_compress = - compressed_size < uncompressed_size || - StorageManager::IsPriorToVersion(StorageVersion::V1_5_0, analyze_state.storage_version); - - const idx_t vector_size = should_compress ? compressed_size : uncompressed_size; - - if (!analyze_state.HasEnoughSpace(vector_size)) { - analyze_state.FlushSegment(); + auto &compression_data = analyze_state.compression_data; + + // Find the top combinations of exponent and factor. + alp::AlpCompression::FindTopKCombinations(analyze_state.rowgroup_sample, compression_data); + + // Encode the sampled vectors to estimate their storage size. + double sampled_values = 0; + double sampled_bytes = 0; + for (auto &sample : analyze_state.complete_vectors_sampled) { + alp::AlpCompression::Compress(sample.data(), sample.size(), compression_data); + auto vector_size = compression_data.RequiredSpace(); + if (analyze_state.has_fallback) { + const idx_t uncompressed_size = AlpConstants::EXPONENT_SIZE + sizeof(T) * sample.size(); + vector_size = MinValue(vector_size, uncompressed_size); } - analyze_state.FlushVector(vector_size); - compressed_values += vector_to_compress.size(); + sampled_bytes += vector_size; + sampled_values += sample.size(); + compression_data.Reset(); + } + + if (sampled_values == 0) { + return DConstants::INVALID_INDEX; } - // Flush last unfinished segment - analyze_state.FlushSegment(); + // Extrapolate sampled set to total count + const auto total_values = static_cast(analyze_state.total_values_count); + const auto sampling_factor = total_values / sampled_values; + auto estimated_size = sampled_bytes * sampling_factor; - if (compressed_values == 0) { + const auto vector_count = std::ceil(total_values / AlpConstants::ALP_VECTOR_SIZE); + estimated_size += vector_count * AlpConstants::METADATA_POINTER_SIZE; + + const auto usable_segment_size = static_cast(state.info.GetBlockSize() - AlpConstants::HEADER_SIZE); + const auto segment_count = std::ceil(estimated_size / usable_segment_size); + estimated_size = std::ceil(estimated_size + segment_count * AlpConstants::HEADER_SIZE); + if (estimated_size >= static_cast(DConstants::INVALID_INDEX)) { return DConstants::INVALID_INDEX; } - - // We estimate the size by taking into account the portion of the values we took - const auto factor_of_sampling = analyze_state.total_values_count / compressed_values; - const auto final_analyze_size = analyze_state.TotalUsedBytes() * factor_of_sampling; - return final_analyze_size; // return size of data in bytes + return AlignValue(LossyNumericCast(estimated_size)); } } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_compress.hpp b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_compress.hpp index 219293063..978637f10 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_compress.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_compress.hpp @@ -9,12 +9,9 @@ #pragma once #include "duckdb/common/helper.hpp" -#include "duckdb/common/operator/subtract.hpp" -#include "duckdb/common/types/null_value.hpp" #include "duckdb/function/compression_function.hpp" #include "duckdb/storage/compression/standard_compression_state.hpp" #include "duckdb/main/config.hpp" -#include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/compression/alp/algorithm/alp.hpp" #include "duckdb/storage/compression/alp/alp_analyze.hpp" #include "duckdb/storage/compression/patas/patas.hpp" @@ -211,7 +208,9 @@ struct AlpCompressionState : public StandardCompressionState { //! We compact the block if the space used is less than a threshold const auto used_space_percentage = static_cast(metadata_offset + bytes_used_by_metadata) / static_cast(total_segment_size); + const auto data_end = UsedSpace(); if (used_space_percentage < AlpConstants::COMPACT_BLOCK_THRESHOLD) { + memset(dataptr + data_end, 0, metadata_offset - data_end); #ifdef DEBUG //! Copy the first 4 bytes of the metadata AlpConstants::METADATA_POINTER_TYPE verify_bytes; @@ -223,6 +222,8 @@ struct AlpCompressionState : public StandardCompressionState { D_ASSERT(verify_bytes == *(AlpConstants::METADATA_POINTER_TYPE *)(dataptr + metadata_offset)); #endif total_segment_size = metadata_offset + bytes_used_by_metadata; + } else { + memset(dataptr + data_end, 0, info.GetBlockSize() - bytes_used_by_metadata - data_end); } // Store the offset to the end of metadata (to be used as a backwards pointer in decoding) diff --git a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_constants.hpp b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_constants.hpp index d43e89862..ad65870fb 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_constants.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_constants.hpp @@ -25,6 +25,15 @@ class AlpConstants { using BIT_WIDTH_TYPE = uint8_t; using METADATA_POINTER_TYPE = uint32_t; + //! Conservative upper bounds on encoded vector size, combining maximum bitpacked data and exception sizes. + //! Formula: vector_size * max_bit_width / 8 + vector_size * (original_type_size + position_size) + + //! encoding_metadata + //! + //! DOUBLE: 1024 * 64 / 8 + 1024 * (8 + 2) + 13 = 18445 bytes < 32 KiB + //! FLOAT: 1024 * 64 / 8 + 1024 * (4 + 2) + 13 = 14349 bytes < 32 KiB + //! 32 KiB also accommodates block/segment headers, vector pointers and alignment. + static constexpr idx_t MIN_BLOCK_SIZE = static_cast(1024 * 32); + static constexpr uint32_t ALP_VECTOR_SIZE = 1024; static constexpr uint32_t RG_SAMPLES = 8; static constexpr uint16_t SAMPLES_PER_VECTOR = 32; diff --git a/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_compress.hpp b/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_compress.hpp index 69a743170..36e903556 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_compress.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_compress.hpp @@ -207,7 +207,9 @@ struct AlpRDCompressionState : public StandardCompressionState { //! We compact the block if the space used is less than a threshold const auto used_space_percentage = static_cast(metadata_offset + bytes_used_by_metadata) / static_cast(total_segment_size); + const auto data_end = UsedSpace(); if (used_space_percentage < AlpConstants::COMPACT_BLOCK_THRESHOLD) { + memset(dataptr + data_end, 0, metadata_offset - data_end); #ifdef DEBUG //! Copy the first 4 bytes of the metadata AlpRDConstants::METADATA_POINTER_TYPE verify_bytes; @@ -219,6 +221,8 @@ struct AlpRDCompressionState : public StandardCompressionState { D_ASSERT(verify_bytes == *(AlpRDConstants::METADATA_POINTER_TYPE *)(dataptr + metadata_offset)); #endif total_segment_size = metadata_offset + bytes_used_by_metadata; + } else { + memset(dataptr + data_end, 0, info.GetBlockSize() - bytes_used_by_metadata - data_end); } // Store the offset to the end of metadata (to be used as a backwards pointer in decoding) diff --git a/src/duckdb/src/include/duckdb/storage/object_cache.hpp b/src/duckdb/src/include/duckdb/storage/object_cache.hpp index b133749ed..4c4ed3a05 100644 --- a/src/duckdb/src/include/duckdb/storage/object_cache.hpp +++ b/src/duckdb/src/include/duckdb/storage/object_cache.hpp @@ -85,7 +85,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 @@ -159,7 +159,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)...); } diff --git a/src/duckdb/src/include/duckdb/storage/sharded_allocator_queue.hpp b/src/duckdb/src/include/duckdb/storage/sharded_allocator_queue.hpp new file mode 100644 index 000000000..f9f52d73d --- /dev/null +++ b/src/duckdb/src/include/duckdb/storage/sharded_allocator_queue.hpp @@ -0,0 +1,175 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/storage/sharded_allocator_queue.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/atomic.hpp" +#include "duckdb/common/helper.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/common/vector.hpp" +#include "duckdb/parallel/concurrentqueue.hpp" + +#include +#include + +namespace duckdb { + +template > +class ShardedAllocatorQueue { + static_assert(std::is_trivially_copyable::value, "Allocator queue entries must be trivially copyable"); + +public: + struct alignas(64) Shard { + bool Enqueue(T value) { + return EnqueueInternal( + 1, [&] { return q.enqueue(value); }, [&] { return EnqueueOverflow(&value, 1); }); + } + template + bool EnqueueBulk(ITERATOR begin, idx_t size) { +#ifdef DUCKDB_NO_THREADS + // The single-threaded queue can throw after publishing a prefix of a batch. + for (idx_t i = 0; i < size; i++) { + if (!Enqueue(begin[i])) { + return false; + } + } + return true; +#else + return EnqueueInternal( + size, [&] { return q.enqueue_bulk(begin, size); }, [&] { return EnqueueOverflow(begin, size); }); +#endif + } + bool TryDequeue(T &value) { + return TryDequeueInternal([&] { return idx_t(q.try_dequeue(value)); }, + [&] { return DequeueOverflow(&value, 1); }) != 0; + } + template + idx_t TryDequeueBulk(ITERATOR begin, idx_t size) { + return TryDequeueInternal([&] { return q.try_dequeue_bulk(begin, size); }, + [&] { return DequeueOverflow(begin, size); }); + } + idx_t SizeApprox() const { + return track_count ? count.load(std::memory_order_relaxed) + : q.size_approx() + overflow_count.load(std::memory_order_relaxed); + } + //! Reserve before publication: fixed-pool returns must survive queue allocation failure. + void ReserveOverflow(idx_t capacity) { + if (capacity == 0) { + overflow.reset(); + } else { + overflow = make_uniq>(capacity); + } + } + + bool track_count = false; + + private: + template + bool EnqueueInternal(idx_t size, ENQUEUE enqueue, ENQUEUE_OVERFLOW enqueue_overflow) { + if (track_count) { + count.fetch_add(size, std::memory_order_relaxed); + } + try { + bool queued = false; + try { + queued = enqueue(); + } catch (const std::bad_alloc &) { + // The single-threaded queue reports allocation failure by throwing. + } + if (queued || enqueue_overflow()) { + return true; + } + } catch (...) { + if (track_count) { + count.fetch_sub(size, std::memory_order_relaxed); + } + throw; + } + if (track_count) { + count.fetch_sub(size, std::memory_order_relaxed); + } + return false; + } + template + idx_t TryDequeueInternal(DEQUEUE dequeue, DEQUEUE_OVERFLOW dequeue_overflow) { + if (track_count && count.load(std::memory_order_relaxed) == 0) { + return 0; + } + auto obtained = dequeue(); + if (obtained == 0) { + obtained = dequeue_overflow(); + } + if (track_count && obtained > 0) { + count.fetch_sub(obtained, std::memory_order_relaxed); + } + return obtained; + } + template + bool EnqueueOverflow(ITERATOR begin, idx_t size) { + if (!overflow) { + return false; + } + lock_guard guard(overflow_lock); + const auto current = overflow_count.load(std::memory_order_relaxed); + if (size > overflow->size() - current) { + return false; + } + for (idx_t i = 0; i < size; i++) { + (*overflow)[current + i] = begin[i]; + } + overflow_count.store(current + size, std::memory_order_relaxed); + return true; + } + template + idx_t DequeueOverflow(ITERATOR begin, idx_t size) { + if (overflow_count.load(std::memory_order_relaxed) == 0) { + return 0; + } + lock_guard guard(overflow_lock); + const auto current = overflow_count.load(std::memory_order_relaxed); + const auto obtained = MinValue(size, current); + for (idx_t i = 0; i < obtained; i++) { + begin[i] = (*overflow)[current - obtained + i]; + } + overflow_count.store(current - obtained, std::memory_order_relaxed); + return obtained; + } + + QUEUE q; + mutex overflow_lock; + unique_ptr> overflow; + atomic overflow_count {0}; + alignas(64) atomic count {0}; + }; + +public: + explicit ShardedAllocatorQueue(idx_t count, bool track_count = false) : queues(count) { + D_ASSERT(count > 0); + for (auto &queue : queues) { + queue.track_count = track_count; + } + } + idx_t Count() const { + return queues.size(); + } + Shard &Get(idx_t shard) { + return queues[shard]; + } + idx_t SizeApprox() const { + idx_t count = 0; + for (auto &queue : queues) { + count += queue.SizeApprox(); + } + return count; + } + +private: + vector queues; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp index 10a863be5..6cd54f03a 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp @@ -91,7 +91,7 @@ struct NumericStats { DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); template - static inline void UpdateValue(T new_value, T &min, T &max) { + static inline void UpdateValue(const T &new_value, T &min, T &max) { min = Min::Operation(new_value, min); max = Max::Operation(new_value, max); if constexpr (std::is_floating_point_v) { diff --git a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp index 30e129d47..16f6f9c3f 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp @@ -80,6 +80,8 @@ class StorageManager { bool HasWAL() const; void AddWALSize(idx_t size); void SetWALSize(idx_t size); + void MarkBufferedIndexReplays(); + bool HasBufferedIndexReplays() const; //! Gets the number of WAL entries since last checkpoint idx_t GetWALEntriesCount() const; void ResetWALEntriesCount(); @@ -189,6 +191,8 @@ class StorageManager { //! WAL. atomic wal_size; atomic wal_entries_count; + //! Set when an unbound index buffers an operation. Cleared by BindIndexesForCheckpoint once none remain. + atomic buffered_index_replays {false}; //! Storage options passed in through configuration StorageOptions storage_options; //! Header prefetched during file-type detection, consumed by LoadDatabase. Empty unless a DuckDB file via ATTACH. @@ -234,6 +238,10 @@ class SingleFileStorageManager : public StorageManager { void LoadDatabase(QueryContext context) override; unique_ptr CreateCheckpointWriter(QueryContext context, CheckpointOptions options, - optional_ptr client_context); + optional_ptr checkpoint_context); + +private: + //! Returns false if the checkpoint must be skipped to keep buffered index replays. + bool BindIndexesForCheckpoint(optional_ptr checkpoint_context, bool explicit_checkpoint); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/table/column_segment.hpp b/src/duckdb/src/include/duckdb/storage/table/column_segment.hpp index 16c26498a..58a8b6a6b 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_segment.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_segment.hpp @@ -50,7 +50,7 @@ class ColumnSegment final : public SegmentBase, public BlockPacka DataPointer &data_pointer); static unique_ptr CreateTransientSegment(DatabaseInstance &db, const CompressionFunction &function, const LogicalType &type, const idx_t segment_size, - BlockManager &block_manager); + BlockManager &block_manager, bool zero_initialize = false); public: void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state); diff --git a/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp b/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp index 4ee40b19c..3788fcb73 100644 --- a/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp @@ -19,7 +19,7 @@ class InMemoryCheckpointer final : public CheckpointWriter { public: InMemoryCheckpointer(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, StorageManager &storage_manager, CheckpointOptions options, - optional_ptr client_context = nullptr); + optional_ptr checkpoint_context = nullptr); void CreateCheckpoint() override; diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 3014ab186..563f1eb9e 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -99,8 +99,10 @@ class LocalTableStorage : public enable_shared_from_this { void Rollback(); idx_t EstimatedSize() const; - void AppendToIndexes(DuckTransaction &transaction, TableAppendState &append_state); - void AppendToTable(DuckTransaction &transaction, TableAppendState &append_state); + //! Appends to the table's indexes at commit. A returned error means the indexes were restored. + ErrorData AppendToIndexes(DuckTransaction &transaction, TableAppendState &append_state); + //! Appends to the table at commit. A returned error means the table and its indexes were restored. + ErrorData AppendToTable(DuckTransaction &transaction, TableAppendState &append_state); ErrorData AppendToIndexes(DuckTransaction &transaction, RowGroupCollection &source, TableIndexList &index_list, const vector &table_types, row_t &start_row); //! Removes the rows of this storage that were appended to the indexes of the table at [row_start, row_end) @@ -243,6 +245,7 @@ class LocalStorage { 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); }; diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 4ee4651ce..c9e23c16a 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1570,6 +1570,20 @@ typedef struct { (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_ERROR(*duckdb_v2_table_function_add_virtual_column) + (duckdb_v2_table_function_handle function, DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_bind_data) + (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_global_state) + (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_user_data) + (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_set) + (duckdb_v2_table_function_metrics_info_handle info, const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_metrics_callback) + (duckdb_v2_table_function_handle function, duckdb_v2_table_function_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_check_statistics) (duckdb_v2_context_handle context, duckdb_v2_expression_handle expression, duckdb_v2_stats_handle stats, DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, duckdb_v2_error_info_handle *err); @@ -3599,6 +3613,25 @@ typedef struct { #define duckdb_v2_statement_add_collection duckdb_ext_api.duckdb_v2_statement_add_collection #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_add_virtual_column duckdb_ext_api.duckdb_v2_table_function_add_virtual_column +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_metrics_get_bind_data duckdb_ext_api.duckdb_v2_table_function_metrics_get_bind_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_metrics_get_global_state \ + duckdb_ext_api.duckdb_v2_table_function_metrics_get_global_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_metrics_get_user_data duckdb_ext_api.duckdb_v2_table_function_metrics_get_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_metrics_set duckdb_ext_api.duckdb_v2_table_function_metrics_set +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_set_metrics_callback duckdb_ext_api.duckdb_v2_table_function_set_metrics_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_expression_check_statistics duckdb_ext_api.duckdb_v2_expression_check_statistics #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index f57da675d..853ec5d32 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -11820,10 +11820,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_next(duckdb_v2_stateme * * Binding is read-only and does not disturb a live result: it begins no query, claims no cursor, reuses an active * transaction read-only, and runs alongside a paused stream. It is single-consumer like the stepping functions, so bind - * concurrently only on a second connection. Prepare-time errors — binder, catalog, preprocessing — surface here. A - * statement that expands into a group (a dynamic PIVOT, or statement-expanding DDL such as ALTER ADD COLUMN with a - * non-constant DEFAULT) has a schema known only at execution, and is reported with ERROR_INPUT_METADATA_DEFERRED; - * execute it instead. + * concurrently only on a second connection. Errors of the bind itself (catalog lookups, type resolution, preprocessing) + * surface here; errors of the planning after the bind (the plan depth limit, a correlated subquery or trigger body that + * decorrelation refuses) may surface only when the statement is executed. A statement that expands into a group (a + * dynamic PIVOT, or statement-expanding DDL such as ALTER ADD COLUMN with a non-constant DEFAULT) has a schema known + * only at execution, and is reported with ERROR_INPUT_METADATA_DEFERRED; execute it instead. * * *out_schema and *out_parameters are set to NULL on failure. * @@ -13188,6 +13189,22 @@ typedef enum DUCKDB_V2_TABLE_PARTITION_INFO { DUCKDB_V2_TABLE_PARTITION_INFO_MAX_ENUM = 0x7FFFFFFF, } DUCKDB_V2_TABLE_PARTITION_INFO; +/*! + * A column a table function can produce next to the columns it declares in bind. A query asks for it by name, but it is + * not part of the function's result columns. Declared with `duckdb_v2_table_function_add_virtual_column()`. In the + * column lists of the scan (e.g. `duckdb_v2_table_function_exec_get_column_index()`), a virtual column is identified by + * 2^63 plus its value in this enum. + */ +typedef enum DUCKDB_V2_TABLE_VIRTUAL_COLUMN { + /*! + * `file_row_number`, a BIGINT holding the position of the row within the file it was read from, counting from 0. A + * function that reads a single file produces it when it is wrapped in a multi-file function (see + * `duckdb_v2_multi_file_function_create()`), which is where the name of the file comes from. + */ + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER = 0, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_VIRTUAL_COLUMN; + /* --- Struct forward declarations for table --- */ /* --- Types for table --- */ @@ -13295,6 +13312,15 @@ typedef struct _duckdb_v2_table_function_claim_batch_info { void *internal_ptr; } * duckdb_v2_table_function_claim_batch_info_handle; +/*! + * A borrowed opaque handle to the arguments supplied to a table function when the engine collects the metrics of a + * scan. The "metrics" callback receives this handle and can use it to report the operator metrics of the scan, e.g. how + * many row groups it read. + */ +typedef struct _duckdb_v2_table_function_metrics_info { + void *internal_ptr; +} * duckdb_v2_table_function_metrics_info_handle; + /*! * A borrowed opaque handle to the arguments supplied to a table function when the engine asks it to describe a bound * call. The "get bind info" callback receives this handle, and can use it to describe the call in more detail than its @@ -13343,6 +13369,10 @@ typedef void (*duckdb_v2_table_function_progress_callback_fn)(duckdb_v2_table_fu duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_table_function_metrics_callback_fn)(duckdb_v2_table_function_metrics_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + typedef void (*duckdb_v2_table_function_filter_pushdown_callback_fn)( duckdb_v2_table_function_filter_pushdown_info_handle info, duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); @@ -13619,6 +13649,57 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(du duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Declares that the table function can produce the given virtual column. + * + * A virtual column is not one of the columns declared in bind: the query asks for it by name, and the function only + * produces it when it is asked for. It then takes up a vector of the exec callback's output chunk, like any other + * column the scan produces. This requires projection pushdown (see + * `duckdb_v2_table_function_set_projection_pushdown()`), which is what lets the engine ask for it. The global init, + * local init and exec callbacks recognize the vector by its column index, which is 2^63 plus the value of the + * `DUCKDB_V2_TABLE_VIRTUAL_COLUMN` (see e.g. `duckdb_v2_table_function_exec_get_column_index()`). + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to configure. + * @param column The virtual column the function can produce. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional metrics callback of the table function. + * + * The metrics callback is invoked when the engine collects the metrics of the scan, e.g. when profiling is enabled, and + * can report what the scan did through its `duckdb_v2_table_function_metrics_info_handle`. + * + * DuckDB does not synchronize the callback with the scan: each thread that scanned invokes it when it finishes, so it + * can run while other threads still scan and while other threads invoke it. The global state it reads is shared with + * those threads, so the function must synchronize what the callback reads from it, e.g. by keeping counters in atomics + * and reading them with an exchange, so that each amount is reported once. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the metrics callback of. + * @param callback The metrics callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_metrics_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Sets the optional filter pushdown callback of the table function. @@ -13631,6 +13712,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(du * predicate is a promise to filter the rows exactly as it would have. The optimizer may invoke the callback more than * once for the same query, each time with the predicates not yet accepted; it is not invoked when there are none. * + * A function that also has projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) is offered + * the predicates that apply to a single column of it once more when a scan starts, just before the global init + * callback, in the same form, with the column references resolved by + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` as at optimization time. This is how the callback of a + * function wrapped in a multi-file function sees the predicates, which the optimizer only offers to the wrapper. The + * engine applies these predicates to the rows the function produces itself, so the function may use them to skip what + * the query can never use but does not have to understand them, and accepting one has no effect. The scan keeps the + * columns the predicates are applied to. + * * history: * - unstable: v2.0.0 * @@ -14784,6 +14874,92 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats( duckdb_v2_table_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The metrics info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_user_data( + duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the bind data set by the function's bind callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The metrics info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_bind_data( + duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the global state set by the function's global init callback. + * + * The metrics callback can run while the scan is still running, so it must read the global state in a thread-safe way. + * The global state is null if the scan has not been initialized. + * + * history: + * - unstable: v2.0.0 + * + * @param info The metrics info handle. + * @param data Receives the global state pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_global_state( + duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reports an operator metric of the scan, by the name DuckDB's profiler uses for it (the names `tracked_metrics` + * accepts). + * + * The metrics a scan can report are counters: + * - `operator.rows_scanned`: the rows the scan read. + * - `operator.row_groups_scanned`: the row groups the scan read. A row group is the unit a format lets the scan skip, + * e.g. a Parquet row group or an ORC stripe. + * - `operator.total_row_groups_to_scan`: the row groups the scan read or skipped. + * - `operator.bytes_scanned`: the bytes the scan read. + * + * The engine may collect the metrics of a scan more than once, and adds up what it is told: each value is the amount + * since the metrics were last collected, except `operator.total_row_groups_to_scan`, which is the number found so far + * in all. Fails for a name that is not one of the above. + * + * history: + * - unstable: v2.0.0 + * + * @param info The metrics info handle. + * @param name The name of the metric. Borrowed. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8 and need not be null-terminated. + * @param value The value of the metric. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_set(duckdb_v2_table_function_metrics_info_handle info, + const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Registers the table function, making it available for use in SQL queries. diff --git a/src/duckdb/src/logging/log_manager.cpp b/src/duckdb/src/logging/log_manager.cpp index 55d2a3813..6ae3dc8fa 100644 --- a/src/duckdb/src/logging/log_manager.cpp +++ b/src/duckdb/src/logging/log_manager.cpp @@ -1,6 +1,6 @@ #include "duckdb/logging/log_type.hpp" #include "duckdb/logging/log_manager.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/logging/file_system_logger.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/client_context.hpp" @@ -10,6 +10,25 @@ namespace duckdb { +struct DeprecatedLogSinkName { + const char *old_name; + const char *new_name; +}; + +static const DeprecatedLogSinkName DEPRECATED_LOG_SINK_NAMES[] = {{"shell_log_storage", "shell_log_sink"}}; + +//! Maps a deprecated sink name to its new name and warns. Call it without holding the LogManager lock +static string ResolveDeprecatedLogSinkName(DatabaseInstance &db, const string &sink_name) { + for (auto &entry : DEPRECATED_LOG_SINK_NAMES) { + if (StringUtil::CIEquals(sink_name, entry.old_name)) { + DUCKDB_LOG_WARNING(db, "The log sink '%s' has been renamed to '%s', the old name is deprecated", + entry.old_name, entry.new_name); + return entry.new_name; + } + } + return sink_name; +} + unique_ptr LogManager::CreateLogger(const LoggingContext &context, bool thread_safe, bool mutable_settings) { annotated_unique_lock lck(lock); if (mutable_settings) { @@ -50,12 +69,12 @@ RegisteredLoggingContext LogManager::RegisterLoggingContext(const LoggingContext return RegisterLoggingContextInternal(context); } -bool LogManager::RegisterLogStorage(const string &name, shared_ptr &storage) { +bool LogManager::RegisterLogSink(const string &name, shared_ptr &sink) { annotated_unique_lock lck(lock); - if (registered_log_storages.find(name) != registered_log_storages.end()) { + if (registered_log_sinks.find(name) != registered_log_sinks.end()) { return false; } - registered_log_storages.insert({name, std::move(storage)}); + registered_log_sinks.insert({name, std::move(sink)}); return true; } @@ -69,22 +88,22 @@ shared_ptr LogManager::GlobalLoggerReference() { void LogManager::Flush() { annotated_unique_lock lck(lock); - log_storage->FlushAll(); + log_sink->FlushAll(); } -shared_ptr LogManager::GetLogStorage() { +shared_ptr LogManager::GetLogSink() { annotated_unique_lock lck(lock); - return log_storage; + return log_sink; } bool LogManager::CanScan(LoggingTargetTable table) { annotated_unique_lock lck(lock); - return log_storage->CanScan(table); + return log_sink->CanScan(table); } LogManager::LogManager(DatabaseInstance &db, LogConfig config_p) : config(make_shared_ptr(std::move(config_p))), db_instance(db) { - log_storage = make_uniq(db); + log_sink = make_uniq(db); } LogManager::~LogManager() { @@ -115,7 +134,7 @@ void LogManager::WriteLogEntry(timestamp_t timestamp, const char *log_type, LogL throw InvalidInputException(log_message); } else { annotated_unique_lock lck(lock); - log_storage->WriteLogEntry(timestamp, log_level, log_type, log_message, context); + log_sink->WriteLogEntry(timestamp, log_level, log_type, log_message, context); } } @@ -124,22 +143,24 @@ void LogManager::FlushCachedLogEntries(DataChunk &chunk, const RegisteredLogging } void LogManager::SetConfig(DatabaseInstance &db, const LogConfig &config_p) { + auto sink_name = ResolveDeprecatedLogSinkName(db, config_p.storage); + annotated_unique_lock lck(lock); - // We need extra handling for switching storage + // We need extra handling for switching sink auto new_config = config_p; - SetLogStorageInternal(db, new_config, config_p.storage); + SetLogSinkInternal(db, new_config, sink_name); SetConfigInternal(std::move(new_config)); } -pair> LogManager::GetConfigAndStorage() { +pair> LogManager::GetConfigAndSink() { annotated_unique_lock lck(lock); - return make_pair(*config, log_storage); + return make_pair(*config, log_sink); } -void LogManager::RestoreConfig(const LogConfig &config_p, shared_ptr storage) { +void LogManager::RestoreConfig(const LogConfig &config_p, shared_ptr sink) { annotated_unique_lock lck(lock); - log_storage = std::move(storage); + log_sink = std::move(sink); SetConfigInternal(config_p); } @@ -186,57 +207,59 @@ void LogManager::SetDisabledLogTypes(optional_ptr> disable SetConfigInternal(std::move(new_config)); } -void LogManager::SetLogStorage(DatabaseInstance &db, const string &storage_name) { +void LogManager::SetLogSink(DatabaseInstance &db, const string &requested_sink_name) { + auto sink_name = ResolveDeprecatedLogSinkName(db, requested_sink_name); + annotated_unique_lock lck(lock); - // 'SET logging_storage' cannot supply the path that file storage requires, so reject the switch - // here (active storage preserved) and point users at enable_logging instead of installing a - // path-less storage that throws on every later flush. - auto storage_name_to_lower = StringUtil::Lower(storage_name); - if (storage_name_to_lower == LogConfig::FILE_STORAGE_NAME && config->storage != storage_name_to_lower) { + // 'SET logging_sink' cannot supply the path that file sink requires, so reject the switch + // here (active sink preserved) and point users at enable_logging instead of installing a + // path-less sink that throws on every later flush. + auto sink_name_to_lower = StringUtil::Lower(sink_name); + if (sink_name_to_lower == LogConfig::FILE_STORAGE_NAME && config->storage != sink_name_to_lower) { throw InvalidConfigurationException( - "Cannot select 'file' log storage via 'SET logging_storage' because it requires a path. " + "Cannot select 'file' log sink via 'SET logging_sink' because it requires a path. " "Use CALL enable_logging(storage='file', storage_path='...') instead."); } auto new_config = *config; - SetLogStorageInternal(db, new_config, storage_name); + SetLogSinkInternal(db, new_config, sink_name); SetConfigInternal(std::move(new_config)); } -void LogManager::SetLogStorageInternal(DatabaseInstance &db, LogConfig &new_config, const string &storage_name) { - auto storage_name_to_lower = StringUtil::Lower(storage_name); +void LogManager::SetLogSinkInternal(DatabaseInstance &db, LogConfig &new_config, const string &sink_name) { + auto sink_name_to_lower = StringUtil::Lower(sink_name); // keep the lowercased name, so that it is recognized when set again - new_config.storage = storage_name_to_lower; - if (config->storage == storage_name_to_lower) { + new_config.storage = sink_name_to_lower; + if (config->storage == sink_name_to_lower) { return; } - if (storage_name_to_lower == LogConfig::FILE_STORAGE_NAME) { + if (sink_name_to_lower == LogConfig::FILE_STORAGE_NAME) { auto &fs = FileSystem::GetFileSystem(db); if (fs.SubSystemIsDisabled(LocalFileSystem().GetName())) { throw InvalidConfigurationException("Can not enable file logging with the LocalFileSystem disabled"); } } - // Flush the old storage, we are going to replace it. - log_storage->FlushAll(); - - if (storage_name_to_lower == LogConfig::IN_MEMORY_STORAGE_NAME) { - log_storage = make_shared_ptr(db); - } else if (storage_name_to_lower == LogConfig::STDOUT_STORAGE_NAME) { - log_storage = make_shared_ptr(db); - } else if (storage_name_to_lower == LogConfig::FILE_STORAGE_NAME) { - log_storage = make_shared_ptr(db); - } else if (registered_log_storages.find(storage_name_to_lower) != registered_log_storages.end()) { - log_storage = registered_log_storages[storage_name_to_lower]; + // Flush the old sink, we are going to replace it. + log_sink->FlushAll(); + + if (sink_name_to_lower == LogConfig::IN_MEMORY_STORAGE_NAME) { + log_sink = make_shared_ptr(db); + } else if (sink_name_to_lower == LogConfig::STDOUT_STORAGE_NAME) { + log_sink = make_shared_ptr(db); + } else if (sink_name_to_lower == LogConfig::FILE_STORAGE_NAME) { + log_sink = make_shared_ptr(db); + } else if (registered_log_sinks.find(sink_name_to_lower) != registered_log_sinks.end()) { + log_sink = registered_log_sinks[sink_name_to_lower]; } else { - throw InvalidInputException("Log storage '%s' is not yet registered", storage_name); + throw InvalidInputException("Log sink '%s' is not yet registered", sink_name); } } -void LogManager::UpdateLogStorageConfig(DatabaseInstance &db, case_insensitive_map_t &config_value) { +void LogManager::UpdateLogSinkConfig(DatabaseInstance &db, case_insensitive_map_t &config_value) { annotated_unique_lock lck(lock); - log_storage->UpdateConfig(db, config_value); + log_sink->UpdateConfig(db, config_value); } void LogManager::SetEnableStructuredLoggers(vector &enabled_logger_types) { @@ -265,9 +288,9 @@ void LogManager::SetEnableStructuredLoggers(vector &enabled_logger_types SetConfigInternal(std::move(new_config)); } -void LogManager::TruncateLogStorage() { +void LogManager::TruncateLogSink() { annotated_unique_lock lck(lock); - log_storage->Truncate(); + log_sink->Truncate(); } LogConfig LogManager::GetConfig() { diff --git a/src/duckdb/src/logging/log_storage.cpp b/src/duckdb/src/logging/log_sink.cpp similarity index 75% rename from src/duckdb/src/logging/log_storage.cpp rename to src/duckdb/src/logging/log_sink.cpp index 1b51d1867..4ddcb128d 100644 --- a/src/duckdb/src/logging/log_storage.cpp +++ b/src/duckdb/src/logging/log_sink.cpp @@ -1,4 +1,4 @@ -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/function/table_function.hpp" #include "duckdb/common/csv_writer.hpp" @@ -21,7 +21,7 @@ namespace duckdb { -vector LogStorage::GetSchema(LoggingTargetTable table) { +vector LogSink::GetSchema(LoggingTargetTable table) { switch (table) { case LoggingTargetTable::ALL_LOGS: { auto all_logs = GetSchema(LoggingTargetTable::LOG_CONTEXTS); @@ -51,7 +51,7 @@ vector LogStorage::GetSchema(LoggingTargetTable table) { } } -vector LogStorage::GetColumnNames(LoggingTargetTable table) { +vector LogSink::GetColumnNames(LoggingTargetTable table) { switch (table) { case LoggingTargetTable::ALL_LOGS: { auto all_logs = GetColumnNames(LoggingTargetTable::LOG_CONTEXTS); @@ -70,38 +70,38 @@ vector LogStorage::GetColumnNames(LoggingTargetTable table) { } } -unique_ptr LogStorage::CreateScanState(LoggingTargetTable table) const { - throw NotImplementedException("Not implemented for this LogStorage: CreateScanEntriesState"); +unique_ptr LogSink::CreateScanState(LoggingTargetTable table) const { + throw NotImplementedException("Not implemented for this LogSink: CreateScanEntriesState"); } -bool LogStorage::Scan(LogStorageScanState &state, DataChunk &result) const { - throw NotImplementedException("Not implemented for this LogStorage: ScanEntries"); +bool LogSink::Scan(LogSinkScanState &state, DataChunk &result) const { + throw NotImplementedException("Not implemented for this LogSink: ScanEntries"); } -void LogStorage::InitializeScan(LogStorageScanState &state) const { - throw NotImplementedException("Not implemented for this LogStorage: InitializeScanEntries"); +void LogSink::InitializeScan(LogSinkScanState &state) const { + throw NotImplementedException("Not implemented for this LogSink: InitializeScanEntries"); } -optional_idx LogStorage::GetScanRowCount(LoggingTargetTable table) const { +optional_idx LogSink::GetScanRowCount(LoggingTargetTable table) const { return optional_idx(); } -void LogStorage::Truncate() { - throw NotImplementedException("Not implemented for this LogStorage: TruncateLogStorage"); +void LogSink::Truncate() { + throw NotImplementedException("Not implemented for this LogSink: TruncateLogSink"); } -void LogStorage::UpdateConfig(DatabaseInstance &db, case_insensitive_map_t &config) { +void LogSink::UpdateConfig(DatabaseInstance &db, case_insensitive_map_t &config) { if (!config.empty()) { - throw InvalidInputException("Log storage '%s' does not support passing configuration", GetStorageName()); + throw InvalidInputException("Log sink '%s' does not support passing configuration", GetSinkName()); } } -unique_ptr LogStorage::BindReplace(ClientContext &context, TableFunctionBindInput &input, - LoggingTargetTable table) { +unique_ptr LogSink::BindReplace(ClientContext &context, TableFunctionBindInput &input, + LoggingTargetTable table) { return nullptr; } -CSVLogStorage::~CSVLogStorage() { +CSVLogSink::~CSVLogSink() { } -CSVLogStorage::CSVLogStorage(DatabaseInstance &db, bool normalize, idx_t buffer_size) - : BufferingLogStorage(db, buffer_size, normalize) { +CSVLogSink::CSVLogSink(DatabaseInstance &db, bool normalize, idx_t buffer_size) + : BufferingLogSink(db, buffer_size, normalize) { reader_options = make_uniq(); writer_options = make_uniq(*reader_options); @@ -112,17 +112,17 @@ CSVLogStorage::CSVLogStorage(DatabaseInstance &db, bool normalize, idx_t buffer_ ResetCastChunk(); } -void BufferingLogStorage::UpdateConfig(DatabaseInstance &db, case_insensitive_map_t &config) { +void BufferingLogSink::UpdateConfig(DatabaseInstance &db, case_insensitive_map_t &config) { lock_guard lck(lock); return UpdateConfigInternal(db, config); } -bool BufferingLogStorage::IsEnabled(LoggingTargetTable table) { +bool BufferingLogSink::IsEnabled(LoggingTargetTable table) { lock_guard lck(lock); return IsEnabledInternal(table); } -bool BufferingLogStorage::IsEnabledInternal(LoggingTargetTable table) { +bool BufferingLogSink::IsEnabledInternal(LoggingTargetTable table) { if (normalize_contexts) { return table == LoggingTargetTable::LOG_CONTEXTS || table == LoggingTargetTable::LOG_ENTRIES; } @@ -130,11 +130,11 @@ bool BufferingLogStorage::IsEnabledInternal(LoggingTargetTable table) { return table == LoggingTargetTable::ALL_LOGS; } -idx_t BufferingLogStorage::GetBufferLimit() const { +idx_t BufferingLogSink::GetBufferLimit() const { return buffer_limit; } -void CSVLogStorage::ExecuteCast(LoggingTargetTable table, DataChunk &chunk) { +void CSVLogSink::ExecuteCast(LoggingTargetTable table, DataChunk &chunk) { // Reset the cast buffer before use cast_buffers[table]->Reset(); @@ -147,12 +147,12 @@ void CSVLogStorage::ExecuteCast(LoggingTargetTable table, DataChunk &chunk) { } } -void CSVLogStorage::ResetAllBuffers() { - BufferingLogStorage::ResetAllBuffers(); +void CSVLogSink::ResetAllBuffers() { + BufferingLogSink::ResetAllBuffers(); ResetCastChunk(); } -void CSVLogStorage::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { +void CSVLogSink::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { auto config_copy = config; bool changed_writer_settings = false; @@ -177,18 +177,18 @@ void CSVLogStorage::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_ config_copy.erase(it); } - return BufferingLogStorage::UpdateConfigInternal(db, config_copy); + return BufferingLogSink::UpdateConfigInternal(db, config_copy); } -void CSVLogStorage::RegisterWriter(LoggingTargetTable table, unique_ptr writer) { +void CSVLogSink::RegisterWriter(LoggingTargetTable table, unique_ptr writer) { writers[table] = std::move(writer); } -CSVWriter &CSVLogStorage::GetWriter(LoggingTargetTable table) { +CSVWriter &CSVLogSink::GetWriter(LoggingTargetTable table) { return *writers[table]; } -void CSVLogStorage::InitializeCastChunk(LoggingTargetTable table) { +void CSVLogSink::InitializeCastChunk(LoggingTargetTable table) { cast_buffers[table] = make_uniq(); vector types; @@ -197,13 +197,13 @@ void CSVLogStorage::InitializeCastChunk(LoggingTargetTable table) { cast_buffers[table]->Initialize(Allocator::DefaultAllocator(), types, buffer_size); } -void CSVLogStorage::ResetCastChunk() { +void CSVLogSink::ResetCastChunk() { InitializeCastChunk(LoggingTargetTable::LOG_ENTRIES); InitializeCastChunk(LoggingTargetTable::LOG_CONTEXTS); InitializeCastChunk(LoggingTargetTable::ALL_LOGS); } -void CSVLogStorage::SetWriterConfigs(CSVWriter &writer, vector column_names) { +void CSVLogSink::SetWriterConfigs(CSVWriter &writer, vector column_names) { writer.options = *reader_options; writer.writer_options = *writer_options; @@ -212,15 +212,15 @@ void CSVLogStorage::SetWriterConfigs(CSVWriter &writer, vector colum writer.options.force_quote = vector(writer.options.name_list.size(), false); } -CSVReaderOptions &CSVLogStorage::GetCSVReaderOptions() { +CSVReaderOptions &CSVLogSink::GetCSVReaderOptions() { return *reader_options; } -CSVWriterOptions &CSVLogStorage::GetCSVWriterOptions() { +CSVWriterOptions &CSVLogSink::GetCSVWriterOptions() { return *writer_options; } -void CSVLogStorage::FlushChunk(LoggingTargetTable table, DataChunk &chunk) { +void CSVLogSink::FlushChunk(LoggingTargetTable table, DataChunk &chunk) { BeforeFlush(table, chunk); // Execute the cast @@ -237,7 +237,7 @@ void CSVLogStorage::FlushChunk(LoggingTargetTable table, DataChunk &chunk) { cast_buffers[table]->Reset(); } -void BufferingLogStorage::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { +void BufferingLogSink::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { for (const auto &it : config) { if (StringUtil::CIEquals(it.first, "buffer_size")) { buffer_limit = it.second.GetValue(); @@ -248,23 +248,23 @@ void BufferingLogStorage::UpdateConfigInternal(DatabaseInstance &db, case_insens } else if (StringUtil::CIEquals(it.first, "normalize")) { throw InternalException("'normalize' setting should be handled in child class"); } else { - throw InvalidInputException("Unrecognized log storage config option for storage: '%s': '%s'", - GetStorageName(), it.first); + throw InvalidInputException("Unrecognized log sink config option for sink: '%s': '%s'", GetSinkName(), + it.first); } } } -void StdOutLogStorage::StdOutWriteStream::WriteData(const_data_ptr_t buffer, idx_t write_size) { +void StdOutLogSink::StdOutWriteStream::WriteData(const_data_ptr_t buffer, idx_t write_size) { string data(const_char_ptr_cast(buffer), NumericCast(write_size)); Printer::RawPrint(OutputStream::STREAM_STDOUT, data); Printer::Flush(OutputStream::STREAM_STDOUT); } -StdOutLogStorage::StdOutLogStorage(DatabaseInstance &db) : CSVLogStorage(db, false, 1) { - // StdOutLogStorage is denormalized only +StdOutLogSink::StdOutLogSink(DatabaseInstance &db) : CSVLogSink(db, false, 1) { + // StdOutLogSink is denormalized only auto target_table = LoggingTargetTable::ALL_LOGS; - // Set storage specific defaults + // Set sink specific defaults GetCSVWriterOptions().newline_writing_mode = CSVNewLineMode::WRITE_AFTER; GetCSVReaderOptions().dialect_options.state_machine_options.delimiter = CSVOption("\t"); @@ -275,23 +275,23 @@ StdOutLogStorage::StdOutLogStorage(DatabaseInstance &db) : CSVLogStorage(db, fal RegisterWriter(target_table, std::move(writer)); } -StdOutLogStorage::~StdOutLogStorage() { +StdOutLogSink::~StdOutLogSink() { } -FileLogStorage::FileLogStorage(DatabaseInstance &db_p) : CSVLogStorage(db_p, true, STANDARD_VECTOR_SIZE), db(db_p) { +FileLogSink::FileLogSink(DatabaseInstance &db_p) : CSVLogSink(db_p, true, STANDARD_VECTOR_SIZE), db(db_p) { tables[LoggingTargetTable::ALL_LOGS] = TableWriter(); tables[LoggingTargetTable::LOG_CONTEXTS] = TableWriter(); tables[LoggingTargetTable::LOG_ENTRIES] = TableWriter(); - // Set storage specific defaults + // Set sink specific defaults GetCSVWriterOptions().newline_writing_mode = CSVNewLineMode::WRITE_BEFORE; GetCSVReaderOptions().dialect_options.state_machine_options.delimiter = CSVOption(","); } -FileLogStorage::~FileLogStorage() { +FileLogSink::~FileLogSink() { } -void FileLogStorage::InitializeFile(DatabaseInstance &db, LoggingTargetTable table) { +void FileLogSink::InitializeFile(DatabaseInstance &db, LoggingTargetTable table) { auto &table_writer = tables[table]; // reset the files writer, we may be re-initializing it here and otherwise we hold 2 handles to the same file @@ -326,7 +326,7 @@ void FileLogStorage::InitializeFile(DatabaseInstance &db, LoggingTargetTable tab table_writer.initialized = true; } -unique_ptr FileLogStorage::InitializeFileWriter(DatabaseInstance &db, const string &path) { +unique_ptr FileLogSink::InitializeFileWriter(DatabaseInstance &db, const string &path) { auto &fs = db.GetFileSystem(); // Create parent directories if non existent @@ -346,7 +346,7 @@ unique_ptr FileLogStorage::InitializeFileWriter(DatabaseInst return make_uniq(fs, path, flags); } -void FileLogStorage::Truncate() { +void FileLogSink::Truncate() { lock_guard lck(lock); // Reset buffers @@ -367,27 +367,27 @@ void FileLogStorage::Truncate() { } } -void FileLogStorage::BeforeFlush(LoggingTargetTable table, DataChunk &) { +void FileLogSink::BeforeFlush(LoggingTargetTable table, DataChunk &) { // Lazily initialize the files Initialize(table); } -void FileLogStorage::AfterFlush(LoggingTargetTable table, DataChunk &) { +void FileLogSink::AfterFlush(LoggingTargetTable table, DataChunk &) { tables[table].file_writer->Sync(); } -void FileLogStorage::Initialize(LoggingTargetTable table) { +void FileLogSink::Initialize(LoggingTargetTable table) { auto &table_writer = tables[table]; if (!table_writer.initialized) { if (table_writer.path.empty()) { - throw InvalidConfigurationException("Failed to initialize file log storage table, path wasn't set"); + throw InvalidConfigurationException("Failed to initialize file log sink table, path wasn't set"); } InitializeFile(db, table); } } -void FileLogStorage::SetPaths(const string &base_path) { +void FileLogSink::SetPaths(const string &base_path) { for (auto &it : tables) { it.second.path.clear(); } @@ -405,7 +405,7 @@ void FileLogStorage::SetPaths(const string &base_path) { } } -void FileLogStorage::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { +void FileLogSink::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { auto config_copy = config; string new_path; @@ -476,12 +476,12 @@ void FileLogStorage::UpdateConfigInternal(DatabaseInstance &db, case_insensitive config_copy.erase(it); } - CSVLogStorage::UpdateConfigInternal(db, config_copy); + CSVLogSink::UpdateConfigInternal(db, config_copy); } -unique_ptr FileLogStorage::BindReplaceInternal(ClientContext &context, TableFunctionBindInput &input, - const string &path, const string &select_clause, - const string &csv_columns) { +unique_ptr FileLogSink::BindReplaceInternal(ClientContext &context, TableFunctionBindInput &input, + const string &path, const string &select_clause, + const string &csv_columns) { string sub_query_string = StringUtil::Format("%s FROM read_csv_auto(%s, columns={%s})", select_clause, SQLString(path), csv_columns); @@ -492,8 +492,8 @@ unique_ptr FileLogStorage::BindReplaceInternal(ClientContext &context, return duckdb::make_uniq(std::move(select_stmt)); } -unique_ptr FileLogStorage::BindReplace(ClientContext &context, TableFunctionBindInput &input, - LoggingTargetTable table) { +unique_ptr FileLogSink::BindReplace(ClientContext &context, TableFunctionBindInput &input, + LoggingTargetTable table) { lock_guard lck(lock); // We only allow scanning enabled tables @@ -536,12 +536,12 @@ unique_ptr FileLogStorage::BindReplace(ClientContext &context, TableFu return BindReplaceInternal(context, input, path, select, columns); } -BufferingLogStorage::BufferingLogStorage(DatabaseInstance &db_p, idx_t buffer_size, bool normalize) +BufferingLogSink::BufferingLogSink(DatabaseInstance &db_p, idx_t buffer_size, bool normalize) : normalize_contexts(normalize), buffer_limit(buffer_size) { ResetLogBuffers(); } -void BufferingLogStorage::ResetLogBuffers() { +void BufferingLogSink::ResetLogBuffers() { idx_t buffer_size = MaxValue(buffer_limit, 1); // initialize the new buffers before replacing the old ones - initializing allocates, and a buffer that is // replaced but not initialized has no columns, so every later write to it indexes out of bounds @@ -561,42 +561,42 @@ void BufferingLogStorage::ResetLogBuffers() { registered_contexts.clear(); } -void BufferingLogStorage::ResetAllBuffers() { +void BufferingLogSink::ResetAllBuffers() { ResetLogBuffers(); } -InMemoryLogStorageScanState::InMemoryLogStorageScanState(LoggingTargetTable table) : LogStorageScanState(table) { +InMemoryLogSinkScanState::InMemoryLogSinkScanState(LoggingTargetTable table) : LogSinkScanState(table) { } -InMemoryLogStorageScanState::~InMemoryLogStorageScanState() { +InMemoryLogSinkScanState::~InMemoryLogSinkScanState() { } -InMemoryLogStorage::InMemoryLogStorage(DatabaseInstance &db_p) : BufferingLogStorage(db_p, STANDARD_VECTOR_SIZE, true) { - log_storage_buffers[LoggingTargetTable::LOG_ENTRIES] = +InMemoryLogSink::InMemoryLogSink(DatabaseInstance &db_p) : BufferingLogSink(db_p, STANDARD_VECTOR_SIZE, true) { + log_sink_buffers[LoggingTargetTable::LOG_ENTRIES] = make_uniq(Allocator::DefaultAllocator(), GetSchema(LoggingTargetTable::LOG_ENTRIES)); - log_storage_buffers[LoggingTargetTable::LOG_CONTEXTS] = + log_sink_buffers[LoggingTargetTable::LOG_CONTEXTS] = make_uniq(Allocator::DefaultAllocator(), GetSchema(LoggingTargetTable::LOG_CONTEXTS)); } -void InMemoryLogStorage::ResetAllBuffers() { - BufferingLogStorage::ResetAllBuffers(); +void InMemoryLogSink::ResetAllBuffers() { + BufferingLogSink::ResetAllBuffers(); - for (const auto &buffer : log_storage_buffers) { + for (const auto &buffer : log_sink_buffers) { buffer.second->Reset(); } } -ColumnDataCollection &InMemoryLogStorage::GetBuffer(LoggingTargetTable table) const { - auto res = log_storage_buffers.find(table); - if (res == log_storage_buffers.end()) { +ColumnDataCollection &InMemoryLogSink::GetBuffer(LoggingTargetTable table) const { + auto res = log_sink_buffers.find(table); + if (res == log_sink_buffers.end()) { throw InternalException("Failed to find table"); } return *res->second; } -InMemoryLogStorage::~InMemoryLogStorage() { +InMemoryLogSink::~InMemoryLogSink() { } -BufferingLogStorage::~BufferingLogStorage() { +BufferingLogSink::~BufferingLogSink() { } static void WriteLoggingContextsToChunk(DataChunk &chunk, const RegisteredLoggingContext &context, idx_t &col) { @@ -637,8 +637,8 @@ static void WriteLoggingContextsToChunk(DataChunk &chunk, const RegisteredLoggin chunk.SetChildCardinality(size + 1); } -void BufferingLogStorage::WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type, - const string &log_message, const RegisteredLoggingContext &context) { +void BufferingLogSink::WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type, + const string &log_message, const RegisteredLoggingContext &context) { unique_lock lck(lock); auto &log_entries_buffer = @@ -694,35 +694,35 @@ void BufferingLogStorage::WriteLogEntry(timestamp_t timestamp, LogLevel level, c } } -void BufferingLogStorage::WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) { - throw NotImplementedException("BufferingLogStorage::WriteLogEntries(DataChunk &chunk) not implemented"); +void BufferingLogSink::WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) { + throw NotImplementedException("BufferingLogSink::WriteLogEntries(DataChunk &chunk) not implemented"); } -void BufferingLogStorage::FlushAll() { +void BufferingLogSink::FlushAll() { unique_lock lck(lock); if (!only_flush_on_full_buffer) { FlushAllInternal(); } } -void BufferingLogStorage::Flush(LoggingTargetTable table) { +void BufferingLogSink::Flush(LoggingTargetTable table) { unique_lock lck(lock); if (!only_flush_on_full_buffer) { FlushInternal(table); } } -void BufferingLogStorage::Truncate() { +void BufferingLogSink::Truncate() { unique_lock lck(lock); ResetAllBuffers(); } -void InMemoryLogStorage::FlushChunk(LoggingTargetTable table, DataChunk &chunk) { +void InMemoryLogSink::FlushChunk(LoggingTargetTable table, DataChunk &chunk) { D_ASSERT(table == LoggingTargetTable::LOG_ENTRIES || table == LoggingTargetTable::LOG_CONTEXTS); - log_storage_buffers[table]->Append(chunk); + log_sink_buffers[table]->Append(chunk); } -void BufferingLogStorage::FlushAllInternal() { +void BufferingLogSink::FlushAllInternal() { if (normalize_contexts) { FlushInternal(LoggingTargetTable::LOG_ENTRIES); FlushInternal(LoggingTargetTable::LOG_CONTEXTS); @@ -731,7 +731,7 @@ void BufferingLogStorage::FlushAllInternal() { } } -void BufferingLogStorage::FlushInternal(LoggingTargetTable table) { +void BufferingLogSink::FlushInternal(LoggingTargetTable table) { if (!IsEnabledInternal(table)) { throw InvalidConfigurationException("Cannot flush disabled logging target"); } @@ -739,7 +739,7 @@ void BufferingLogStorage::FlushInternal(LoggingTargetTable table) { buffers[table]->Reset(); } -void BufferingLogStorage::WriteLoggingContext(const RegisteredLoggingContext &context) { +void BufferingLogSink::WriteLoggingContext(const RegisteredLoggingContext &context) { registered_contexts.insert(context.context_id); // If we don't normalize the contexts they are written out on every log entry @@ -758,29 +758,29 @@ void BufferingLogStorage::WriteLoggingContext(const RegisteredLoggingContext &co WriteLoggingContextsToChunk(*log_contexts_buffer, context, col); } -bool InMemoryLogStorage::CanScan(LoggingTargetTable table) { +bool InMemoryLogSink::CanScan(LoggingTargetTable table) { unique_lock lck(lock); return IsEnabledInternal(table); } -unique_ptr InMemoryLogStorage::CreateScanState(LoggingTargetTable table) const { - return make_uniq(table); +unique_ptr InMemoryLogSink::CreateScanState(LoggingTargetTable table) const { + return make_uniq(table); } -bool InMemoryLogStorage::Scan(LogStorageScanState &state, DataChunk &result) const { +bool InMemoryLogSink::Scan(LogSinkScanState &state, DataChunk &result) const { unique_lock lck(lock); - auto &in_mem_scan_state = state.Cast(); + auto &in_mem_scan_state = state.Cast(); return GetBuffer(in_mem_scan_state.table).Scan(in_mem_scan_state.scan_state, result); } -optional_idx InMemoryLogStorage::GetScanRowCount(LoggingTargetTable table) const { +optional_idx InMemoryLogSink::GetScanRowCount(LoggingTargetTable table) const { unique_lock lck(lock); return GetBuffer(table).Count(); } -void InMemoryLogStorage::InitializeScan(LogStorageScanState &state) const { +void InMemoryLogSink::InitializeScan(LogSinkScanState &state) const { unique_lock lck(lock); - auto &in_mem_scan_state = state.Cast(); + auto &in_mem_scan_state = state.Cast(); GetBuffer(in_mem_scan_state.table) .InitializeScan(in_mem_scan_state.scan_state, ColumnDataScanProperties::DISALLOW_ZERO_COPY); } diff --git a/src/duckdb/src/logging/logger.cpp b/src/duckdb/src/logging/logger.cpp index 3b81d20db..19959159a 100644 --- a/src/duckdb/src/logging/logger.cpp +++ b/src/duckdb/src/logging/logger.cpp @@ -1,4 +1,5 @@ -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/main/context.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/logging/log_manager.hpp" #include "duckdb/main/client_context.hpp" @@ -38,6 +39,10 @@ Logger &Logger::Get(const ClientContext &client_context) { return client_context.GetLogger(); } +Logger &Logger::Get(const Context &context) { + return context.GetLogger(); +} + Logger &Logger::Get(const FileOpener &opener) { return opener.GetLogger(); } diff --git a/src/duckdb/src/logging/logging.cpp b/src/duckdb/src/logging/logging.cpp index 4585c8d7b..84d89fef1 100644 --- a/src/duckdb/src/logging/logging.cpp +++ b/src/duckdb/src/logging/logging.cpp @@ -1,4 +1,4 @@ -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" #include "duckdb/logging/logger.hpp" namespace duckdb { diff --git a/src/duckdb/src/main/attached_database.cpp b/src/duckdb/src/main/attached_database.cpp index 1e477ed60..833040a38 100644 --- a/src/duckdb/src/main/attached_database.cpp +++ b/src/duckdb/src/main/attached_database.cpp @@ -7,6 +7,7 @@ #include "duckdb/common/file_system.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/database_manager.hpp" +#include "duckdb/main/error_manager.hpp" #include "duckdb/main/external_resources_manager.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/parser/parsed_data/attach_info.hpp" @@ -126,8 +127,8 @@ AttachedDatabase::AttachedDatabase(DatabaseInstance &db, AttachedDatabaseType ty D_ASSERT(type == AttachedDatabaseType::TEMP_DATABASE || type == AttachedDatabaseType::SYSTEM_DATABASE); if (type == AttachedDatabaseType::TEMP_DATABASE) { unordered_map options; - auto services = db.Services(); - AttachOptions attach_options(*services, options, AccessMode::READ_WRITE); + auto &services = db.GetContext(); + AttachOptions attach_options(services, options, AccessMode::READ_WRITE); options["storage_version"] = "latest"; storage = make_uniq(*this, string(IN_MEMORY_PATH), attach_options); } @@ -273,7 +274,7 @@ void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr & close_action = DatabaseCloseAction::CHECKPOINT; } else if (checkpoint_on_detach == CheckpointOnDetach::DISABLED) { close_action = DatabaseCloseAction::SKIP_CHECKPOINT; - } else if (!DBConfig::GetConfig(context).options.checkpoint_on_shutdown) { + } else if (!Settings::Get(context)) { close_action = DatabaseCloseAction::SKIP_CHECKPOINT; } @@ -286,6 +287,10 @@ void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr & } attached_db->is_closing = true; } + // 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. + auto synchronizing_reference = attached_db; + synchronizing_reference.reset(); attached_db->Close(close_action); attached_db.reset(); } @@ -356,13 +361,43 @@ bool AttachedDatabase::IsInitialDatabase() const { return is_initial_database; } -void AttachedDatabase::Invalidate(const string &reason) { +bool AttachedDatabase::SupportsScopedInvalidation() const { + return !IsSystem() && !IsTemporary() && !IsInitialDatabase(); +} + +void AttachedDatabase::Invalidate(const string &cause, const string &error) { + if (!SupportsScopedInvalidation()) { + ValidChecker::Invalidate(db, + StringUtil::Format("Database %s has been invalidated because %s. Original error: %s", + GetName(), cause, error)); + return; + } string recovery = HasStorageManager() && GetStorageManager().InMemory() ? "It is an in-memory database, so its data cannot be recovered." : "Detach and reattach it before using it again."; - ValidChecker::Invalidate(*this, StringUtil::Format("Database %s has been invalidated because checkpointing " - "failed. %s Original error: %s", - GetName(), recovery, reason)); + validity.InvalidateIfValid(StringUtil::Format("Database %s has been invalidated because %s. %s Original error: %s", + GetName(), cause, recovery, error)); +} + +ErrorData AttachedDatabase::ScopeFatalError(ErrorData error) { + if (!error.HasError() || !Exception::InvalidatesDatabase(error.Type()) || !SupportsScopedInvalidation()) { + return error; + } + Invalidate("of a fatal error", error.RawMessage()); + error.SetExtraInfo(Exception::INVALIDATED_DATABASE_KEY, GetName().GetIdentifierName()); + return error; +} + +ErrorData AttachedDatabase::InvalidationError(const string &operation) { + if (ValidChecker::IsInvalidated(*this)) { + return ErrorData(IOException("Cannot %s: %s", operation, ValidChecker::InvalidatedMessage(*this))); + } + if (ValidChecker::IsInvalidated(db)) { + auto message = ErrorManager::Get(db).FormatException(ErrorType::INVALIDATED_DATABASE, + ValidChecker::InvalidatedMessage(db)); + return ErrorData(IOException("Cannot %s: %s", operation, message)); + } + return ErrorData(); } void AttachedDatabase::SetInitialDatabase() { @@ -414,7 +449,7 @@ void AttachedDatabase::Close(const DatabaseCloseAction action) { should_checkpoint = true; } else if (action == DatabaseCloseAction::TRY_CHECKPOINT) { auto &config = DBConfig::GetConfig(db); - should_checkpoint = config.options.checkpoint_on_shutdown; + should_checkpoint = Settings::Get(config); } if (should_checkpoint) { CheckpointOptions options; diff --git a/src/duckdb/src/main/capi/v1/logging-c.cpp b/src/duckdb/src/main/capi/v1/logging-c.cpp index 841e53cf9..a484aefb4 100644 --- a/src/duckdb/src/main/capi/v1/logging-c.cpp +++ b/src/duckdb/src/main/capi/v1/logging-c.cpp @@ -1,18 +1,18 @@ #include "duckdb/main/capi/capi_internal.hpp" #include "duckdb/logging/log_manager.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" namespace duckdb { -class CallbackLogStorage : public LogStorage { +class CallbackLogSink : public LogSink { public: - CallbackLogStorage(const string &name, duckdb_logger_write_log_entry_t write_log_entry_fun, void *extra_data, - duckdb_delete_callback_t delete_callback) + CallbackLogSink(const string &name, duckdb_logger_write_log_entry_t write_log_entry_fun, void *extra_data, + duckdb_delete_callback_t delete_callback) : name(name), write_log_entry_fun(write_log_entry_fun), extra_data(extra_data), delete_callback(delete_callback) { } - ~CallbackLogStorage() override { + ~CallbackLogSink() override { if (!extra_data || !delete_callback) { return; } @@ -38,7 +38,7 @@ class CallbackLogStorage : public LogStorage { return true; } - const string GetStorageName() override { + const string GetSinkName() override { return name; } @@ -117,12 +117,12 @@ duckdb_state duckdb_register_log_storage(duckdb_database database, duckdb_log_st } const auto &db = *db_wrapper->database; - auto shared_storage_ptr = duckdb::make_shared_ptr( + auto shared_storage_ptr = duckdb::make_shared_ptr( log_storage_wrapper->name, log_storage_wrapper->write_log_entry, log_storage_wrapper->extra_data, log_storage_wrapper->delete_callback); - duckdb::shared_ptr storage_ptr = shared_storage_ptr; + duckdb::shared_ptr storage_ptr = shared_storage_ptr; - const auto success = db.instance->GetLogManager().RegisterLogStorage(log_storage_wrapper->name, storage_ptr); + const auto success = db.instance->GetLogManager().RegisterLogSink(log_storage_wrapper->name, storage_ptr); if (!success) { return DuckDBError; } 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 302d5e794..e66626616 100644 --- a/src/duckdb/src/main/capi/v1/scalar_function-c.cpp +++ b/src/duckdb/src/main/capi/v1/scalar_function-c.cpp @@ -184,7 +184,7 @@ unique_ptr CScalarFunctionInit(ExpressionState &state, const auto result = make_uniq(); if (info.init) { - auto &context = state.GetContext(); + auto &context = state.GetClientContext(); auto &c_bind_data = bind_data->Cast(); CScalarFunctionInternalInitInfo init_info(context, c_bind_data, *result); info.init(ToCScalarFunctionInitInfo(init_info)); 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 6f158a304..3780432ff 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 @@ -202,7 +202,7 @@ static auto CV2ScalarInit(ExpressionState &state, const BoundFunctionExpression CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(state.GetContext()); + CV2CallbackContext callback_context(state.GetClientContext()); info.init_cb(Convert(&args), Convert(&callback_context), &err_ptr); unique_ptr result = nullptr; @@ -246,7 +246,7 @@ static auto CV2ScalarExec(DataChunk &input, ExpressionState &state, Vector &resu CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(state.GetContext()); + CV2CallbackContext callback_context(state.GetClientContext()); info.exec_cb(Convert(&args), Convert(&callback_context), &err_ptr); if (err.HasError()) { 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 29fe5e07d..5053d914c 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 @@ -2,14 +2,23 @@ #include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/table_function_catalog_entry.hpp" +#include "duckdb/common/multi_file/base_file_reader.hpp" #include "duckdb/common/multi_file/multi_file_data.hpp" #include "duckdb/common/multi_file/table_function_multi_file.hpp" +#include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/partition_info.hpp" #include "duckdb/function/partition_stats.hpp" +#include "duckdb/main/profiler/metrics.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/parser/parsed_data/create_table_function_info.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/table_filter_set.hpp" +#include "duckdb/planner/table_filter_state.hpp" #include "duckdb/storage/statistics/node_statistics.hpp" +#include "duckdb/storage/table/column_segment.hpp" namespace duckdb::capiv2 { @@ -72,6 +81,22 @@ class CV2TableLocalState final : public LocalTableFunctionState { //! Written into by the exec callback when the scan requests no columns, as the function produces its rows through //! its first column unique_ptr row_chunk; + //! The filters of the query the engine applies to what the function produces, as the position of the scan column + //! each applies to and its state. Only for a function that reads the filters. + vector>> filters; + //! A column the multi-file scan wants converted before its filters apply: the position of the scan column it + //! produces and the expression doing the conversion, on the columns that follow it in what the function produced + struct ConvertedColumn { + idx_t position; + unique_ptr expression; + unique_ptr executor; + unique_ptr input; + }; + vector converted_columns; + //! For each scan column, whether it is one of the converted columns + vector converted_position; + //! What the function produces, in the types of its file, when some columns are converted afterwards + unique_ptr file_chunk; // Requested partition columns as declared columns, fixed for the lifetime of the local state's pipeline. const vector &PartitionColumns(const OperatorPartitionInfo &partition_info, @@ -211,6 +236,52 @@ static auto Convert(CV2TableProgressInfo *info) -> duckdb_v2_table_function_prog return reinterpret_cast(info); } +class CV2TableMetricsInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + + //! The metrics the callback reported, by name, applied to the scan's metrics afterwards + vector> out_metrics; +}; + +//! The operator metrics a table function scan can report, by the name the profiler uses for them +static auto CV2TableApplyMetric(OperatorMetrics &metrics, const string &name, uint64_t value) -> bool { + if (name == MetricOperatorRowsScanned::Name) { + metrics.rows_scanned = value; + } else if (name == MetricOperatorRowGroupsScanned::Name) { + metrics.row_groups_scanned = value; + } else if (name == MetricOperatorTotalRowGroupsToScan::Name) { + metrics.total_row_groups_to_scan = value; + } else if (name == MetricOperatorBytesScanned::Name) { + metrics.bytes_scanned = value; + metrics.bytes_scanned_reported = true; + } else { + return false; + } + return true; +} + +static void CV2TableAddMetric(CV2TableMetricsInfo &info, const char *name, idx_t name_length, uint64_t value) { + string metric_name(name, name_length); + OperatorMetrics probe; + if (!CV2TableApplyMetric(probe, metric_name, value)) { + throw InvalidInputException("\"%s\" is not a metric a table function can report, expected one of " + "\"%s\", \"%s\", \"%s\" or \"%s\"", + metric_name, MetricOperatorRowsScanned::Name, MetricOperatorRowGroupsScanned::Name, + MetricOperatorTotalRowGroupsToScan::Name, MetricOperatorBytesScanned::Name); + } + info.out_metrics.emplace_back(std::move(metric_name), value); +} + +static auto Convert(duckdb_v2_table_function_metrics_info_handle info) -> CV2TableMetricsInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableMetricsInfo *info) -> duckdb_v2_table_function_metrics_info_handle { + return reinterpret_cast(info); +} + class CV2TableClaimBatchInfo { public: void *in_user_data = nullptr; @@ -234,8 +305,8 @@ class CV2TableFilterPushdownInfo { void *in_bind_data = nullptr; // The predicates the optimizer offers, borrowed from the engine for the duration of the callback. const vector> *in_filters = nullptr; - // What the column references inside the predicates index: the scan's column list at optimization time. - const vector *in_column_ids = nullptr; + // What the column references inside the predicates index: the scan's columns, as the function sees them. + vector in_column_ids; vector out_handled; }; @@ -339,6 +410,19 @@ static auto CV2ConvertOrderPreservation(DUCKDB_V2_ORDER_PRESERVATION value) -> O return static_cast(value); } +//! Virtual columns are told apart from declared ones in the column lists of the scan by this plus their value in the +//! public enum +static constexpr column_t CV2_VIRTUAL_COLUMN_START = UINT64_C(9223372036854775808); + +//! The index the scan's column lists hold for a virtual column of the engine, which is invalid if there is no such +//! virtual column +static auto CV2VirtualColumnIndex(column_t engine_id) -> column_t { + if (engine_id == MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER) { + return CV2_VIRTUAL_COLUMN_START + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER; + } + throw InternalException("Unsupported virtual column %llu in a table function scan", engine_id); +} + class CV2TableFunctionInfo : public TableFunctionInfo { public: duckdb_v2_table_function_bind_callback_fn bind_cb = nullptr; @@ -352,8 +436,15 @@ class CV2TableFunctionInfo : public TableFunctionInfo { duckdb_v2_table_function_stats_callback_fn stats_cb = nullptr; duckdb_v2_table_function_claim_batch_callback_fn claim_batch_cb = nullptr; duckdb_v2_table_function_get_bind_info_callback_fn get_bind_info_cb = nullptr; + duckdb_v2_table_function_metrics_callback_fn metrics_cb = nullptr; shared_ptr user_data = nullptr; bool projection_pushdown = false; + //! Whether the function sees the filters of the scan: it has a filter pushdown callback and projection pushdown + bool ReadsFilters() const { + return filter_pushdown_cb && projection_pushdown; + } + //! Whether the function can produce the file_row_number virtual column + bool file_row_number = false; Identifier name; }; @@ -446,6 +537,19 @@ static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, return std::move(result); } +//! The index the function sees for a column of the scan. A virtual column of a function wrapped in a multi-file +//! function has an index of its own past the declared columns, and the wrapper tells which virtual column that is. +static auto CV2ScanColumnIndex(column_t column, optional_ptr> virtual_columns) + -> column_t { + if (virtual_columns) { + auto entry = virtual_columns->find(column); + if (entry != virtual_columns->end()) { + return CV2VirtualColumnIndex(entry->second); + } + } + return IsVirtualColumn(column) ? CV2VirtualColumnIndex(column) : column; +} + //! The declared column behind each vector of the output chunk. With projection pushdown the engine sizes the chunk //! to the columns it asked for; without it the chunk always holds every declared column, whatever the engine asked. static auto CV2TableScanColumns(const CV2TableFunctionData &bind_data, const TableFunctionInitInput &input) @@ -455,7 +559,13 @@ static auto CV2TableScanColumns(const CV2TableFunctionData &bind_data, const Tab // the scan only produces rows (e.g. for count(*)) - the function produces them through its first column return {0}; } - return input.column_ids; + const auto &virtual_columns = TableFunctionFileInitInput::Get(input).virtual_columns; + vector columns; + columns.reserve(input.column_ids.size()); + for (auto column : input.column_ids) { + columns.push_back(CV2ScanColumnIndex(column, virtual_columns)); + } + return columns; } vector columns; for (idx_t i = 0; i < bind_data.column_types.size(); i++) { @@ -464,6 +574,94 @@ static auto CV2TableScanColumns(const CV2TableFunctionData &bind_data, const Tab return columns; } +//! The filters of the query that apply to a single column of the scan, as the position of the column among the scan's +//! columns and the predicate on it. A filter the engine applies speculatively is handed out as the predicate it +//! applies. +static auto CV2TableFilters(const TableFunctionInitInput &input) -> vector> { + //! The predicate behind a filter that is applied speculatively, which wraps it + auto unwrap = [](Expression &expression) -> Expression & { + reference current(expression); + while (current.get().GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + auto &function = current.get().Cast(); + if (!function.BindInfo()) { + break; + } + auto &name = function.Function().GetName(); + if (name == OptionalFilterScalarFun::NAME) { + current = *function.BindInfo()->Cast().child_filter_expr; + } else if (name == SelectivityOptionalFilterScalarFun::NAME) { + current = *function.BindInfo()->Cast().child_filter_expr; + } else { + break; + } + } + return current.get(); + }; + vector> result; + if (!input.filters) { + return result; + } + for (auto &entry : *input.filters) { + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "CV2TableFilters"); + result.emplace_back(entry.GetIndex().GetIndex(), &unwrap(*filter.expr)); + } + return result; +} + +//! Offers the filters the scan applies to the filter pushdown callback once more, for the scan that is about to start. +//! The callback only sees the predicates at optimization time, which a function wrapped in a multi-file function does +//! not: the optimizer asks the wrapper. The engine applies the filters to what the function produces, so accepting a +//! predicate has no effect here. +static auto CV2TableOfferFilters(ClientContext &context, const CV2TableFunctionData &bind_data, + const TableFunctionInitInput &input) -> void { + const auto &info = *bind_data.info; + const auto &file_input = TableFunctionFileInitInput::Get(input); + auto filters = CV2TableFilters(input); + if (file_input.expression_map) { + // the predicate on a converted column is written against the converted values, not those of the file + vector> on_file_columns; + for (auto &entry : filters) { + if (file_input.expression_map->find(ProjectionIndex(entry.first)) == file_input.expression_map->end()) { + on_file_columns.push_back(entry); + } + } + filters = std::move(on_file_columns); + } + if (filters.empty()) { + return; + } + // A table filter refers to the one column it applies to by a physical reference; the callback is offered column + // references, like at optimization time, which it resolves through the column list + vector> predicates; + for (auto &entry : filters) { + auto predicate = entry.second->Copy(); + ExpressionIterator::EnumerateExpression(predicate, [&](unique_ptr &child) { + if (child->GetExpressionClass() == ExpressionClass::BOUND_REF) { + child = make_uniq(child->GetAlias(), child->GetReturnType(), + ColumnBinding(TableIndex(0), ProjectionIndex(entry.first))); + } + }); + predicates.push_back(std::move(predicate)); + } + + CV2TableFilterPushdownInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + args.in_filters = &predicates; + for (auto column : input.column_ids) { + args.in_column_ids.push_back(CV2ScanColumnIndex(column, file_input.virtual_columns)); + } + args.out_handled.resize(predicates.size(), false); + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.filter_pushdown_cb(Convert(&args), Convert(&callback_context), &err_ptr); + if (err.HasError()) { + err.ThrowAsException(); + } +} + static auto CV2TableInitGlobal(ClientContext &context, TableFunctionInitInput &input) -> unique_ptr { const auto &bind_data = input.bind_data->Cast(); @@ -472,6 +670,9 @@ static auto CV2TableInitGlobal(ClientContext &context, TableFunctionInitInput &i // Always produced, even without a callback: it carries the thread count and column list the scan runs with. auto result = make_uniq(); result->scan_columns = CV2TableScanColumns(bind_data, input); + if (info.ReadsFilters()) { + CV2TableOfferFilters(context, bind_data, input); + } if (!info.init_global_cb) { return std::move(result); } @@ -500,6 +701,63 @@ static auto CV2TableInitGlobal(ClientContext &context, TableFunctionInitInput &i return std::move(result); } +//! Prepares the conversions the multi-file scan asks for (see TableFunctionFileInitInput::expression_map). The function +//! produces the values of its file, and the conversion turns them into the values the filters are written against. +static auto CV2TableInitConvertedColumns(ClientContext &context, const CV2TableFunctionData &bind_data, + const TableFunctionInitInput &input, const vector &scan_columns, + CV2TableLocalState &local_state) -> void { + const auto &expression_map = TableFunctionFileInitInput::Get(input).expression_map; + if (!expression_map || expression_map->empty()) { + return; + } + vector file_types; + for (auto column : scan_columns) { + file_types.push_back(IsVirtualColumn(column) ? LogicalType::BIGINT : bind_data.column_types[column]); + } + for (auto &entry : *expression_map) { + const auto position = entry.first.GetIndex(); + const auto input_count = entry.second.column_indexes.size(); + if (position + input_count > file_types.size()) { + throw InternalException("Converted column %llu of a table function scan is out of range", position); + } + CV2TableLocalState::ConvertedColumn converted; + converted.position = position; + converted.expression = entry.second.expression->Copy(); + converted.executor = make_uniq(context, *converted.expression); + vector input_types(file_types.begin() + NumericCast(position), + file_types.begin() + NumericCast(position + input_count)); + converted.input = make_uniq(); + converted.input->InitializeEmpty(input_types); + local_state.converted_columns.push_back(std::move(converted)); + } + local_state.converted_position.assign(file_types.size(), false); + for (auto &converted : local_state.converted_columns) { + local_state.converted_position[converted.position] = true; + } + local_state.file_chunk = make_uniq(); + local_state.file_chunk->Initialize(context, file_types); +} + +//! Produces the converted columns from what the function produced in the types of its file +static auto CV2TableConvertColumns(CV2TableLocalState &local_state, DataChunk &output) -> void { + auto &file_chunk = *local_state.file_chunk; + D_ASSERT(local_state.converted_position.size() == output.ColumnCount()); + for (idx_t i = 0; i < output.ColumnCount(); i++) { + if (!local_state.converted_position[i]) { + output.data[i].Reference(file_chunk.data[i]); + } + } + for (auto &converted : local_state.converted_columns) { + auto &converted_input = *converted.input; + for (idx_t i = 0; i < converted_input.ColumnCount(); i++) { + converted_input.data[i].Reference(file_chunk.data[converted.position + i]); + } + converted_input.SetChildCardinality(file_chunk.size()); + converted.executor->ExecuteExpression(converted_input, output.data[converted.position]); + } + output.SetChildCardinality(file_chunk.size()); +} + static auto CV2TableInitLocal(ExecutionContext &context, TableFunctionInitInput &input, GlobalTableFunctionState *global_state) -> unique_ptr { const auto &bind_data = input.bind_data->Cast(); @@ -507,12 +765,21 @@ static auto CV2TableInitLocal(ExecutionContext &context, TableFunctionInitInput // Always produced, even without a callback: get_partition_data keeps its per-thread guard state here. auto result = make_uniq(); + if (info.ReadsFilters() && input.filters) { + // The function only reads the filters, so it is left to the engine to apply them to what it produces + for (auto &entry : *input.filters) { + result->filters.emplace_back(entry.GetIndex().GetIndex(), + TableFilterState::Initialize(context.client, entry.Filter())); + } + } + auto scan_columns = CV2TableScanColumns(bind_data, input); + if (info.ReadsFilters()) { + CV2TableInitConvertedColumns(context.client, bind_data, input, scan_columns, *result); + } if (!info.init_local_cb) { return std::move(result); } - auto scan_columns = CV2TableScanColumns(bind_data, input); - CV2TableInitLocalInfo args = {}; args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; @@ -598,7 +865,47 @@ static auto CV2TableExec(ClientContext &context, TableFunctionInput &input, Data } } +static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; + +//! Runs the exec callback and, for a function that reads the filters of the query, applies them to what it produced: +//! the function is free to produce rows that do not pass them static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { + auto &local_state = input.local_state->Cast(); + while (true) { + if (local_state.file_chunk) { + local_state.file_chunk->Reset(); + CV2TableExecBatchOnce(context, input, *local_state.file_chunk); + CV2TableConvertColumns(local_state, output); + } else { + CV2TableExecBatchOnce(context, input, output); + } + if (local_state.filters.empty() || output.size() == 0) { + return; + } + const auto count = output.size(); + idx_t remaining = count; + SelectionVector selection; + selection.Initialize(nullptr); + for (auto &filter : local_state.filters) { + if (remaining == 0) { + break; + } + ColumnSegment::FilterSelection(selection, output.data[filter.first], *filter.second, count, remaining); + } + if (remaining == count) { + return; + } + if (remaining > 0) { + output.Slice(selection, remaining); + return; + } + // Nothing of this batch passed, but an empty chunk means that the batch is exhausted + output.Reset(); + context.InterruptCheck(); + } +} + +static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { const auto &bind_data = input.bind_data->Cast(); const auto &info = *bind_data.info; @@ -717,6 +1024,43 @@ static auto CV2TableProgress(ClientContext &context, const FunctionData *bind_da return MinValue(MaxValue(args.out_progress, 0.0), 1.0) * 100.0; } +static auto CV2TableGetMetrics(TableFunctionGetMetricsInput &input) -> void { + if (!input.bind_data) { + return; + } + const auto &data = input.bind_data->Cast(); + const auto &info = *data.info; + + CV2TableMetricsInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; + if (input.global_state) { + // The callback can run while the scan does, so the state it reads is the shared one, unsynchronized. + args.in_global_state = input.global_state->Cast().handle.GetData(); + } + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(input.context); + info.metrics_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + + for (auto &metric : args.out_metrics) { + CV2TableApplyMetric(input.operator_metrics, metric.first, metric.second); + } +} + +//! Registered only for functions that declared the file_row_number virtual column, which is all there is to know +static auto CV2TableGetFileRowNumberColumn(ClientContext &, optional_ptr) -> virtual_column_map_t { + virtual_column_map_t result; + result.insert(make_pair(MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER, + TableColumn("file_row_number", LogicalType::BIGINT))); + return result; +} + //! The optimizer hands over the predicates it would otherwise evaluate above the scan; whatever the callback accepts //! is removed from the list, and the engine keeps applying the rest itself. static auto CV2TableFilterPushdown(ClientContext &context, LogicalGet &get, FunctionData *bind_data_p, @@ -731,7 +1075,9 @@ static auto CV2TableFilterPushdown(ClientContext &context, LogicalGet &get, Func args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; args.in_filters = &filters; - args.in_column_ids = &get.GetColumnIds(); + for (auto &column : get.GetColumnIds()) { + args.in_column_ids.push_back(CV2ScanColumnIndex(column.GetPrimaryIndex(), nullptr)); + } args.out_handled.resize(filters.size(), false); CV2ErrorInfo err = {}; @@ -855,6 +1201,12 @@ class CV2TableFunction { throw InvalidInputException("A table function signature cannot set a return type."); } + // Both are told apart from the declared columns by their place among the columns the scan was asked for + if (info.file_row_number && !info.projection_pushdown) { + throw InvalidInputException( + "A table function that produces a virtual column requires projection pushdown."); + } + signature.Verify(); // A table function holds a signature of its own, so the declared one is handed over as-is @@ -881,6 +1233,16 @@ class CV2TableFunction { function.statistics_extended = CV2TableStats; } function.projection_pushdown = info.projection_pushdown; + if (info.ReadsFilters()) { + // The engine applies the filters to what the function produces, so they only need to reach the scan + function.filter_pushdown = true; + } + if (info.file_row_number) { + function.get_virtual_columns = CV2TableGetFileRowNumberColumn; + } + if (info.metrics_cb) { + function.get_metrics = CV2TableGetMetrics; + } if (info.get_bind_info_cb) { function.get_bind_info = CV2TableGetBindInfo; } @@ -1089,6 +1451,29 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(duckdb_v2_table return WithErrorHandler(err, [&]() { Convert(function)->info.projection_pushdown = enable; }); } +DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { + switch (column) { + case DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER: + Convert(function)->info.file_row_number = true; + break; + default: + throw duckdb::InvalidInputException("Invalid value in duckdb_v2_table_function_add_virtual_column"); + } + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_table_function_set_metrics_callback(duckdb_v2_table_function_handle function, + duckdb_v2_table_function_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.metrics_cb = callback; }); +} + DUCKDB_V2_ERROR duckdb_v2_table_function_set_filter_pushdown_callback(duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, @@ -1357,6 +1742,35 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_progress_set_progress(duckdb_v2_table_f return WithErrorHandler(err, [&]() { Convert(info)->out_progress = progress; }); } +DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_user_data(duckdb_v2_table_function_metrics_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_bind_data(duckdb_v2_table_function_metrics_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_global_state(duckdb_v2_table_function_metrics_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_set(duckdb_v2_table_function_metrics_info_handle info, + const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(name); + return WithErrorHandler(err, [&]() { CV2TableAddMetric(*Convert(info), name, name_length, value); }); +} + DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_user_data(duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err) { @@ -1417,7 +1831,7 @@ duckdb_v2_table_function_filter_pushdown_get_column_count(duckdb_v2_table_functi idx_t *count, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(count); - return WithErrorHandler(err, [&]() { *count = Convert(info)->in_column_ids->size(); }); + return WithErrorHandler(err, [&]() { *count = Convert(info)->in_column_ids.size(); }); } DUCKDB_V2_ERROR @@ -1427,13 +1841,12 @@ duckdb_v2_table_function_filter_pushdown_get_column_index(duckdb_v2_table_functi DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(column_index); return WithErrorHandler(err, [&]() { - const auto &columns = *Convert(info)->in_column_ids; + const auto &columns = Convert(info)->in_column_ids; if (index >= columns.size()) { throw duckdb::InvalidInputException( "Index out of bounds in duckdb_v2_table_function_filter_pushdown_get_column_index"); } - // A function registered here declares no virtual columns, so every entry is a declared column. - *column_index = columns[index].GetPrimaryIndex(); + *column_index = columns[index]; }); } 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 d2b8c7cf9..402d5905e 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp @@ -56,8 +56,8 @@ void CV2Instance::Attach(const string &path, const Identifier &name, if (attach_options) { info.options = attach_options->options; } - auto services = instance.Services(); - AttachOptions options(*services, info.options, instance.config.options.access_mode); + auto &services = instance.GetContext(); + AttachOptions options(services, info.options, instance.config.options.access_mode); options.original_path = path; if (options.db_type.empty()) { DBPathAndType::ExtractExtensionPrefix(info.path, options.db_type); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_log_sink.cpp b/src/duckdb/src/main/capi/v2/capi_v2_log_sink.cpp index 65ff63422..3257d9be1 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_log_sink.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_log_sink.cpp @@ -1,7 +1,7 @@ #include "duckdb/main/capi_v2/capi_v2_internal.hpp" #include "duckdb/logging/log_manager.hpp" -#include "duckdb/logging/log_storage.hpp" +#include "duckdb/logging/log_sink.hpp" namespace duckdb::capiv2 { @@ -30,14 +30,14 @@ static auto Convert(CV2LogSinkFlushInfo *info) -> duckdb_v2_log_sink_flush_info_ //! A log sink that hands every entry to the caller's write callback. Errors the callbacks report are dropped: //! logging happens inside arbitrary operations, which a sink must not fail. -class CV2CallbackLogSink final : public LogStorage { +class CV2CallbackLogSink final : public LogSink { public: CV2CallbackLogSink(string name, duckdb_v2_log_sink_write_callback_fn write_cb, duckdb_v2_log_sink_flush_callback_fn flush_cb, shared_ptr user_data) : name(std::move(name)), write_cb(write_cb), flush_cb(flush_cb), user_data(std::move(user_data)) { } - const string GetStorageName() override { + const string GetSinkName() override { return name; } @@ -103,8 +103,8 @@ class CV2LogSink { sink_name == LogConfig::FILE_STORAGE_NAME) { throw InvalidInputException("\"%s\" is the name of a log sink DuckDB provides.", name); } - shared_ptr sink = make_shared_ptr(sink_name, write_cb, flush_cb, user_data); - if (!target.GetLogManager().RegisterLogStorage(sink_name, sink)) { + shared_ptr sink = make_shared_ptr(sink_name, write_cb, flush_cb, user_data); + if (!target.GetLogManager().RegisterLogSink(sink_name, sink)) { throw InvalidInputException("A log sink named \"%s\" is already registered.", name); } } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_tokenizer.cpp b/src/duckdb/src/main/capi/v2/capi_v2_tokenizer.cpp index f3778ab33..9b737d5ea 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_tokenizer.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_tokenizer.cpp @@ -79,10 +79,10 @@ DUCKDB_V2_ERROR duckdb_v2_tokenize_sql(duckdb_v2_connection_handle conn, const c return WithErrorHandler(err, [&]() { auto *connection = Convert(conn); duckdb::string input(Convert(sql, sql_length)); - duckdb::vector raw_tokens; - CleanExitTokenizerBehavior behavior(input, raw_tokens); + CleanExitTokenizerBehavior behavior(input); auto grammar = duckdb::CompiledGrammar::Get(*connection->context); const bool clean_exit = grammar->GetTokenizer().TokenizeInput(behavior); + auto &raw_tokens = behavior.tokens; auto wrapper = duckdb::make_uniq(); wrapper->input_length = input.size(); diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 57fa6265d..902dfbb01 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -163,7 +163,11 @@ ClientContext::~ClientContext() { } // 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 - Destroy(); + try { + Destroy(); + } catch (...) { + // a destructor cannot throw, and locking the context allocates + } } unique_ptr ClientContext::LockContext() { @@ -244,7 +248,7 @@ void ClientContext::ApplyInvalidationPolicy(const ErrorData &error) { invalidates_transaction = false; } else if (Exception::InvalidatesDatabase(error.Type())) { auto &db_instance = DatabaseInstance::GetDatabase(*this); - ValidChecker::Invalidate(db_instance, error.RawMessage()); + ValidChecker::Invalidate(db_instance, error); } // a statement issued while CONNECT-ed that did not run locally is not part of the local transaction const bool outside_local_transaction = active_query ? active_query->outside_local_transaction : is_connected; @@ -331,8 +335,20 @@ shared_ptr ClientContext::CreatePreparedStatementInternal { auto planner_timer = profiler.StartTimer(); + logical_planner.reuse_prepared_plans = true; logical_planner.CreatePlan(std::move(statement)); - D_ASSERT(logical_planner.plan || !logical_planner.properties.bound_all_parameters); + D_ASSERT(logical_planner.plan || logical_planner.reused_statement || + !logical_planner.properties.bound_all_parameters); + } + if (logical_planner.reused_statement) { + // re-use the physical plan of the prepared statement + result->properties = logical_planner.properties; + result->names = logical_planner.names; + result->types = logical_planner.types; + result->physical_plan = make_uniq(Allocator::Get(*this)); + result->physical_plan->SetRoot(logical_planner.reused_statement->physical_plan->Root()); + result->reused_statement = std::move(logical_planner.reused_statement); + return result; } if (logical_planner.properties.bound_all_parameters) { @@ -632,7 +648,7 @@ StatementSignature ClientContext::BindStatement(unique_ptr stateme } auto bound = std::move(expanded.statements[0]); auto named_param_map = bound->named_param_map; - Planner planner(*this); + Planner planner(*this, PlanningMode::BIND_ONLY); planner.CreatePlan(std::move(bound)); signature.names = planner.names; signature.types = planner.types; @@ -824,9 +840,9 @@ unique_ptr ClientContext::SubmitStatement(ClientContextLock &lock, } catch (std::exception &ex) { ErrorData error(ex); if (Exception::InvalidatesDatabase(error.Type())) { - // fatal exceptions invalidate the entire database + // fatal exceptions invalidate the database instance, unless scoped to an attached database auto &db_instance = DatabaseInstance::GetDatabase(*this); - ValidChecker::Invalidate(db_instance, error.RawMessage()); + ValidChecker::Invalidate(db_instance, error); } return ErrorResult(std::move(error), query); } @@ -857,9 +873,9 @@ unique_ptr ClientContext::SubmitStatement(ClientContextLock &lock, // standard exceptions do not invalidate the current transaction invalidate_query = false; } else if (Exception::InvalidatesDatabase(error.Type())) { - // fatal exceptions invalidate the entire database + // fatal exceptions invalidate the database instance, unless scoped to an attached database auto &db_instance = DatabaseInstance::GetDatabase(*this); - ValidChecker::Invalidate(db_instance, error.RawMessage()); + ValidChecker::Invalidate(db_instance, error); } // other types of exceptions do invalidate the current transaction result = ErrorResult(std::move(error), query); @@ -1338,7 +1354,7 @@ void ClientContext::RunFunctionInTransactionInternal(ClientContextLock &lock, co invalidates_transaction = false; } else if (Exception::InvalidatesDatabase(error.Type())) { auto &db_instance = DatabaseInstance::GetDatabase(*this); - ValidChecker::Invalidate(db_instance, error.RawMessage()); + ValidChecker::Invalidate(db_instance, error); } if (require_new_transaction) { transaction.Rollback(error); @@ -1531,7 +1547,7 @@ SettingLookupResult ClientContext::TryGetCurrentSetting(const Identifier &key, V return SettingLookupResult(SettingScope::LOCAL); } // setting is not set - get the default value - return DBConfig::TryGetDefaultValue(option, result); + return db_config.TryGetDefaultValue(key, option, result); } SettingLookupResult ClientContext::TryGetCurrentUserSetting(idx_t setting_index, Value &result) const { @@ -1548,7 +1564,7 @@ ParserOptions ClientContext::GetParserOptions() { options.extensions = DBConfig::GetConfig(*this).GetCallbackManager(); options.parser_override_setting = Settings::Get(*this); options.compiled_grammar = CompiledGrammar::Get(*this); - options.context = *this; + options.context = GetContext(); return options; } diff --git a/src/duckdb/src/main/client_context_execution.cpp b/src/duckdb/src/main/client_context_execution.cpp index c1400b3cb..cd44cfc4d 100644 --- a/src/duckdb/src/main/client_context_execution.cpp +++ b/src/duckdb/src/main/client_context_execution.cpp @@ -143,7 +143,7 @@ ErrorData ClientContext::EndQueryInternal(ClientContextLock &lock, bool success, error = ErrorData(ex); if (Exception::InvalidatesDatabase(error.Type()) || error.Type() == ExceptionType::INTERNAL) { auto &db_inst = DatabaseInstance::GetDatabase(*this); - ValidChecker::Invalidate(db_inst, error.RawMessage()); + ValidChecker::Invalidate(db_inst, error); } } catch (...) { // LCOV_EXCL_START error = ErrorData("Unhandled exception!"); @@ -269,15 +269,15 @@ unique_ptr ClientContext::SubmitPreparedStatementInternal( auto &executor = *active_query->executor; auto &config = ClientConfig::GetConfig(*this); - if (config.enable_progress_bar) { + if (Settings::Get(*this)) { progress_bar_display_create_func_t display_create_func = nullptr; - if (config.print_progress_bar) { + if (Settings::Get(*this)) { // Use either a custom display function, or the default. display_create_func = config.display_create_func ? config.display_create_func : ProgressBar::DefaultProgressBarDisplay; } - active_query->progress_bar = - make_uniq(executor, NumericCast(config.wait_time), display_create_func); + active_query->progress_bar = make_uniq( + executor, NumericCast(Settings::Get(*this)), display_create_func); active_query->progress_bar->Start(); query_progress.Restart(); } @@ -482,9 +482,9 @@ QueryResultState ClientContext::FailQueryInternal(ClientContextLock &lock, BaseQ } else if (!ErrorInvalidatesQueryTransaction(error.Type())) { invalidate_transaction = false; } else if (Exception::InvalidatesDatabase(error.Type()) || error.Type() == ExceptionType::INTERNAL) { - // fatal exceptions invalidate the entire database + // fatal exceptions invalidate the database instance, unless scoped to an attached database auto &db_instance = DatabaseInstance::GetDatabase(*this); - ValidChecker::Invalidate(db_instance, error.RawMessage()); + ValidChecker::Invalidate(db_instance, error); } ProcessError(error, active_query->query); result.SetError(std::move(error)); @@ -611,7 +611,7 @@ ErrorData ClientContext::EndStatementInternal(ClientContextLock &lock, optional_ ErrorData state_error(ex); if (Exception::InvalidatesDatabase(state_error.Type()) || state_error.Type() == ExceptionType::INTERNAL) { // a fatal failure invalidates the database also when another failure is the one reported - ValidChecker::Invalidate(DatabaseInstance::GetDatabase(*this), state_error.RawMessage()); + ValidChecker::Invalidate(DatabaseInstance::GetDatabase(*this), state_error); } if (!end_error.HasError()) { end_error = std::move(state_error); diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index e59fd28ff..897c0305f 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -76,7 +76,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_GLOBAL(AccessModeSetting), DUCKDB_LOCAL(ActiveGrammarExtensionsSetting), DUCKDB_SETTING_CALLBACK(AllocatorBackgroundThreadsSetting), - DUCKDB_GLOBAL(AllocatorBulkDeallocationFlushThresholdSetting), + DUCKDB_SETTING_CALLBACK(AllocatorBulkDeallocationFlushThresholdSetting), DUCKDB_SETTING_CALLBACK(AllocatorFlushThresholdSetting), DUCKDB_SETTING_CALLBACK(AllowCommunityExtensionsSetting), DUCKDB_SETTING_CALLBACK(AllowExtensionRepositoriesSetting), @@ -99,39 +99,44 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(AutoinstallExtensionRepositorySetting), DUCKDB_SETTING(AutoinstallKnownExtensionsSetting), DUCKDB_SETTING(AutoloadKnownExtensionsSetting), + DUCKDB_SETTING_CALLBACK(BufferManagerTrackEvictionTimestampsSetting), DUCKDB_SETTING(CacheLocalFilesSetting), DUCKDB_SETTING(CatalogErrorMaxSchemasSetting), DUCKDB_SETTING_CALLBACK(CheckpointOnDetachSetting), - DUCKDB_GLOBAL(CheckpointThresholdSetting), + DUCKDB_SETTING(CheckpointOnShutdownSetting), + DUCKDB_SETTING_CALLBACK(CheckpointThresholdSetting), DUCKDB_LOCAL(CurrentDialectSetting), DUCKDB_SETTING_CALLBACK(CurrentTransactionInvalidationPolicySetting), DUCKDB_SETTING(CustomExtensionRepositorySetting), - DUCKDB_GLOBAL(CustomUserAgentSetting), - DUCKDB_GLOBAL(DebugAbortOnWalFailureSetting), + DUCKDB_SETTING_CALLBACK(CustomUserAgentSetting), + DUCKDB_SETTING(DebugAbortOnWalFailureSetting), DUCKDB_SETTING(DebugAsofIejoinSetting), DUCKDB_SETTING_CALLBACK(DebugCheckpointAbortSetting), DUCKDB_SETTING(DebugCheckpointScanSleepMsSetting), DUCKDB_SETTING(DebugCheckpointSleepMsSetting), - DUCKDB_GLOBAL(DebugDeltaOnlyVariantEncodingEnabledSetting), + DUCKDB_SETTING_CALLBACK(DebugDeltaOnlyVariantEncodingEnabledSetting), DUCKDB_SETTING(DebugDisableOptimizerSetting), DUCKDB_SETTING(EnableCachingOperatorsSetting), DUCKDB_SETTING(DebugEvictionQueueSleepMicroSecondsSetting), DUCKDB_SETTING(DebugFileDescriptorLimitSetting), DUCKDB_SETTING_CALLBACK(ForceBitpackingModeSetting), + DUCKDB_SETTING(DebugForceCheckpointSetting), DUCKDB_SETTING(DebugForceCommitFailureSetting), DUCKDB_SETTING(DebugForceCommitRevertFailureSetting), DUCKDB_SETTING(DebugForceExternalSetting), DUCKDB_SETTING(DebugForceFetchRowSetting), - DUCKDB_GLOBAL(ForceMbedtlsUnsafeSetting), + DUCKDB_SETTING(DebugForceFlushAppendFailureSetting), + DUCKDB_SETTING_CALLBACK(ForceMbedtlsUnsafeSetting), DUCKDB_SETTING(DebugForceNoCrossProductSetting), DUCKDB_SETTING(ForceUpdateToDelAndInsertSetting), - DUCKDB_GLOBAL(ForceVariantShredding), + DUCKDB_SETTING_CALLBACK(ForceVariantShredding), DUCKDB_SETTING(DebugForceWalFsyncFailureSetting), + DUCKDB_SETTING_CALLBACK(DebugInitializeSetting), DUCKDB_SETTING(DebugLocalFileSystemDelayMsSetting), - DUCKDB_GLOBAL(DebugOrderVerificationSetting), + DUCKDB_SETTING_CALLBACK(DebugOrderVerificationSetting), DUCKDB_SETTING_CALLBACK(DebugPhysicalTableScanExecutionStrategySetting), DUCKDB_SETTING(DebugSkipCheckpointOnCommitSetting), - DUCKDB_GLOBAL(DebugVerificationModeSetting), + DUCKDB_SETTING_CALLBACK(DebugVerificationModeSetting), DUCKDB_SETTING(DebugVerificationProjectionSetting), DUCKDB_SETTING(DebugVerifyAggregateStateExportSetting), DUCKDB_SETTING(DebugVerifyBlocksSetting), @@ -155,10 +160,10 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(DialectCompatibilityModeSetting), DUCKDB_SETTING_CALLBACK(DisableDatabaseInvalidationSetting), DUCKDB_SETTING(DisableTimestamptzCastsSetting), - DUCKDB_GLOBAL(DisabledCompressionMethodsSetting), + DUCKDB_SETTING_CALLBACK(DisabledCompressionMethodsSetting), DUCKDB_GLOBAL(DisabledFilesystemsSetting), DUCKDB_GLOBAL(DisabledLogTypes), - DUCKDB_GLOBAL(DisabledOptimizersSetting), + DUCKDB_SETTING_CALLBACK(DisabledOptimizersSetting), DUCKDB_SETTING_CALLBACK(DuckDBAPISetting), DUCKDB_SETTING(DynamicOrFilterThresholdSetting), DUCKDB_GLOBAL(EnableBlockAllocatorSetting), @@ -172,15 +177,15 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(EnableOptimisticWriteSetting), DUCKDB_SETTING(EnableOptimizerSetting), DUCKDB_LOCAL(EnableProfilingSetting), - DUCKDB_LOCAL(EnableProgressBarSetting), - DUCKDB_LOCAL(EnableProgressBarPrintSetting), + DUCKDB_SETTING_CALLBACK(EnableProgressBarSetting), + DUCKDB_SETTING_CALLBACK(EnableProgressBarPrintSetting), DUCKDB_SETTING(EnableViewDependenciesSetting), DUCKDB_GLOBAL(EnabledLogTypes), DUCKDB_SETTING(ErrorOnDivisionByZeroSetting), DUCKDB_SETTING(ErrorsAsJSONSetting), DUCKDB_SETTING(ExperimentalMetadataReuseSetting), DUCKDB_SETTING_CALLBACK(ExplainOutputSetting), - DUCKDB_GLOBAL(ExtensionDirectoriesSetting), + DUCKDB_SETTING_CALLBACK(ExtensionDirectoriesSetting), DUCKDB_SETTING(ExtensionDirectorySetting), DUCKDB_SETTING_CALLBACK(ExtensionRepositoryDirectorySetting), DUCKDB_SETTING_CALLBACK(ExternalFileCacheLocalMaxBlockSizeSetting), @@ -216,6 +221,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(LogQueryPathSetting), DUCKDB_GLOBAL(LoggingLevel), DUCKDB_GLOBAL(LoggingMode), + DUCKDB_GLOBAL(LoggingSink), DUCKDB_GLOBAL(LoggingStorage), DUCKDB_SETTING(MatchRecognizeMaxStatesSetting), DUCKDB_SETTING(MaxExecutionTimeSetting), @@ -241,11 +247,11 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(PreserveIdentifierCaseSetting), DUCKDB_SETTING(PreserveInsertionOrderSetting), DUCKDB_SETTING(ProduceArrowStringViewSetting), - DUCKDB_LOCAL(ProfilingCoverageSetting), + DUCKDB_SETTING_CALLBACK(ProfilingCoverageSetting), DUCKDB_LOCAL(ProfilingModeSetting), - DUCKDB_LOCAL(ProfilingOutputSetting), - DUCKDB_LOCAL(ProfilingRendererSettingsSetting), - DUCKDB_LOCAL(ProgressBarTimeSetting), + DUCKDB_SETTING_CALLBACK(ProfilingOutputSetting), + DUCKDB_SETTING_CALLBACK(ProfilingRendererSettingsSetting), + DUCKDB_SETTING_CALLBACK(ProgressBarTimeSetting), DUCKDB_SETTING_CALLBACK(ReadAheadDepthSetting), DUCKDB_SETTING(RedactHttpLogsSetting), DUCKDB_SETTING_CALLBACK(RegexMatchOperatorSemanticsSetting), @@ -264,6 +270,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(TempFileEncryptionSetting), DUCKDB_GLOBAL(ThreadsSetting), DUCKDB_SETTING_CALLBACK(TrackedMetricsSetting), + DUCKDB_SETTING(TrimFreeBlocksSetting), DUCKDB_SETTING(UsernameSetting), DUCKDB_SETTING_CALLBACK(VacuumRebuildIndexesSetting), DUCKDB_SETTING_CALLBACK(ValidateExternalFileCacheSetting), @@ -392,8 +399,7 @@ idx_t DBConfig::GetWriteBufferMemoryLimit() const { } vector DBConfig::GetExtensionDirectories() const { - std::lock_guard guard(config_lock); - return options.extension_directories; + return Settings::Get(*this); } void DBConfig::SetOption(const ConfigurationOption &option, const Value &value) { @@ -454,6 +460,12 @@ void DBConfig::SetOption(optional_ptr db, const ConfigurationO void DBConfig::ResetOption(optional_ptr db, const ConfigurationOption &option) { if (option.default_value) { // generic option + if (option.set_callback) { + 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()); return; } @@ -479,15 +491,7 @@ void DBConfig::SetOption(const Identifier &name, Value value) { } void DBConfig::ResetOption(const ExtensionOption &extension_option) { - auto &default_value = extension_option.default_value; - auto setting_index = extension_option.setting_index.GetIndex(); - if (!default_value.IsNull()) { - // Default is not NULL, override the setting - user_settings.SetUserSetting(setting_index, default_value); - } else { - // Otherwise just remove it from the 'set_variables' map - user_settings.ClearSetting(setting_index); - } + user_settings.ClearSetting(extension_option.setting_index.GetIndex()); } void DBConfig::ResetGenericOption(idx_t setting_index) { @@ -623,7 +627,6 @@ void DBConfig::AddExtensionOption(const Identifier &name, string description, Lo } void DBConfig::AddExtensionOption(const Identifier &name, ExtensionOption extension_option) { - auto default_value = extension_option.default_value; auto setting_index = user_settings.AddExtensionOption(name, std::move(extension_option)); // copy over unrecognized options, if they match the new extension option auto iter = options.unrecognized_options.find(name); @@ -631,10 +634,6 @@ void DBConfig::AddExtensionOption(const Identifier &name, ExtensionOption extens user_settings.SetUserSetting(setting_index, iter->second); options.unrecognized_options.erase(iter); } - if (!default_value.IsNull() && !user_settings.IsSet(setting_index)) { - // Default value is set, insert it into the 'set_variables' list - user_settings.SetUserSetting(setting_index, default_value); - } } identifier_map_t DBConfig::GetExtensionSettings() const { @@ -892,6 +891,19 @@ SettingLookupResult DBConfig::TryGetDefaultValue(optional_ptr option, + Value &result) const { + if (option) { + return TryGetDefaultValue(option, result); + } + ExtensionOption extension_option; + if (!TryGetExtensionOption(key, extension_option) || extension_option.default_value.IsNull()) { + return SettingLookupResult(); + } + result = extension_option.default_value; + return SettingLookupResult(SettingScope::GLOBAL); +} + SettingLookupResult DBConfig::TryGetCurrentSetting(const Identifier &key, Value &result) const { optional_ptr option; auto setting_index = TryGetSettingIndex(key, option); @@ -901,7 +913,7 @@ SettingLookupResult DBConfig::TryGetCurrentSetting(const Identifier &key, Value return lookup_result; } } - return TryGetDefaultValue(option, result); + return TryGetDefaultValue(key, option, result); } optional_idx DBConfig::TryGetSettingIndex(const Identifier &name, @@ -952,8 +964,9 @@ const string DBConfig::UserAgent() const { user_agent += " " + duckdb_api; } - if (!options.custom_user_agent.empty()) { - user_agent += " " + options.custom_user_agent; + auto custom_user_agent = Settings::Get(*this); + if (!custom_user_agent.empty()) { + user_agent += " " + custom_user_agent; } return user_agent; } @@ -1028,11 +1041,6 @@ bool DBConfig::IsOptimizerDisabled(OptimizerType type) const { return options.disabled_optimizers.find(type) != options.disabled_optimizers.end(); } -LogicalType DBConfig::GetForceVariantShredding() const { - std::lock_guard guard(config_lock); - return options.force_variant_shredding; -} - identifier_set_t DBConfig::GetAllowedConfigs() const { std::lock_guard guard(config_lock); return options.allowed_configs; @@ -1107,11 +1115,47 @@ vector DBConfig::GetAllowedPaths() const { return vector(options.allowed_paths.begin(), options.allowed_paths.end()); } +static bool HasRemotePathTraversal(const string &path) { + auto scheme_end = path.find("://"); + if (scheme_end == string::npos || Path::FromString(path).IsLocal()) { + return false; + } + + auto path_to_check = StringUtil::Lower(path); + if (StringUtil::StartsWith(path_to_check, "http://") || StringUtil::StartsWith(path_to_check, "https://")) { + // HTTP queries and fragments are not part of the path. + path_to_check = path_to_check.substr(0, path_to_check.find_first_of("?#")); + } + auto path_start = path_to_check.find_first_of("/\\", scheme_end + 3); + if (path_start == string::npos) { + return false; + } + + // Replace all separator variants with a literal / + path_to_check = path_to_check.substr(path_start); + path_to_check = StringUtil::Replace(path_to_check, "\\", "/"); + path_to_check = StringUtil::Replace(path_to_check, "%2f", "/"); + path_to_check = StringUtil::Replace(path_to_check, "%5c", "/"); + // Ensure encoded dots are also treated as a . + path_to_check = StringUtil::Replace(path_to_check, "%2e", "."); + + for (const auto &segment : StringUtil::Split(path_to_check, '/')) { + if (segment == "..") { + return true; + } + } + return false; +} + bool DBConfig::CanAccessFile(const string &input_path, FileType type, optional_ptr opener) { if (Settings::Get(*this)) { // all external access is allowed return true; } + // Remote backends can resolve parent segments outside the allowed prefix. + if (HasRemotePathTraversal(input_path)) { + return false; + } string path = SanitizeAllowedPath(input_path, opener); lock_guard guard(allowed_paths_lock); diff --git a/src/duckdb/src/main/context.cpp b/src/duckdb/src/main/context.cpp index 34f4c8caf..41d8e0d80 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::InterruptCheck() const { + if (context) { + context->InterruptCheck(); + } +} + bool Context::IsClient() const { return context != nullptr; } @@ -369,8 +375,8 @@ const shared_ptr &Context::GetQueryProfilerPtr() const { return profiler; } -shared_ptr DatabaseInstance::Services() { - return make_shared_ptr(*this); +Context &DatabaseInstance::GetContext() { + return *services; } } // namespace duckdb diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index b258206eb..f4abcee00 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -20,6 +20,7 @@ #include "duckdb/main/attached_database.hpp" #include "duckdb/main/capi/extension_api.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/connection_manager.hpp" #include "duckdb/main/database_file_opener.hpp" #include "duckdb/main/database_file_path_manager.hpp" @@ -49,6 +50,7 @@ #ifndef DUCKDB_NO_THREADS #include "duckdb/common/thread.hpp" +#include "duckdb/main/settings.hpp" #endif namespace duckdb { @@ -87,6 +89,7 @@ DatabaseInstance::DatabaseInstance() : db_validity(*this) { create_api_v1 = nullptr; invoke_capi_v2 = nullptr; parser_cache = make_uniq(); + services = make_uniq(*this); } ParserCache &DatabaseInstance::GetParserCache() { @@ -609,9 +612,10 @@ void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path if (new_config.buffer_pool) { config.buffer_pool = std::move(new_config.buffer_pool); } else { - config.buffer_pool = make_shared_ptr(*config.block_allocator, config.options.maximum_memory, - config.options.buffer_manager_track_eviction_timestamps, - config.options.allocator_bulk_deallocation_flush_threshold); + config.buffer_pool = make_shared_ptr( + *config.block_allocator, config.options.maximum_memory, + Settings::Get(config), + DBConfig::ParseMemoryLimitOrMaximum(Settings::Get(config))); } config.db_cache_entry = std::move(new_config.db_cache_entry); config.path_manager = std::move(new_config.path_manager); @@ -658,7 +662,7 @@ shared_ptr DatabaseInstance::GetMbedTLSUtil(bool force_mbedtls) } shared_ptr DatabaseInstance::GetEncryptionUtil(bool read_only) { - auto force_mbedtls = config.options.force_mbedtls; + auto force_mbedtls = Settings::Get(config); if (force_mbedtls) { // return mbedtls if setting is enabled diff --git a/src/duckdb/src/main/database_manager.cpp b/src/duckdb/src/main/database_manager.cpp index c6ed33a8c..0347a3dac 100644 --- a/src/duckdb/src/main/database_manager.cpp +++ b/src/duckdb/src/main/database_manager.cpp @@ -595,11 +595,17 @@ vector> DatabaseManager::GetDatabases() { } void DatabaseManager::ResetDatabases() { - auto shared_db_pointers = GetDatabases(); - for (auto &entry : shared_db_pointers) { - entry->Close(DatabaseCloseAction::TRY_CHECKPOINT); - entry.reset(); + // the instance destructor runs this, so take the map instead of allocating a copy + identifier_map_t> attached; + { + lock_guard guard(databases_lock); + attached = std::move(databases); + } + for (auto &entry : attached) { + entry.second->Close(DatabaseCloseAction::TRY_CHECKPOINT); + entry.second.reset(); } + system->Close(DatabaseCloseAction::TRY_CHECKPOINT); } Catalog &DatabaseManager::GetSystemCatalog() { diff --git a/src/duckdb/src/main/extension/extension_helper.cpp b/src/duckdb/src/main/extension/extension_helper.cpp index 59c9cf1b2..bb64c4e88 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -875,7 +875,7 @@ vector ExtensionHelper::GetTrustedPublicKeys(DatabaseInstance &db, Exten return keys; case ExtensionRepositoryType::USER_PROVIDED: { // when adding repositories has been forbidden, the user repositories are distrusted entirely: their keys are - // no longer trusted, so extensions installed from them can no longer be loaded. Note that 'undecided' still + // no longer trusted, so extensions installed from them can no longer be loaded. Note that 'hosts' still // trusts existing repositories if (!ExtensionRepositoryManager::TrustsExistingRepositories(db)) { return keys; @@ -883,7 +883,9 @@ vector ExtensionHelper::GetTrustedPublicKeys(DatabaseInstance &db, Exten // only the keys of the repository the extension came from are trusted ExtensionRepository repository; auto &fs = FileSystem::GetLocal(db); - if (ExtensionRepositoryManager::TryGetRepository(db, fs, repository_name, repository)) { + // under 'hosts_only' only a repository resolved from its host is trusted + if (ExtensionRepositoryManager::TryGetRepository(db, fs, repository_name, repository) && + ExtensionRepositoryManager::TrustsRepository(db, repository)) { for (auto &public_key : repository.public_keys) { keys.push_back(ExtensionRepositoryManager::ToPEMPublicKey(public_key)); } diff --git a/src/duckdb/src/main/extension/extension_install.cpp b/src/duckdb/src/main/extension/extension_install.cpp index 4e975159d..efb4a3b1e 100644 --- a/src/duckdb/src/main/extension/extension_install.cpp +++ b/src/duckdb/src/main/extension/extension_install.cpp @@ -138,6 +138,43 @@ vector ExtensionHelper::GetExtensionDirectoryPath(DatabaseInstance &db, return extension_directories; } +vector ExtensionHelper::GetInstalledExtensionDirectories(ClientContext &context) { + auto &db = DatabaseInstance::GetDatabase(context); + auto &fs = FileSystem::GetFileSystem(context); + return GetInstalledExtensionDirectories(db, fs); +} + +vector ExtensionHelper::GetInstalledExtensionDirectories(DatabaseInstance &db, + FileSystem &fs) { + auto extension_directories = GetExtensionDirectoryPath(db, fs); + vector result; + for (auto &directory : extension_directories) { + result.push_back({directory, string()}); + } + + // Per-repository install folders are discovered on disk, independent of whether their repository is trusted + for (auto &directory : extension_directories) { + auto repositories_directory = fs.JoinPath(directory, "repositories"); + if (!fs.DirectoryExists(repositories_directory)) { + continue; + } + vector repository_names; + fs.ListFiles(repositories_directory, [&](const string &name, bool is_directory) { + string normalized; + if (!is_directory || !ExtensionRepositoryManager::TryNormalizeRepositoryName(name, normalized) || + normalized != name || !ExtensionRepository::TryGetRepositoryUrl(name).empty()) { + return; + } + repository_names.push_back(name); + }); + std::sort(repository_names.begin(), repository_names.end()); + for (auto &name : repository_names) { + result.push_back({fs.JoinPath(repositories_directory, name), name}); + } + } + return result; +} + bool ExtensionHelper::IsInstalledExtensionFile(const string &path) { // an install writes .duckdb_extension.tmp-.duckdb_extension before it moves the file in place return StringUtil::EndsWith(path, ".duckdb_extension") && !StringUtil::Contains(path, ".duckdb_extension.tmp-"); diff --git a/src/duckdb/src/main/extension/extension_install_dynamic.cpp b/src/duckdb/src/main/extension/extension_install_dynamic.cpp index 3aadea291..1a80383e2 100644 --- a/src/duckdb/src/main/extension/extension_install_dynamic.cpp +++ b/src/duckdb/src/main/extension/extension_install_dynamic.cpp @@ -206,16 +206,6 @@ static void VerifyCanDownloadExtension(DatabaseInstance &db, const string &url) if (Settings::Get(db) || ExtensionRepository::IsOfficialRepositoryUrl(url)) { return; } - // urls are matched against allowed_directories by prefix without being normalized, so reject dot segments - // (also percent-encoded) that the server could resolve to a location outside of the allowed directory - auto lower_url = StringUtil::Lower(url); - for (auto &segment : StringUtil::Split(lower_url, '/')) { - if (segment == "." || segment == ".." || StringUtil::Contains(segment, "%2e")) { - throw PermissionException("Cannot download extension from \"%s\" - urls with dot segments are not " - "allowed when external access is disabled", - url); - } - } if (db.config.CanAccessFile(url, FileType::FILE_TYPE_REGULAR)) { return; } @@ -437,11 +427,12 @@ unique_ptr InstallExternalExtension(DatabaseInstance &db, string install_path = local_path; if (options.repository && options.repository->type == ExtensionRepositoryType::USER_PROVIDED) { // the opt-in gates adding a repository, i.e. trusting a new signing key. An existing repository stays trusted - // while 'undecided' or 'allowed', as it does for LOAD - if (!ExtensionRepositoryManager::TrustsExistingRepositories(db)) { + // while 'hosts' or 'allowed', as it does for LOAD + if (!ExtensionRepositoryManager::TrustsRepository(db, *options.repository)) { throw PermissionException( - "Installing extensions from a user-provided repository is not permitted while " + "Installing extensions from the user-provided repository '%s' is not permitted while " "allow_extension_repositories='%s'", + options.repository->name, ExtensionRepositoryManager::AccessToString(ExtensionRepositoryManager::GetAccess(db))); } install_path = fs.JoinPath(fs.JoinPath(local_path, "repositories"), options.repository->name); diff --git a/src/duckdb/src/main/extension/extension_load.cpp b/src/duckdb/src/main/extension/extension_load.cpp index eef2efc3a..f2262ba83 100644 --- a/src/duckdb/src/main/extension/extension_load.cpp +++ b/src/duckdb/src/main/extension/extension_load.cpp @@ -486,6 +486,28 @@ bool ExtensionHelper::CheckExtensionBufferSignature(DatabaseInstance &db, const signature_key_fingerprint); } +#ifndef WASM_LOADABLE_EXTENSIONS +// The trusted user-provided repositories for which is_installed holds. This only feeds an error message, so a +// repository file that cannot be read is skipped rather than reported +static vector FindUserRepositoryInstalls(DatabaseInstance &db, FileSystem &fs, + const std::function &is_installed) { + vector result; + if (!ExtensionRepositoryManager::TrustsExistingRepositories(db)) { + return result; + } + try { + for (auto &repository : ExtensionRepositoryManager::GetRepositories(db, fs)) { + if (is_installed(repository.name)) { + result.push_back(repository.name); + } + } + } catch (std::exception &) { + result.clear(); + } + return result; +} +#endif + bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const string &extension, const string &repository_name, bool core_only, ExtensionInitResult &result, string &error) { @@ -523,6 +545,9 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const } } + // the user-provided repositories that have the extension installed, when a bare load cannot find it + vector installed_in_repositories; + // shorthand case if (!ExtensionHelper::IsFullPath(extension)) { direct_load = false; @@ -552,7 +577,8 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const #else // Local function to process local path - auto ComputeLocalExtensionPath = [&](const string &base_path, const string &extension_name) -> string { + auto ComputeLocalExtensionPath = [&](const string &base_path, const string &extension_name, + const string &user_repository) -> string { // convert random separators to platform-canonic string local_path = fs.ConvertSeparators(base_path); // expand ~ in extension directory @@ -561,8 +587,8 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const for (auto &path_ele : path_components) { local_path = fs.JoinPath(local_path, path_ele); } - if (expect_user_repo) { - local_path = fs.JoinPath(fs.JoinPath(local_path, "repositories"), repository_name); + if (!user_repository.empty()) { + local_path = fs.JoinPath(fs.JoinPath(local_path, "repositories"), user_repository); } return fs.JoinPath(local_path, extension_name + ".duckdb_extension"); }; @@ -587,9 +613,10 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const } // Try each directory in sequence until extension is found + const string user_repository = expect_user_repo ? repository_name : string(); bool found = false; for (const auto &directory : search_directories) { - filename = ComputeLocalExtensionPath(directory, extension_name); + filename = ComputeLocalExtensionPath(directory, extension_name, user_repository); if (fs.FileExists(filename)) { found = true; break; @@ -598,7 +625,17 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const // If not found in any directory, use the first directory for error reporting if (!found) { - filename = ComputeLocalExtensionPath(search_directories[0], extension_name); + filename = ComputeLocalExtensionPath(search_directories[0], extension_name, user_repository); + if (repository_name.empty()) { + installed_in_repositories = FindUserRepositoryInstalls(db, fs, [&](const string &repository) { + for (const auto &directory : search_directories) { + if (fs.FileExists(ComputeLocalExtensionPath(directory, extension_name, repository))) { + return true; + } + } + return false; + }); + } } #endif } else { @@ -613,8 +650,12 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const } if (!fs.FileExists(filename)) { string message; - bool exact_match = ExtensionHelper::CreateSuggestions(extension, message); - if (exact_match) { + if (!installed_in_repositories.empty()) { + message = StringUtil::Format("Note: extension '%s' exists in one or more user-provided repositories.\n" + "Consider `LOAD %s FROM `", + extension, extension); + message += StringUtil::CandidatesMessage(installed_in_repositories, "Candidate repositories"); + } else if (ExtensionHelper::CreateSuggestions(extension, message)) { message += "\nInstall it first using \"INSTALL " + extension + "\"."; } error = StringUtil::Format("Extension \"%s\" not found.\n%s", filename, message); @@ -817,6 +858,7 @@ void ExtensionHelper::LoadExternalExtensionInternal(DatabaseInstance &db, FileSy const string &repository_name, bool core_only, ExtensionActiveLoad &info, optional_ptr context) { auto extension_init_result = InitialLoad(db, fs, extension, repository_name, core_only); + auto loaded_path = fs.CanonicalizePath(extension_init_result.filename); // C++ ABI if (extension_init_result.abi_type == ExtensionABIType::CPP) { @@ -840,7 +882,7 @@ void ExtensionHelper::LoadExternalExtensionInternal(DatabaseInstance &db, FileSy D_ASSERT(extension_init_result.install_info); - info.FinishLoad(*extension_init_result.install_info); + info.FinishLoad(*extension_init_result.install_info, loaded_path); return; } @@ -864,7 +906,7 @@ void ExtensionHelper::LoadExternalExtensionInternal(DatabaseInstance &db, FileSy D_ASSERT(extension_init_result.install_info); - info.FinishLoad(*extension_init_result.install_info); + info.FinishLoad(*extension_init_result.install_info, loaded_path); return; } @@ -903,7 +945,7 @@ void ExtensionHelper::LoadExternalExtensionInternal(DatabaseInstance &db, FileSy D_ASSERT(extension_init_result.install_info); - info.FinishLoad(*extension_init_result.install_info); + info.FinishLoad(*extension_init_result.install_info, loaded_path); return; } diff --git a/src/duckdb/src/main/extension/extension_repository_manager.cpp b/src/duckdb/src/main/extension/extension_repository_manager.cpp index e69c0a277..3aec461a1 100644 --- a/src/duckdb/src/main/extension/extension_repository_manager.cpp +++ b/src/duckdb/src/main/extension/extension_repository_manager.cpp @@ -4,14 +4,19 @@ #include "duckdb/common/file_system.hpp" #include "duckdb/common/types/blob.hpp" #include "duckdb/common/serializer/buffered_file_writer.hpp" +#include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/uuid.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/extension_helper.hpp" +#include "duckdb/main/http/http_transport_manager.hpp" +#include "duckdb/main/http/http_util.hpp" #include "duckdb/main/settings.hpp" #include "mbedtls_wrapper.hpp" #include "yyjson.hpp" +#include + using namespace duckdb_yyjson; // NOLINT namespace duckdb { @@ -126,8 +131,47 @@ string ExtensionRepositoryManager::GetPublicKeyFingerprint(const string &compact } //===--------------------------------------------------------------------===// -// Repository storage +// Repository metadata //===--------------------------------------------------------------------===// +//! Read a small file that may live on a remote file system (autoloading the extension that provides it), bounded by +//! MAX_METADATA_FILE_SIZE: a metadata file is a few lines of json +//! Remote file systems are provided by extensions - autoload the one `path` needs if necessary. A missing extension is +//! reported as such: it is not something the remote side did +static void LoadExtensionForRemotePath(DatabaseInstance &db, optional_ptr context, const string &path) { + auto &fs = db.GetFileSystem(); + string required_extension; + if (fs.IsRemoteFile(path, required_extension) && !db.ExtensionIsLoaded(required_extension)) { + if (!context || !Settings::Get(*context)) { + throw MissingExtensionException( + StringUtil::Format("reading '%s' requires the %s extension, which is not loaded: run `INSTALL AND LOAD " + "%s;` first", + path, required_extension, required_extension)); + } + try { + ExtensionHelper::AutoLoadExtension(*context, required_extension); + } catch (std::exception &ex) { + ErrorData error(ex); + throw MissingExtensionException(StringUtil::Format( + "reading '%s' requires the %s extension, which could not be autoloaded: %s\nRun `INSTALL AND LOAD %s;` " + "first", + path, required_extension, error.RawMessage(), required_extension)); + } + } +} + +static string ReadSmallRemoteFile(DatabaseInstance &db, optional_ptr context, const string &path) { + LoadExtensionForRemotePath(db, context, path); + auto &fs = db.GetFileSystem(); + auto handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ); + auto file_size = handle->GetFileSize(); + if (file_size > MAX_METADATA_FILE_SIZE) { + throw IOException("File is %llu bytes, which is too large to be a repository metadata file", file_size); + } + auto buffer = make_unsafe_uniq_array(file_size); + handle->Read(buffer.get(), file_size, 0); + return string(buffer.get(), file_size); +} + //! Fetch the public keys that the repository publishes at its prefix. Note that the keys are pinned when the repository //! is created: the fingerprints that are reported back are what identify the keys from there on vector ExtensionRepositoryManager::FetchPublicKeys(DatabaseInstance &db, optional_ptr context, @@ -136,31 +180,21 @@ vector ExtensionRepositoryManager::FetchPublicKeys(DatabaseInstance &db, StringUtil::RTrim(metadata_path, "/"); metadata_path += "/" + string(METADATA_FILE); - auto &fs = db.GetFileSystem(); - // remote file systems are provided by extensions - autoload them if necessary - string required_extension; - if (context && fs.IsRemoteFile(metadata_path, required_extension) && !db.ExtensionIsLoaded(required_extension) && - Settings::Get(*context)) { - ExtensionHelper::AutoLoadExtension(*context, required_extension); - } - string contents; try { - auto handle = fs.OpenFile(metadata_path, FileFlags::FILE_FLAGS_READ); - auto file_size = handle->GetFileSize(); - if (file_size > MAX_METADATA_FILE_SIZE) { - throw IOException("File is %llu bytes, which is too large to be a repository metadata file", file_size); - } - auto buffer = make_unsafe_uniq_array(file_size); - handle->Read(buffer.get(), file_size, 0); - contents = string(buffer.get(), file_size); + contents = ReadSmallRemoteFile(db, context, metadata_path); + } catch (MissingExtensionException &) { + throw; } catch (std::exception &ex) { ErrorData error(ex); throw IOException("Failed to read the metadata file of the extension repository from '%s': %s\nProvide the key " "directly using `USING PUBLIC KEY ''` if the repository does not serve it", metadata_path, error.RawMessage()); } + return ParsePublicKeys(contents, metadata_path); +} +vector ExtensionRepositoryManager::ParsePublicKeys(const string &contents, const string &metadata_path) { RepositoryJSONDocument document(yyjson_read(contents.c_str(), contents.size(), 0)); if (!document.doc) { throw IOException("Failed to read extension repository metadata file '%s': the file is not valid json", @@ -200,8 +234,8 @@ vector ExtensionRepositoryManager::FetchPublicKeys(DatabaseInstance &db, ExtensionRepositoryAccess ExtensionRepositoryManager::ParseAccess(const string &value) { auto lower = StringUtil::Lower(value); - if (lower == "undecided") { - return ExtensionRepositoryAccess::UNDECIDED; + if (lower == "hosts") { + return ExtensionRepositoryAccess::HOSTS; } if (lower == "allowed") { return ExtensionRepositoryAccess::ALLOWED; @@ -209,8 +243,11 @@ ExtensionRepositoryAccess ExtensionRepositoryManager::ParseAccess(const string & if (lower == "forbidden") { return ExtensionRepositoryAccess::FORBIDDEN; } - throw InvalidInputException("Invalid value '%s' for allow_extension_repositories: expected 'undecided', 'allowed' " - "or 'forbidden'", + if (lower == "hosts_only") { + return ExtensionRepositoryAccess::HOSTS_ONLY; + } + throw InvalidInputException("Invalid value '%s' for allow_extension_repositories: expected 'hosts', 'allowed', " + "'hosts_only' or 'forbidden'", value); } @@ -220,8 +257,10 @@ string ExtensionRepositoryManager::AccessToString(ExtensionRepositoryAccess acce return "allowed"; case ExtensionRepositoryAccess::FORBIDDEN: return "forbidden"; + case ExtensionRepositoryAccess::HOSTS_ONLY: + return "hosts_only"; default: - return "undecided"; + return "hosts"; } } @@ -232,31 +271,56 @@ ExtensionRepositoryAccess ExtensionRepositoryManager::GetAccess(DatabaseInstance bool ExtensionRepositoryManager::TrustsExistingRepositories(DatabaseInstance &db) { // the access values that trust existing repositories are listed explicitly, any other value distrusts them switch (GetAccess(db)) { - case ExtensionRepositoryAccess::UNDECIDED: + case ExtensionRepositoryAccess::HOSTS: case ExtensionRepositoryAccess::ALLOWED: + case ExtensionRepositoryAccess::HOSTS_ONLY: return true; default: return false; } } +bool ExtensionRepositoryManager::TrustsRepository(DatabaseInstance &db, const ExtensionRepository &repository) { + if (!TrustsExistingRepositories(db)) { + return false; + } + if (GetAccess(db) == ExtensionRepositoryAccess::HOSTS_ONLY) { + // only a repository resolved from its host is trusted - one added by prefix is distrusted + return !repository.host.empty(); + } + return true; +} + 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 db.config.CheckLock(AllowExtensionRepositoriesSetting::Name); } -void ExtensionRepositoryManager::CheckCanCreate(DatabaseInstance &db) { +void ExtensionRepositoryManager::CheckCanCreate(DatabaseInstance &db, bool from_host) { CheckNotLocked(db); - // adding a repository adds a new trusted signing key, so the user must explicitly opt in first + // 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: 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; + } throw PermissionException("Adding extension repositories is not enabled: set " - "allow_extension_repositories='allowed' to opt in"); + "allow_extension_repositories='allowed' to opt in, or use `CREATE EXTENSION " + "REPOSITORY ` without a prefix, so that the host names its repository"); } } @@ -266,23 +330,244 @@ bool ExtensionRepositoryManager::TryNormalizeRepositoryName(const string &name, } result = StringUtil::Lower(name); for (auto c : result) { - if (!StringUtil::CharacterIsAlpha(c) && !StringUtil::CharacterIsDigit(c) && c != '_' && c != '-') { + if (!StringUtil::CharacterIsAlpha(c) && !StringUtil::CharacterIsDigit(c) && c != '_' && c != '-' && c != '.') { return false; } } + // a dot lets a repository be named after a host ('carlopi.github.io'); as a file name it must still be a plain + // name: not hidden, not '.' or '..' or a run of dots + if (result.front() == '.' || result.back() == '.' || result.find("..") != string::npos) { + return false; + } return true; } +//! The repository name a stored file carries in its name: the file name without the fixed suffix +static string RepositoryNameOfFile(const string &file_name) { + D_ASSERT(StringUtil::EndsWith(file_name, ExtensionRepositoryManager::FILE_EXTENSION)); + return file_name.substr(0, file_name.size() - strlen(ExtensionRepositoryManager::FILE_EXTENSION)); +} + string ExtensionRepositoryManager::NormalizeRepositoryName(const string &name) { string result; if (!TryNormalizeRepositoryName(name, result)) { throw InvalidInputException("Invalid extension repository name '%s': names cannot be empty and can only " - "contain letters, digits, '_' and '-'", + "contain letters, digits, '_', '-' and '.' (not at the start or the end, and not " + "two in a row)", name); } return result; } +//===--------------------------------------------------------------------===// +// Repositories resolved from their host: CREATE EXTENSION REPOSITORY without a prefix +// +// The name is the publisher's host. The host serves `https:///.well-known/duckdb-extension-repo.json`, the same +// metadata file a prefix serves, and only its `{"version": 1, "repository_url": ""}` is read: where the repository +// is. From there on it is CREATE EXTENSION REPOSITORY WITH PREFIX '', keys fetched from the prefix and +// pinned. The fetch over https from the host is what makes the file the host's own statement. +//===--------------------------------------------------------------------===// + +static constexpr const idx_t METADATA_FORMAT_VERSION = 1; + +//! Whether a name is one DuckDB will reach over the network as a host: two or more labels of letters, digits and '-' +//! separated by single dots, no label starting or ending with '-', the last label letters only (so no IPv4 literal), +//! 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 != '-') { + return false; + } + continue; + } + // end of a label + if (i == label_start || text[label_start] == '-' || text[i - 1] == '-') { + return false; + } + label_count++; + label_start = i + 1; + } + if (label_count < 2) { + return false; + } + for (idx_t i = text.rfind('.') + 1; i < text.size(); i++) { + if (!StringUtil::CharacterIsAlpha(text[i])) { + return false; + } + } + auto lower = StringUtil::Lower(text); + return lower != "localhost" && !StringUtil::EndsWith(lower, ".localhost"); +} + +//! Read a small file over https for resolving a repository from its host. The file decides which prefix and which +//! signing keys get trusted, so it is not read through the file system, whose http settings the user controls: the url +//! must be https, a secret or setting that switches verification off for it is refused, and the server certificate is +//! verified whatever the provider's defaults are. +//! +//! Redirects are followed as the client follows them, wherever they lead, http included. The first hop is verified +//! https, so a redirect can only come from the host itself: it is the host speaking, and where it sends its visitors +//! (a moved site, a different domain, even plain http) is the host's own decision and the host's own risk, exactly as +//! the content of the file is. Nothing here inspects the hops. +static string ReadAuthenticatedHTTPS(DatabaseInstance &db, optional_ptr context, const string &url, + const char *what) { + if (!StringUtil::StartsWith(url, "https://")) { + throw InvalidInputException("The %s must be reached over https, got '%s'", what, url); + } + LoadExtensionForRemotePath(db, context, url); + + auto &manager = db.config.GetHTTPTransportManager(); + auto session = context ? manager.CreateSession(*context, url) : manager.CreateSession(db, url); + auto ¶ms = session.Parameters(); + // a secret or setting that switches verification off for this url is refused outright, rather than silently + // overruled: it says the user does not want this host verified, and an unverified host cannot vouch for anything + if (params.override_verify_ssl && !params.verify_ssl) { + throw InvalidInputException( + "Cannot read the %s '%s': certificate verification is disabled for it (a VERIFY_SSL " + "false secret or setting applies), and a repository is only resolved from a host " + "that is verified", + what, url); + } + // ...and verification is required regardless of the provider's defaults + params.RequireServerCertificateVerification(); + params.keep_alive = false; + + // the body is received through a handler so that the transfer stops as soon as it exceeds the cap, or before it + // starts when the announced length does: the cap is on what is downloaded, not on what is kept afterwards + string body; + bool too_large = false; + auto response_handler = [&](const HTTPResponse &response) { + // called once per response (a redirect or a retry starts another one): begin afresh + body.clear(); + if (too_large) { + // a previous attempt already received too much: do not download it again + return false; + } + if (response.HasHeader("Content-Length")) { + idx_t content_length; + if (TryCast::Operation(string_t(response.GetHeaderValue("Content-Length")), content_length, + false) && + content_length > MAX_METADATA_FILE_SIZE) { + too_large = true; + return false; + } + } + return true; + }; + auto content_handler = [&](const_data_ptr_t data, idx_t data_length) { + if (body.size() + data_length > MAX_METADATA_FILE_SIZE) { + too_large = true; + return false; + } + body.append(const_char_ptr_cast(data), data_length); + return true; + }; + HTTPHeaders headers(db); + GetRequestInfo get_request(url, headers, params, response_handler, content_handler); + get_request.try_request = true; + auto response = session.Request(get_request); + if (too_large) { + throw IOException("Failed to read the %s '%s': it is larger than the %llu bytes a repository metadata file can " + "take", + what, url, MAX_METADATA_FILE_SIZE); + } + if (response->HasRequestError()) { + throw IOException("Failed to read the %s '%s': %s", what, url, response->GetRequestError()); + } + if (!response->Success()) { + throw IOException("Failed to read the %s '%s': HTTP %d %s", what, url, static_cast(response->status), + response->GetError()); + } + return body; +} + +//! The root object of a host's metadata file, after checking its version +static yyjson_val *ReadVersionedObject(RepositoryJSONDocument &document, const string &path) { + if (!document.doc) { + throw IOException("Failed to read the extension repository metadata file '%s': the file is not valid json", + path); + } + auto root = yyjson_doc_get_root(document.doc); + if (!root || !yyjson_is_obj(root)) { + throw IOException("Failed to read the extension repository metadata file '%s': expected a json object", path); + } + auto version = yyjson_obj_get(root, "version"); + if (!version || !yyjson_is_uint(version)) { + throw IOException("Failed to read the extension repository metadata file '%s': missing or invalid field " + "'version'", + path); + } + if (yyjson_get_uint(version) != METADATA_FORMAT_VERSION) { + throw IOException("Failed to read the extension repository metadata file '%s': it has version %llu, this " + "version of DuckDB understands version %llu", + path, yyjson_get_uint(version), METADATA_FORMAT_VERSION); + } + return root; +} + +ExtensionRepositoryResolution ExtensionRepositoryManager::ResolveRepositoryFromHost(DatabaseInstance &db, + optional_ptr context, + const string &name_p) { + // called by CreateRepository once the access check and the conflict check have passed + auto name = NormalizeRepositoryName(name_p); + // only a name that is a host on the public internet is reached: a single word would resolve through search + // domains to a host the user did not name, an IP literal or localhost is nobody's statement + if (!IsHostName(name)) { + throw InvalidInputException( + "Cannot create extension repository '%s': '%s' is not a host name. A host has two or " + "more labels 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); + } + ExtensionRepositoryResolution resolution; + resolution.host = name; + + // the host is the name the user typed, reached over verified https: that is what makes the file the host's own + // statement + auto metadata_path = "https://" + name + "/" + string(METADATA_FILE); + string contents; + try { + contents = ReadAuthenticatedHTTPS(db, context, metadata_path, "host's metadata file"); + } catch (MissingExtensionException &) { + throw; + } catch (InvalidInputException &) { + // a policy refusal (verification switched off for the url): not something the host did + throw; + } catch (std::exception &ex) { + 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()); + } + RepositoryJSONDocument document(yyjson_read(contents.c_str(), contents.size(), 0)); + auto root = ReadVersionedObject(document, metadata_path); + auto url = yyjson_obj_get(root, "repository_url"); + if (!url || !yyjson_is_str(url) || yyjson_get_len(url) == 0) { + throw IOException("Failed to read the extension repository metadata file '%s': missing or invalid field " + "'repository_url'", + metadata_path); + } + resolution.url = string(yyjson_get_str(url), yyjson_get_len(url)); + StringUtil::RTrim(resolution.url, "/"); + // the keys are fetched from the prefix next: over anything but https they could be anyone's + if (!StringUtil::StartsWith(resolution.url, "https://")) { + throw InvalidInputException("Cannot create extension repository '%s': the host names the repository at '%s', " + "but a repository resolved from its host must be served over https, so that its " + "signing keys are fetched from where the host says they are", + name, resolution.url); + } + return resolution; +} + +//===--------------------------------------------------------------------===// +// Repository storage +//===--------------------------------------------------------------------===// string ExtensionRepositoryManager::GetRepositoryDirectory(DatabaseInstance &db, FileSystem &fs) { auto directory = Settings::Get(db); if (directory.empty()) { @@ -358,13 +643,24 @@ ExtensionRepository ExtensionRepositoryManager::ReadRepository(FileSystem &fs, c result.path = ReadJSONString(root, "url", path); result.public_keys = ReadJSONKeys(root, path); result.type = ExtensionRepositoryType::USER_PROVIDED; + auto host = yyjson_obj_get(root, "host"); + if (host && yyjson_is_str(host)) { + result.host = string(yyjson_get_str(host), yyjson_get_len(host)); + } - auto expected_name = fs.ExtractBaseName(path); + auto expected_name = RepositoryNameOfFile(fs.ExtractName(path)); if (NormalizeRepositoryName(result.name) != expected_name) { throw IOException("Failed to read extension repository file '%s': the file contains repository '%s', but '%s' " "was expected based on the file name", path, result.name, expected_name); } + // a host means "resolved from that host", and a repository resolved from a host is named after it: a file that + // says otherwise was not written by DuckDB, and is not trusted on its word + if (!result.host.empty() && (!IsHostName(result.host) || StringUtil::Lower(result.host) != expected_name)) { + throw IOException("Failed to read extension repository file '%s': the file names host '%s', but a repository " + "resolved from a host is named after it ('%s')", + path, result.host, expected_name); + } // a user provided repository must never shadow a built-in repository: those are resolved first, so a file named // after a built-in repository would silently redirect installs to an attacker controlled key and url if (!ExtensionRepository::TryGetRepositoryUrl(result.name).empty()) { @@ -376,18 +672,30 @@ ExtensionRepository ExtensionRepositoryManager::ReadRepository(FileSystem &fs, c ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstance &db, FileSystem &fs, optional_ptr context, - const ExtensionRepository &repository, + const ExtensionRepository &requested, OnCreateConflict on_conflict) { - CheckCanCreate(db); + // no prefix: the name is the host, and the host names the prefix. The host is derived here, never taken from the + // caller, so a stored host always means the repository was resolved from it + bool from_host = requested.path.empty(); + CheckCanCreate(db, from_host); - auto name = NormalizeRepositoryName(repository.name); + auto name = NormalizeRepositoryName(requested.name); if (!ExtensionRepository::TryGetRepositoryUrl(name).empty()) { throw InvalidInputException("Cannot create extension repository '%s': this is a built-in repository name", name); } - if (repository.path.empty()) { - throw InvalidInputException("Cannot create extension repository '%s': the prefix cannot be empty", name); + if (from_host && !requested.public_keys.empty()) { + // the keys of a repository resolved from its host come from the repository the host names: a key the caller + // supplies would be trusted for whatever the host points at, with nothing vouching for it + throw InvalidInputException( + "Cannot create extension repository '%s': a repository resolved from its host takes " + "its signing keys from the repository the host names; USING PUBLIC KEY goes with " + "WITH PREFIX", + name); } + + // the conflict is decided before anything is fetched: IF NOT EXISTS returns the stored definition, a plain CREATE + // reports the duplicate, and only OR REPLACE goes on to resolve - keeping the old definition if that fails auto directory = GetRepositoryDirectory(db, fs); auto file_path = fs.JoinPath(directory, name + FILE_EXTENSION); if (fs.FileExists(file_path)) { @@ -402,14 +710,29 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc } } - // if no key was provided, the repository is expected to serve it at its prefix. The keys are pinned here: they are - // stored alongside the repository and never fetched again - auto public_keys = repository.public_keys.empty() ? FetchPublicKeys(db, context, repository.path) - : NormalizePublicKeys(repository.public_keys); + ExtensionRepository repository(name, requested.path, requested.public_keys); + vector public_keys; + if (from_host) { + auto resolution = ResolveRepositoryFromHost(db, context, name); + repository.path = resolution.url; + repository.host = name; + // the keys come from the prefix the host named, fetched as strictly as the host's own file was + auto metadata_path = repository.path + "/" + string(METADATA_FILE); + public_keys = ParsePublicKeys(ReadAuthenticatedHTTPS(db, context, metadata_path, "repository's metadata file"), + metadata_path); + } else if (repository.public_keys.empty()) { + // no key was provided: the repository is expected to serve it at its prefix + public_keys = FetchPublicKeys(db, context, repository.path); + } else { + public_keys = NormalizePublicKeys(repository.public_keys); + } + // the keys are pinned here: they are stored alongside the repository and never fetched again if (public_keys.empty()) { throw InvalidInputException("Cannot create extension repository '%s': no public key was provided or served", name); } + // the fetches took time: the access may have been tightened meanwhile, so check again before persisting + CheckCanCreate(db, from_host); if (!fs.DirectoryExists(directory)) { fs.CreateDirectoriesRecursive(directory); @@ -421,6 +744,9 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc yyjson_mut_obj_add_uint(document.doc, root, "version", FORMAT_VERSION); yyjson_mut_obj_add_strcpy(document.doc, root, "name", name.c_str()); yyjson_mut_obj_add_strcpy(document.doc, root, "url", repository.path.c_str()); + if (!repository.host.empty()) { + yyjson_mut_obj_add_strcpy(document.doc, root, "host", repository.host.c_str()); + } auto keys_array = yyjson_mut_arr(document.doc); yyjson_mut_obj_add_val(document.doc, root, "public_keys", keys_array); for (auto &public_key : public_keys) { @@ -450,6 +776,7 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc ExtensionRepository result(name, repository.path, std::move(public_keys)); result.type = ExtensionRepositoryType::USER_PROVIDED; + result.host = repository.host; return result; } @@ -487,7 +814,7 @@ vector ExtensionRepositoryManager::GetRepositories(Database // sort the files to get a deterministic order std::sort(files.begin(), files.end()); for (auto &file_name : files) { - auto base_name = fs.ExtractBaseName(file_name); + auto base_name = RepositoryNameOfFile(file_name); // ignore files that are named after a built-in repository: those are always served by the built-in table string normalized; if (TryNormalizeRepositoryName(base_name, normalized) && diff --git a/src/duckdb/src/main/extension_manager.cpp b/src/duckdb/src/main/extension_manager.cpp index ee186a7fa..733ba657e 100644 --- a/src/duckdb/src/main/extension_manager.cpp +++ b/src/duckdb/src/main/extension_manager.cpp @@ -9,9 +9,10 @@ namespace duckdb { ExtensionInfo::ExtensionInfo() : is_loaded(false) { } -void ExtensionActiveLoad::FinishLoad(ExtensionInstallInfo &install_info) { +void ExtensionActiveLoad::FinishLoad(ExtensionInstallInfo &install_info, const string &file_path) { info.is_loaded = true; info.install_info = make_uniq(install_info); + info.file_path = file_path; string final_extension_name = extension_name.GetIdentifierName(); if (!alias.empty()) { diff --git a/src/duckdb/src/main/http/http_util.cpp b/src/duckdb/src/main/http/http_util.cpp index 7792c9041..5dce7a8d7 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -31,6 +31,13 @@ void HTTPParams::SetTransportReuseDomain(idx_t transport_reuse_domain_p) { transport_reuse_domain = transport_reuse_domain_p; } +void HTTPParams::RequireServerCertificateVerification() { + override_verify_ssl = true; + verify_ssl = true; + // the domain captured at initialization described the unforced parameters; a provider recaptures a cleared one + transport_reuse_domain = 0; +} + HTTPHeaders::HTTPHeaders(DatabaseInstance &db) { headers.insert({"User-Agent", StringUtil::Format("%s %s", db.config.UserAgent(), DuckDB::SourceID())}); } diff --git a/src/duckdb/src/main/parse_iterator.cpp b/src/duckdb/src/main/parse_iterator.cpp index 5056dd952..7a3f7d135 100644 --- a/src/duckdb/src/main/parse_iterator.cpp +++ b/src/duckdb/src/main/parse_iterator.cpp @@ -127,20 +127,15 @@ bool ParseIterator::PeekInternal() { return false; } auto stmt = parser.ParseTopLevelStatement(*token_iterator, sql); + // ParseTopLevelStatement doesn't populate stmt->query (it operates on tokens, not the + // source string). Mirror Parser::ParseQuery's slicing: a statement's text starts where the + // previous one ended and runs through its own terminators, so comments before a statement + // belong to it; the last statement runs to the end of the input. + idx_t stmt_start = next_statement_offset; + idx_t stmt_end = token_iterator->AtEnd() ? sql.size() : token_iterator->ConsumedEndOffset(); + next_statement_offset = stmt_end; if (stmt) { - // ParseTopLevelStatement doesn't populate stmt->query (it operates on tokens, not the - // source string). Mirror Parser::ParseQuery's per-statement post-processing: extend from - // the statement's start to the next statement's start (or end of input) so the trailing - // `;` and inter-statement whitespace end up inside stmt->query — downstream consumers - // (logging, error reporting, EXPLAIN) rely on that shape. - idx_t stmt_loc = stmt->stmt_location.offset; - idx_t end_loc = sql.size(); - if (auto current = token_iterator->Current()) { - if (current->type != TokenType::END_OF_INPUT) { - end_loc = current->offset; - } - } - stmt->query = sql.substr(stmt_loc, end_loc - stmt_loc); + stmt->query = sql.substr(stmt_start, stmt_end - stmt_start); stmt->stmt_location = QueryLocation(0, stmt->query.size()); if (stmt->type == StatementType::CREATE_STATEMENT) { auto &create = stmt->Cast(); @@ -161,12 +156,11 @@ void ParseIterator::EnsureTokenized() { if (!token_iterator) { // Tokenize the full input once. Subsequent Peek/HasMore calls walk through the iterator; // we never re-tokenize. Tokenization is grammar-free. - auto owned_tokens = make_uniq>(); - ParserTokenizerBehavior behavior(sql, *owned_tokens); + ParserTokenizerBehavior behavior(sql); auto compiled_grammar = CompiledGrammar::Get(context); auto &tokenizer = compiled_grammar->GetTokenizer(); tokenizer.TokenizeInput(behavior); - token_iterator = make_uniq(std::move(owned_tokens)); + token_iterator = make_uniq(behavior); } } diff --git a/src/duckdb/src/main/query_profiler.cpp b/src/duckdb/src/main/query_profiler.cpp index b31b9c537..99a863bb7 100644 --- a/src/duckdb/src/main/query_profiler.cpp +++ b/src/duckdb/src/main/query_profiler.cpp @@ -112,7 +112,7 @@ bool QueryProfiler::PrintOptimizerOutput() const { } string QueryProfiler::GetSaveLocation() const { - return is_explain_analyze ? string() : ClientConfig::GetConfig(context).profiler_save_location; + return is_explain_analyze ? string() : Settings::Get(context); } QueryProfiler &QueryProfiler::Get(ClientContext &context) { @@ -182,8 +182,7 @@ void QueryProfiler::AddParserTime(const Profiler &parser_timer, timestamp_t star } bool QueryProfiler::OperatorRequiresProfiling(const PhysicalOperatorType op_type) { - const auto &config = ClientConfig::GetConfig(context); - if (config.profiling_coverage == ProfilingCoverage::ALL) { + if (Settings::Get(context) == ProfilingCoverage::ALL) { return true; } @@ -1164,7 +1163,7 @@ void QueryProfiler::Initialize(const PhysicalOperator &root_op) { void QueryProfiler::Render(const ProfilingNode &node, BaseTreeRenderer &ss) const { TextTreeRenderer renderer; - renderer.Configure(ClientConfig::GetConfig(context).profiling_renderer_settings); + renderer.Configure(TreeRenderer::GetRendererSettings(context)); renderer.Render(node, ss); } diff --git a/src/duckdb/src/main/query_result.cpp b/src/duckdb/src/main/query_result.cpp index 9f06322cc..411dcd4e0 100644 --- a/src/duckdb/src/main/query_result.cpp +++ b/src/duckdb/src/main/query_result.cpp @@ -191,7 +191,11 @@ QueryResult::QueryResult(ErrorData error) } QueryResult::~QueryResult() { - Close(); + try { + Close(); + } catch (...) { + // a destructor cannot throw, and locking the context allocates + } } void QueryResult::DeduplicateColumns(vector &names) { @@ -510,9 +514,9 @@ void QueryResult::HandleFetchFailure(ClientContextLock &lock, ErrorData error) { // standard exceptions do not invalidate the current transaction invalidate_query = false; } else if (Exception::InvalidatesDatabase(error.Type())) { - // fatal exceptions invalidate the entire database + // fatal exceptions invalidate the database instance, unless scoped to an attached database auto &db_instance = DatabaseInstance::GetDatabase(*context); - ValidChecker::Invalidate(db_instance, error.RawMessage()); + ValidChecker::Invalidate(db_instance, error); } context->ProcessError(error, context->GetCurrentQuery()); SetError(std::move(error)); diff --git a/src/duckdb/src/main/secret/default_secrets.cpp b/src/duckdb/src/main/secret/default_secrets.cpp index 4fa756253..637391c84 100644 --- a/src/duckdb/src/main/secret/default_secrets.cpp +++ b/src/duckdb/src/main/secret/default_secrets.cpp @@ -1,4 +1,8 @@ #include "duckdb/main/secret/default_secrets.hpp" + +#include "duckdb/common/string_util.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/os_util.hpp" #include "duckdb/main/secret/secret_manager.hpp" namespace duckdb { @@ -58,30 +62,22 @@ vector CreateHTTPSecretFunctions::GetDefaultSecretFunction return result; } -static const char *TryGetEnv(const char *name) { - const char *res = std::getenv(name); - if (res) { - return res; +//! Reads a proxy setting from the process environment into the secret, trying the lowercase name before the uppercase +static void TrySetValueFromEnv(OSUtil &os_util, KeyValueSecret &secret, const string &name) { + string value; + if (os_util.GetEnv(name, value) || os_util.GetEnv(StringUtil::Upper(name), value)) { + secret.secret_map[Identifier(name)] = Value(value); } - return std::getenv(StringUtil::Upper(name).c_str()); } unique_ptr CreateHTTPSecretFunctions::CreateHTTPSecretFromEnv(ClientContext &context, CreateSecretInput &input) { auto secret = make_uniq(input.scope, input.type, input.provider, input.name); - auto http_proxy = TryGetEnv("http_proxy"); - if (http_proxy) { - secret->secret_map["http_proxy"] = Value(http_proxy); - } - auto http_proxy_password = TryGetEnv("http_proxy_password"); - if (http_proxy_password) { - secret->secret_map["http_proxy_password"] = Value(http_proxy_password); - } - auto http_proxy_username = TryGetEnv("http_proxy_username"); - if (http_proxy_username) { - secret->secret_map["http_proxy_username"] = Value(http_proxy_username); - } + auto &os_util = OSUtil::Get(*context.db); + TrySetValueFromEnv(os_util, *secret, "http_proxy"); + TrySetValueFromEnv(os_util, *secret, "http_proxy_password"); + TrySetValueFromEnv(os_util, *secret, "http_proxy_username"); // Allow overwrites secret->TrySetValue("verify_ssl", input); diff --git a/src/duckdb/src/main/secret/secret.cpp b/src/duckdb/src/main/secret/secret.cpp index ebb5ab10d..a38364347 100644 --- a/src/duckdb/src/main/secret/secret.cpp +++ b/src/duckdb/src/main/secret/secret.cpp @@ -25,9 +25,19 @@ int64_t BaseSecret::MatchScore(const string &path) const { longest_match = 0; continue; } - if (StringUtil::StartsWith(path, prefix)) { - longest_match = MaxValue(NumericCast(prefix.length()), longest_match); + if (!StringUtil::StartsWith(path, prefix)) { + continue; + } + // Authority-only URI scopes have an implicit trailing slash. + auto authority = StringUtil::GetURIAuthority(prefix); + bool authority_only = !authority.empty() && prefix.size() == prefix.find("://") + 3 + authority.size(); + if (authority_only) { + bool at_authority_boundary = path.size() == prefix.size() || path[prefix.size()] == '/'; + if (!at_authority_boundary) { + continue; + } } + longest_match = MaxValue(NumericCast(prefix.length()), longest_match); } return longest_match; } diff --git a/src/duckdb/src/main/secret/secret_manager.cpp b/src/duckdb/src/main/secret/secret_manager.cpp index 4e5140930..1b9416cf0 100644 --- a/src/duckdb/src/main/secret/secret_manager.cpp +++ b/src/duckdb/src/main/secret/secret_manager.cpp @@ -17,6 +17,7 @@ #include "duckdb/main/extension_helper.hpp" #include "duckdb/main/secret/secret_storage.hpp" #include "duckdb/main/secret/default_secrets.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/parser/parsed_data/create_secret_info.hpp" #include "duckdb/parser/statement/create_statement.hpp" #include "duckdb/planner/operator/logical_create_secret.hpp" @@ -255,9 +256,24 @@ optional_ptr SecretManager::LookupFunctionInternal(const I return nullptr; } +//! Secret providers read environment variables, files and credential endpoints: none of that without external access +void SecretManager::ThrowIfSecretCreationDisabled(DatabaseInstance &db, const Identifier &type, + const Identifier &provider) { + if (Settings::Get(db)) { + return; + } + string what = "Creating secrets is disabled when enable_external_access is false"; + if (type.empty()) { + throw PermissionException(what); + } + string provider_string = provider.empty() ? "" : StringUtil::Format(", provider %s", provider); + throw PermissionException("%s (secret type %s%s)", what, type, provider_string); +} + unique_ptr SecretManager::CreateSecret(ClientContext &context, const CreateSecretInput &input) { // Note that a context is required for CreateSecret, as the CreateSecretFunction expects one auto transaction = CatalogTransaction::GetSystemCatalogTransaction(context); + ThrowIfSecretCreationDisabled(transaction.db, input.type, input.provider); InitializeSecrets(transaction); // Make a copy to set the provider to default if necessary @@ -288,6 +304,7 @@ unique_ptr SecretManager::CreateSecret(ClientContext &context, cons BoundStatement SecretManager::BindCreateSecret(Context &context, CatalogTransaction transaction, CreateSecretInput &info) { + ThrowIfSecretCreationDisabled(transaction.db, info.type, info.provider); if (info.persist_type == SecretPersistType::TRANSACTION || info.storage_type == TRANSACTION_STORAGE_NAME) { throw BinderException("Transaction-scoped secrets cannot be created through SQL"); } diff --git a/src/duckdb/src/main/settings/autogenerated_settings.cpp b/src/duckdb/src/main/settings/autogenerated_settings.cpp index e44dca611..8457da4a7 100644 --- a/src/duckdb/src/main/settings/autogenerated_settings.cpp +++ b/src/duckdb/src/main/settings/autogenerated_settings.cpp @@ -64,37 +64,6 @@ void CheckpointOnDetachSetting::OnSet(SettingCallbackInfo &info, Value ¶mete EnumUtil::FromString(StringValue::Get(parameter)); } -//===----------------------------------------------------------------------===// -// Checkpoint Threshold -//===----------------------------------------------------------------------===// -void CheckpointThresholdSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.checkpoint_wal_size = DBConfigOptions().checkpoint_wal_size; -} - -//===----------------------------------------------------------------------===// -// Custom User Agent -//===----------------------------------------------------------------------===// -Value CustomUserAgentSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(config.options.custom_user_agent); -} - -//===----------------------------------------------------------------------===// -// Debug Abort On Wal Failure -//===----------------------------------------------------------------------===// -void DebugAbortOnWalFailureSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - config.options.abort_on_wal_failure = input.GetValue(); -} - -void DebugAbortOnWalFailureSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.abort_on_wal_failure = DBConfigOptions().abort_on_wal_failure; -} - -Value DebugAbortOnWalFailureSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value::BOOLEAN(config.options.abort_on_wal_failure); -} - //===----------------------------------------------------------------------===// // Debug Checkpoint Abort //===----------------------------------------------------------------------===// @@ -116,20 +85,23 @@ void ForceBitpackingModeSetting::OnSet(SettingCallbackInfo &info, Value ¶met } //===----------------------------------------------------------------------===// -// Debug Order Verification +// Debug Initialize //===----------------------------------------------------------------------===// -void DebugOrderVerificationSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - auto str_input = StringUtil::Upper(input.GetValue()); - config.options.debug_order_verification = EnumUtil::FromString(str_input); -} - -void DebugOrderVerificationSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.debug_order_verification = DBConfigOptions().debug_order_verification; +void DebugInitializeSetting::OnSet(SettingCallbackInfo &info, Value ¶meter) { + if (parameter.IsNull()) { + throw InvalidInputException("debug_initialize setting cannot be NULL"); + } + EnumUtil::FromString(StringValue::Get(parameter)); } -Value DebugOrderVerificationSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(StringUtil::Lower(EnumUtil::ToString(config.options.debug_order_verification))); +//===----------------------------------------------------------------------===// +// Debug Order Verification +//===----------------------------------------------------------------------===// +void DebugOrderVerificationSetting::OnSet(SettingCallbackInfo &info, Value ¶meter) { + if (parameter.IsNull()) { + throw InvalidInputException("debug_order_verification setting cannot be NULL"); + } + EnumUtil::FromString(StringValue::Get(parameter)); } //===----------------------------------------------------------------------===// @@ -202,29 +174,6 @@ void DialectCompatibilityModeSetting::OnSet(SettingCallbackInfo &info, Value &pa EnumUtil::FromString(StringValue::Get(parameter)); } -//===----------------------------------------------------------------------===// -// Enable Progress Bar -//===----------------------------------------------------------------------===// -void EnableProgressBarSetting::SetLocal(ClientContext &context, const Value &input) { - if (!OnLocalSet(context, input)) { - return; - } - auto &config = ClientConfig::GetConfig(context); - config.enable_progress_bar = input.GetValue(); -} - -void EnableProgressBarSetting::ResetLocal(ClientContext &context) { - if (!OnLocalReset(context)) { - return; - } - ClientConfig::GetConfig(context).enable_progress_bar = ClientConfig().enable_progress_bar; -} - -Value EnableProgressBarSetting::GetSetting(const ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - return Value::BOOLEAN(config.enable_progress_bar); -} - //===----------------------------------------------------------------------===// // Explain Output //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index 90e998c57..85d60f2ff 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -58,6 +58,7 @@ namespace duckdb { constexpr const char *LoggingMode::Name; constexpr const char *LoggingLevel::Name; constexpr const char *EnableLogging::Name; +constexpr const char *LoggingSink::Name; constexpr const char *LoggingStorage::Name; constexpr const char *EnabledLogTypes::Name; constexpr const char *DisabledLogTypes::Name; @@ -127,46 +128,24 @@ void AllocatorBackgroundThreadsSetting::OnSet(SettingCallbackInfo &info, Value & //===----------------------------------------------------------------------===// // Allocator Bulk Deallocation Flush Threshold //===----------------------------------------------------------------------===// -void AllocatorBulkDeallocationFlushThresholdSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, - const Value &input) { - config.options.allocator_bulk_deallocation_flush_threshold = DBConfig::ParseMemoryLimitOrMaximum(input.ToString()); - if (db) { - BufferManager::GetBufferManager(*db).GetBufferPool().SetAllocatorBulkDeallocationFlushThreshold( - config.options.allocator_bulk_deallocation_flush_threshold); +void AllocatorBulkDeallocationFlushThresholdSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", AllocatorBulkDeallocationFlushThresholdSetting::Name); } -} - -void AllocatorBulkDeallocationFlushThresholdSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.allocator_bulk_deallocation_flush_threshold = - DBConfigOptions().allocator_bulk_deallocation_flush_threshold; - if (db) { - BufferManager::GetBufferManager(*db).GetBufferPool().SetAllocatorBulkDeallocationFlushThreshold( - config.options.allocator_bulk_deallocation_flush_threshold); + auto threshold = DBConfig::ParseMemoryLimitOrMaximum(input.ToString()); + input = Value(StringUtil::BytesToHumanReadableString(threshold)); + if (info.db) { + BufferManager::GetBufferManager(*info.db).GetBufferPool().SetAllocatorBulkDeallocationFlushThreshold(threshold); } } -Value AllocatorBulkDeallocationFlushThresholdSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(StringUtil::BytesToHumanReadableString(config.options.allocator_bulk_deallocation_flush_threshold)); -} - //===----------------------------------------------------------------------===// // Delta Only Variant Legacy Encoding //===----------------------------------------------------------------------===// -void DebugDeltaOnlyVariantEncodingEnabledSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, - const Value &input) { - throw InvalidInputException("This setting is not adjustable by a user"); -} - -void DebugDeltaOnlyVariantEncodingEnabledSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { +void DebugDeltaOnlyVariantEncodingEnabledSetting::OnSet(SettingCallbackInfo &info, Value &input) { throw InvalidInputException("This setting is not adjustable by a user"); } -Value DebugDeltaOnlyVariantEncodingEnabledSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value::BOOLEAN(config.options.variant_legacy_encoding); -} - //===----------------------------------------------------------------------===// // Allocator Flush Threshold //===----------------------------------------------------------------------===// @@ -190,12 +169,14 @@ void AllowCommunityExtensionsSetting::OnSet(SettingCallbackInfo &info, Value &in // Allow Extension Repositories //===----------------------------------------------------------------------===// // Ordering of the access levels, independent of the enum's numeric values: while the database is running the setting -// can only move to a lower level ('undecided' -> 'allowed' -> 'forbidden') +// can only move to a lower level ('hosts' -> 'allowed' -> 'hosts_only' -> 'forbidden') static int ExtensionRepositoryAccessLevel(ExtensionRepositoryAccess access) { switch (access) { - case ExtensionRepositoryAccess::UNDECIDED: - return 2; + case ExtensionRepositoryAccess::HOSTS: + return 3; case ExtensionRepositoryAccess::ALLOWED: + return 2; + case ExtensionRepositoryAccess::HOSTS_ONLY: return 1; default: // FORBIDDEN return 0; @@ -212,13 +193,13 @@ void AllowExtensionRepositoriesSetting::OnSet(SettingCallbackInfo &info, Value & // the value is set before the database is running (startup) - any value is allowed return; } - // while the database is running the setting can only move down: the 'undecided' default can be decided either way, - // 'allowed' can still be forbidden, but a decision cannot be reverted. This makes 'forbidden' a one-way ratchet - // within a session + // while the database is running the setting can only move down: the 'hosts' default can be opened up to 'allowed' + // or tightened, 'allowed' can still be tightened, but no step can be reverted. This makes 'forbidden' a one-way + // ratchet within a session auto current_access = ExtensionRepositoryManager::GetAccess(*info.db); if (ExtensionRepositoryAccessLevel(new_access) > ExtensionRepositoryAccessLevel(current_access)) { - throw InvalidInputException("allow_extension_repositories can only be changed from 'undecided' to 'allowed' or " - "'forbidden', or from 'allowed' to 'forbidden', while the database is running"); + throw InvalidInputException("allow_extension_repositories can only be tightened while the database is running: " + "'hosts' -> 'allowed' -> 'hosts_only' -> 'forbidden'"); } } @@ -392,51 +373,65 @@ Value AllowedPathsSetting::GetSetting(const ClientContext &context) { } //===----------------------------------------------------------------------===// -// Checkpoint Threshold +// Buffer Manager Track Eviction Timestamps //===----------------------------------------------------------------------===// -void CheckpointThresholdSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - idx_t new_limit = DBConfig::ParseMemoryLimitOrMaximum(input.ToString()); - config.options.checkpoint_wal_size = new_limit; +void BufferManagerTrackEvictionTimestampsSetting::OnSet(SettingCallbackInfo &info, Value &input) { + // the buffer pool reads the setting once, when the database starts + if (info.db) { + throw InvalidInputException("Cannot change %s setting while database is running", + BufferManagerTrackEvictionTimestampsSetting::Name); + } } -Value CheckpointThresholdSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(StringUtil::BytesToHumanReadableString(config.options.checkpoint_wal_size)); +//===----------------------------------------------------------------------===// +// Checkpoint Threshold +//===----------------------------------------------------------------------===// +void CheckpointThresholdSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", CheckpointThresholdSetting::Name); + } + auto threshold = DBConfig::ParseMemoryLimitOrMaximum(input.ToString()); + info.config.options.checkpoint_wal_size = threshold; + input = Value(StringUtil::BytesToHumanReadableString(threshold)); } //===----------------------------------------------------------------------===// // Custom User Agent //===----------------------------------------------------------------------===// -void CustomUserAgentSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - auto new_value = input.GetValue(); - if (db) { - throw InvalidInputException("Cannot change custom_user_agent setting while database is running"); +void CustomUserAgentSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", CustomUserAgentSetting::Name); } - config.options.custom_user_agent = - config.options.custom_user_agent.empty() ? new_value : config.options.custom_user_agent + " " + new_value; -} - -void CustomUserAgentSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - if (db) { + if (info.db) { throw InvalidInputException("Cannot change custom_user_agent setting while database is running"); } - config.options.custom_user_agent = DBConfigOptions().custom_user_agent; + auto existing = Settings::Get(info.config); + if (!info.is_reset && !existing.empty()) { + input = Value(existing + " " + StringValue::Get(input)); + } } //===----------------------------------------------------------------------===// // Debug Verification Mode //===----------------------------------------------------------------------===// -void DebugVerificationModeSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - config.options.global_verification_mode = EnumUtil::FromString(input.ToString()); -} - -void DebugVerificationModeSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.global_verification_mode = DebugVerificationMode::NONE; +void DebugVerificationModeSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", DebugVerificationModeSetting::Name); + } + auto mode = EnumUtil::FromString(StringValue::Get(input)); + input = Value(EnumUtil::ToString(mode)); + DBConfigOptions::global_verification_mode = mode; } -Value DebugVerificationModeSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return EnumUtil::ToString(config.options.global_verification_mode); +//===----------------------------------------------------------------------===// +// Profiling Coverage +//===----------------------------------------------------------------------===// +void ProfilingCoverageSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", ProfilingCoverageSetting::Name); + } + auto coverage = EnumUtil::FromString(StringValue::Get(input)); + input = Value(EnumUtil::ToString(coverage)); } //===----------------------------------------------------------------------===// @@ -605,10 +600,12 @@ Value DefaultSecretStorageSetting::GetSetting(const ClientContext &context) { //===----------------------------------------------------------------------===// // Disabled Compression Methods //===----------------------------------------------------------------------===// -void DisabledCompressionMethodsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - auto list = StringUtil::Split(input.ToString(), ","); +void DisabledCompressionMethodsSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", DisabledCompressionMethodsSetting::Name); + } vector disabled_compression_methods; - for (auto &entry : list) { + for (auto &entry : StringUtil::Split(input.ToString(), ",")) { auto param = StringUtil::Lower(entry); StringUtil::Trim(param); if (param.empty()) { @@ -631,24 +628,15 @@ void DisabledCompressionMethodsSetting::SetGlobal(DatabaseInstance *db, DBConfig } disabled_compression_methods.push_back(compression_type); } - config.SetDisabledCompressionMethods(disabled_compression_methods); -} - -void DisabledCompressionMethodsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - vector disabled_compression_methods; - config.SetDisabledCompressionMethods(disabled_compression_methods); -} - -Value DisabledCompressionMethodsSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - string result; - for (auto &optimizer : config.GetDisabledCompressionMethods()) { - if (!result.empty()) { - result += ","; + info.config.SetDisabledCompressionMethods(disabled_compression_methods); + string normalized; + for (auto &method : info.config.GetDisabledCompressionMethods()) { + if (!normalized.empty()) { + normalized += ","; } - result += CompressionTypeToString(optimizer); + normalized += CompressionTypeToString(method); } - return Value(result); + input = Value(normalized); } //===----------------------------------------------------------------------===// @@ -678,10 +666,12 @@ Value DisabledFilesystemsSetting::GetSetting(const ClientContext &context) { //===----------------------------------------------------------------------===// // Disabled Optimizers //===----------------------------------------------------------------------===// -void DisabledOptimizersSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - auto list = StringUtil::Split(input.ToString(), ","); +void DisabledOptimizersSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", DisabledOptimizersSetting::Name); + } set disabled_optimizers; - for (auto &entry : list) { + for (auto &entry : StringUtil::Split(input.ToString(), ",")) { auto param = StringUtil::Lower(entry); StringUtil::Trim(param); if (param.empty()) { @@ -689,23 +679,15 @@ void DisabledOptimizersSetting::SetGlobal(DatabaseInstance *db, DBConfig &config } disabled_optimizers.insert(OptimizerTypeFromString(param)); } - config.SetDisabledOptimizers(std::move(disabled_optimizers)); -} - -void DisabledOptimizersSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.SetDisabledOptimizers(DBConfigOptions().disabled_optimizers); -} - -Value DisabledOptimizersSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - string result; - for (auto &optimizer : config.GetDisabledOptimizers()) { - if (!result.empty()) { - result += ","; + string normalized; + for (auto &optimizer : disabled_optimizers) { + if (!normalized.empty()) { + normalized += ","; } - result += OptimizerTypeToString(optimizer); + normalized += OptimizerTypeToString(optimizer); } - return Value(result); + input = Value(normalized); + info.config.SetDisabledOptimizers(std::move(disabled_optimizers)); } //===----------------------------------------------------------------------===// @@ -850,18 +832,14 @@ void EnableLogging::ResetGlobal(DatabaseInstance *db_p, DBConfig &config) { // Force VARIANT Shredding //===----------------------------------------------------------------------===// -void ForceVariantShredding::SetGlobal(DatabaseInstance *_, DBConfig &config, const Value &value) { - auto &force_variant_shredding = config.options.force_variant_shredding; - - if (value.type().id() != LogicalTypeId::VARCHAR) { - throw InvalidInputException("The argument to 'force_variant_shredding' should be of type VARCHAR, not %s", - value.type().ToString()); +static LogicalType ParseForceVariantShredding(const string &input, bool allow_unset = true) { + if (allow_unset && StringUtil::CIEquals(input, ForceVariantShredding::DefaultValue)) { + return LogicalType::INVALID; } - - auto logical_type = UnboundType::TryParseAndDefaultBind(value.GetValue()); + auto logical_type = UnboundType::TryParseAndDefaultBind(input); if (logical_type.id() == LogicalTypeId::INVALID) { throw InvalidInputException("Could not parse the argument '%s' to 'force_variant_shredding' as a built in type", - value.GetValue()); + input); } TypeVisitor::Contains(logical_type, [](const LogicalType &type) { @@ -913,45 +891,41 @@ void ForceVariantShredding::SetGlobal(DatabaseInstance *_, DBConfig &config, con }); auto shredding_type = VariantStats::GetShreddingType(logical_type); - force_variant_shredding = - LogicalType::STRUCT({{"unshredded", VariantShredding::GetUnshreddedType()}, {"shredded", shredding_type}}); + return LogicalType::STRUCT({{"unshredded", VariantShredding::GetUnshreddedType()}, {"shredded", shredding_type}}); } -void ForceVariantShredding::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.force_variant_shredding = LogicalType::INVALID; +void ForceVariantShredding::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", ForceVariantShredding::Name); + } + if (input.type().id() != LogicalTypeId::VARCHAR) { + throw InvalidInputException("The argument to 'force_variant_shredding' should be of type VARCHAR, not %s", + input.type().ToString()); + } + input = Value(ParseForceVariantShredding(StringValue::Get(input), info.is_reset).ToString()); } -Value ForceVariantShredding::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(config.GetForceVariantShredding().ToString()); +LogicalType DBConfig::GetForceVariantShredding() const { + // the setting stores the expanded shredding type + auto shredding = Settings::Get(*this); + if (StringUtil::CIEquals(shredding, ForceVariantShredding::DefaultValue)) { + return LogicalType::INVALID; + } + return UnboundType::TryParseAndDefaultBind(shredding); } //===----------------------------------------------------------------------===// // Extension Directory //===----------------------------------------------------------------------===// -void ExtensionDirectoriesSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { +void ExtensionDirectoriesSetting::OnSet(SettingCallbackInfo &info, Value &input) { if (input.IsNull()) { throw InvalidInputException("%s setting cannot be NULL", ExtensionDirectoriesSetting::Name); } - config.options.extension_directories.clear(); - - auto &list = ListValue::GetChildren(input); - for (auto &val : list) { - config.options.extension_directories.emplace_back(val.GetValue()); - } -} - -void ExtensionDirectoriesSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.extension_directories = DBConfigOptions().extension_directories; -} - -Value ExtensionDirectoriesSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - vector extension_directories; - for (auto &dir : config.options.extension_directories) { - extension_directories.emplace_back(dir); + for (auto &directory : ListValue::GetChildren(input)) { + if (directory.IsNull()) { + throw InvalidInputException("%s setting elements cannot be NULL", ExtensionDirectoriesSetting::Name); + } } - return Value::LIST(LogicalType::VARCHAR, std::move(extension_directories)); } //===----------------------------------------------------------------------===// @@ -987,19 +961,36 @@ void LoggingLevel::ResetGlobal(DatabaseInstance *db_p, DBConfig &config) { } //===----------------------------------------------------------------------===// -// Logging Storage +// Logging Sink //===----------------------------------------------------------------------===// -Value LoggingStorage::GetSetting(const ClientContext &context) { +Value LoggingSink::GetSetting(const ClientContext &context) { return context.db->GetLogManager().GetConfig().storage; } +void LoggingSink::SetGlobal(DatabaseInstance *db_p, DBConfig &config, const Value ¶meter) { + auto &db = GetDB(db_p); + db.GetLogManager().SetLogSink(db, parameter.GetValue()); +} + +void LoggingSink::ResetGlobal(DatabaseInstance *db_p, DBConfig &config) { + auto &db = GetDB(db_p); + db.GetLogManager().SetLogSink(db, LogConfig::DEFAULT_LOG_STORAGE); +} + +//===----------------------------------------------------------------------===// +// Logging Storage (deprecated, use logging_sink) +//===----------------------------------------------------------------------===// +Value LoggingStorage::GetSetting(const ClientContext &context) { + return LoggingSink::GetSetting(context); +} + void LoggingStorage::SetGlobal(DatabaseInstance *db_p, DBConfig &config, const Value ¶meter) { auto &db = GetDB(db_p); - db.GetLogManager().SetLogStorage(db, parameter.GetValue()); + DUCKDB_LOG_WARNING(db, "the logging_storage setting is deprecated: use logging_sink instead"); + LoggingSink::SetGlobal(db_p, config, parameter); } void LoggingStorage::ResetGlobal(DatabaseInstance *db_p, DBConfig &config) { - auto &db = GetDB(db_p); - db.GetLogManager().SetLogStorage(db, LogConfig::DEFAULT_LOG_STORAGE); + LoggingSink::ResetGlobal(db_p, config); } //===----------------------------------------------------------------------===// @@ -1068,14 +1059,15 @@ void EnableProfilingSetting::SetLocal(ClientContext &context, const Value &input config.enable_profiler = true; - if (parameter != "no_output" && !config.profiler_save_location.empty()) { + auto save_location = Settings::Get(context); + if (parameter != "no_output" && !save_location.empty()) { auto &file_system = FileSystem::GetFileSystem(context); - const auto file_type = file_system.ExtractExtension(config.profiler_save_location); + const auto file_type = file_system.ExtractExtension(save_location); if (file_type != parameter && file_type != "txt") { throw ParserException( "Profiler file type (%s) must either have the same file extension as the profiling output type (%s), " "or be a '.txt' file. Set 'profiling_output' to a '%s' file or run \"RESET profiling_output\" first.", - config.profiler_save_location, parameter, parameter); + save_location, parameter, parameter); } } @@ -1096,50 +1088,34 @@ Value EnableProfilingSetting::GetSetting(const ClientContext &context) { return Value(config.profiler_print_format); } +//! The progress bar settings are per connection: setting them without a client context (e.g. on a DBConfig) fails +static ClientContext &GetProgressBarSettingContext(SettingCallbackInfo &info, const char *setting_name) { + if (!info.context) { + throw InvalidInputException("Could not set option \"%s\" as a global option", setting_name); + } + return *info.context; +} + //===----------------------------------------------------------------------===// // Enable Progress Bar Print //===----------------------------------------------------------------------===// -void EnableProgressBarPrintSetting::SetLocal(ClientContext &context, const Value &input) { +void EnableProgressBarPrintSetting::OnSet(SettingCallbackInfo &info, Value &input) { + auto &context = GetProgressBarSettingContext(info, EnableProgressBarPrintSetting::Name); if (input.IsNull()) { throw InvalidInputException("enable_progress_bar_print setting cannot be NULL"); } - if (input.type().id() != LogicalTypeId::BOOLEAN) { - throw InvalidInputException("enable_progress_bar_print setting must be a boolean value"); - } - auto &config = ClientConfig::GetConfig(context); - ProgressBar::SystemOverrideCheck(config); - config.print_progress_bar = input.GetValue(); -} - -void EnableProgressBarPrintSetting::ResetLocal(ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - ProgressBar::SystemOverrideCheck(config); - config.print_progress_bar = ClientConfig().print_progress_bar; -} - -Value EnableProgressBarPrintSetting::GetSetting(const ClientContext &context) { - return Value::BOOLEAN(ClientConfig::GetConfig(context).print_progress_bar); + ProgressBar::SystemOverrideCheck(ClientConfig::GetConfig(context)); } //===----------------------------------------------------------------------===// // Enable Progress Bar //===----------------------------------------------------------------------===// -bool EnableProgressBarSetting::OnLocalSet(ClientContext &context, const Value &input) { +void EnableProgressBarSetting::OnSet(SettingCallbackInfo &info, Value &input) { + auto &context = GetProgressBarSettingContext(info, EnableProgressBarSetting::Name); if (input.IsNull()) { throw InvalidInputException("enable_progress_bar setting cannot be NULL"); } - if (input.type().id() != LogicalTypeId::BOOLEAN) { - throw InvalidInputException("enable_progress_bar setting must be a boolean value"); - } - auto &config = ClientConfig::GetConfig(context); - ProgressBar::SystemOverrideCheck(config); - return true; -} - -bool EnableProgressBarSetting::OnLocalReset(ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - ProgressBar::SystemOverrideCheck(config); - return true; + ProgressBar::SystemOverrideCheck(ClientConfig::GetConfig(context)); } //===----------------------------------------------------------------------===// @@ -1205,40 +1181,30 @@ void HomeDirectorySetting::OnSet(SettingCallbackInfo &info, Value &input) { // Enable Mbedtls //===----------------------------------------------------------------------===// -void ForceMbedtlsUnsafeSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - config.options.force_mbedtls = input.GetValue(); - +void ForceMbedtlsUnsafeSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", ForceMbedtlsUnsafeSetting::Name); + } // db is null when the option is set on a DBConfig before the database is opened (e.g. duckdb_set_config), // in which case nothing is attached yet - if (!config.options.force_mbedtls && db) { - // check if there are attached databases encrypted that are not read only - bool encrypted_db_attached = false; - for (auto &database : db->GetDatabaseManager().GetDatabases()) { - if (database->HasStorageManager() && database->GetStorageManager().IsEncrypted() && - !database->IsReadOnly()) { - encrypted_db_attached = true; - break; - }; - }; - - if (encrypted_db_attached) { - // autoload httpfs if any attached db uses encryption - if (!ExtensionHelper::TryAutoLoadExtension(*db, "httpfs")) { - throw InvalidConfigurationException("Failed to autoload HTTPFS. Cannot disable MbedTLS, HTTPFS " - "extension is required to write encrypted databases."); - }; + if (input.GetValue() || !info.db) { + return; + } + // check if there are attached databases encrypted that are not read only + bool encrypted_db_attached = false; + for (auto &database : info.db->GetDatabaseManager().GetDatabases()) { + if (database->HasStorageManager() && database->GetStorageManager().IsEncrypted() && !database->IsReadOnly()) { + encrypted_db_attached = true; + break; + } + } + if (encrypted_db_attached) { + // autoload httpfs if any attached db uses encryption + if (!ExtensionHelper::TryAutoLoadExtension(*info.db, "httpfs")) { + throw InvalidConfigurationException("Failed to autoload HTTPFS. Cannot disable MbedTLS, HTTPFS " + "extension is required to write encrypted databases."); } } -} - -void ForceMbedtlsUnsafeSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - // If encryption is initialized, httpfs will be attempted to autoload again - SetGlobal(db, config, false); -} - -Value ForceMbedtlsUnsafeSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value::BOOLEAN(config.options.force_mbedtls); } //===----------------------------------------------------------------------===// @@ -1462,46 +1428,41 @@ void PreserveIdentifierCaseSetting::OnSet(SettingCallbackInfo &, Value &input) { //===----------------------------------------------------------------------===// // Profile Output //===----------------------------------------------------------------------===// -void ProfilingOutputSetting::SetLocal(ClientContext &context, const Value &input) { - auto &config = ClientConfig::GetConfig(context); +void ProfilingOutputSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", ProfilingOutputSetting::Name); + } auto parameter = input.ToString(); - - if (!parameter.empty() && config.profiler_print_format != "no_output") { - auto &file_system = FileSystem::GetFileSystem(context); - const auto file_type = file_system.ExtractExtension(parameter); - if (file_type != "txt") { - try { - QueryProfiler::Get(context).CreateProfiler(file_type); - } catch (std::exception &e) { - throw ParserException("Invalid output file type: %s", file_type); - } - } - - const auto printer_format = config.profiler_print_format; - if (file_type != printer_format && file_type != "txt") { - throw ParserException("Profiler file type (%s) must either have the same file extension as the profiling " - "output type (%s), or be a '.txt' file. Set \"enable_profiling = \'%s\'\" first.", - parameter, printer_format, file_type); + if (!info.context || parameter.empty()) { + return; + } + auto &context = *info.context; + auto &config = ClientConfig::GetConfig(context); + if (config.profiler_print_format == "no_output") { + return; + } + auto &file_system = FileSystem::GetFileSystem(context); + const auto file_type = file_system.ExtractExtension(parameter); + if (file_type != "txt") { + try { + QueryProfiler::Get(context).CreateProfiler(file_type); + } catch (std::exception &e) { + throw ParserException("Invalid output file type: %s", file_type); } } - config.profiler_save_location = parameter; -} - -void ProfilingOutputSetting::ResetLocal(ClientContext &context) { - ClientConfig::GetConfig(context).profiler_save_location = ClientConfig().profiler_save_location; -} - -Value ProfilingOutputSetting::GetSetting(const ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - return Value(config.profiler_save_location); + const auto printer_format = config.profiler_print_format; + if (file_type != printer_format && file_type != "txt") { + throw ParserException("Profiler file type (%s) must either have the same file extension as the profiling " + "output type (%s), or be a '.txt' file. Set \"enable_profiling = \'%s\'\" first.", + parameter, printer_format, file_type); + } } //===----------------------------------------------------------------------===// // Profiler Renderer Settings //===----------------------------------------------------------------------===// -void ProfilingRendererSettingsSetting::SetLocal(ClientContext &context, const Value &input) { - auto &config = ClientConfig::GetConfig(context); +void ProfilingRendererSettingsSetting::OnSet(SettingCallbackInfo &info, Value &input) { if (input.IsNull() || input.type().id() != LogicalTypeId::MAP) { throw InvalidInputException("Invalid profiling_renderer_settings type \"%s\", expected a map of settings " "(e.g. {'maximum_render_width': 300})", @@ -1514,35 +1475,16 @@ void ProfilingRendererSettingsSetting::SetLocal(ClientContext &context, const Va throw InvalidInputException("profiling_renderer_settings: the value of \"%s\" cannot be NULL", key_value[0].ToString()); } - new_settings[StringUtil::Lower(key_value[0].ToString())] = key_value[1]; + 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 - auto renderer = QueryProfiler::Get(context).GetRenderer(); - if (renderer) { - renderer->Configure(new_settings); - } - config.profiling_renderer_settings = std::move(new_settings); -} - -void ProfilingRendererSettingsSetting::ResetLocal(ClientContext &context) { - ClientConfig::GetConfig(context).profiling_renderer_settings.clear(); -} - -Value ProfilingRendererSettingsSetting::GetSetting(const ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - // sort the settings by name so that the rendered value is deterministic - vector setting_names; - for (auto &entry : config.profiling_renderer_settings) { - setting_names.push_back(entry.first); - } - std::sort(setting_names.begin(), setting_names.end()); - vector keys; - vector values; - for (auto &name : setting_names) { - keys.emplace_back(name); - values.push_back(config.profiling_renderer_settings.at(name).DefaultCastAs(LogicalType::VARCHAR)); + if (info.context) { + auto renderer = QueryProfiler::Get(*info.context).GetRenderer(); + if (renderer) { + renderer->Configure(new_settings); + } } - return Value::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR, std::move(keys), std::move(values)); + input = TreeRenderer::RendererSettingsToValue(new_settings); } //===----------------------------------------------------------------------===// @@ -1576,51 +1518,23 @@ Value ProfilingModeSetting::GetSetting(const ClientContext &context) { return Value("standard"); } -//===----------------------------------------------------------------------===// -// Profiling Coverage Setting -//===----------------------------------------------------------------------===// -void ProfilingCoverageSetting::SetLocal(ClientContext &context, const Value &input) { - auto setting_type = EnumUtil::FromString(input.ToString()); - auto &config = ClientConfig::GetConfig(context); - config.profiling_coverage = setting_type; -} - -void ProfilingCoverageSetting::ResetLocal(ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - config.profiling_coverage = ProfilingCoverage::SELECT; -} - -Value ProfilingCoverageSetting::GetSetting(const ClientContext &context) { - const auto &config = ClientConfig::GetConfig(context); - return Value(EnumUtil::ToString(config.profiling_coverage)); -} - //===----------------------------------------------------------------------===// // Progress Bar Time //===----------------------------------------------------------------------===// -void ProgressBarTimeSetting::SetLocal(ClientContext &context, const Value &input) { +void ProgressBarTimeSetting::OnSet(SettingCallbackInfo &info, Value &input) { + auto &context = GetProgressBarSettingContext(info, ProgressBarTimeSetting::Name); + ProgressBar::SystemOverrideCheck(ClientConfig::GetConfig(context)); + if (info.is_reset) { + ClientConfig::GetConfig(context).user_settings.ClearSetting(EnableProgressBarSetting::SettingIndex); + return; + } if (input.IsNull()) { throw InvalidInputException("%s setting cannot be NULL", ProgressBarTimeSetting::Name); } - auto &config = ClientConfig::GetConfig(context); - ProgressBar::SystemOverrideCheck(config); - auto wait_time = input.GetValue(); - if (wait_time < 0) { + if (input.GetValue() < 0) { throw InvalidInputException("%s setting cannot be negative", ProgressBarTimeSetting::Name); } - config.wait_time = wait_time; - config.enable_progress_bar = true; -} - -void ProgressBarTimeSetting::ResetLocal(ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - ProgressBar::SystemOverrideCheck(config); - config.wait_time = ClientConfig().wait_time; - config.enable_progress_bar = ClientConfig().enable_progress_bar; -} - -Value ProgressBarTimeSetting::GetSetting(const ClientContext &context) { - return Value::BIGINT(ClientConfig::GetConfig(context).wait_time); + Settings::Set(context, SetScope::SESSION, Value::BOOLEAN(true)); } //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/main/valid_checker.cpp b/src/duckdb/src/main/valid_checker.cpp index 4a7ac5333..114ac5f1d 100644 --- a/src/duckdb/src/main/valid_checker.cpp +++ b/src/duckdb/src/main/valid_checker.cpp @@ -1,5 +1,7 @@ #include "duckdb/main/valid_checker.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/common/error_data.hpp" +#include "duckdb/common/exception.hpp" namespace duckdb { @@ -19,6 +21,23 @@ bool ValidChecker::IsInvalidated() { return !Settings::Get(db); } +void ValidChecker::InvalidateIfValid(string error) { + lock_guard l(invalidate_lock); + if (is_invalidated) { + return; + } + is_invalidated = true; + invalidated_msg = std::move(error); +} + +void ValidChecker::Invalidate(DatabaseInstance &db, const ErrorData &error) { + if (error.ExtraInfo().count(Exception::INVALIDATED_DATABASE_KEY)) { + // the attached database that raised the error has already been invalidated + return; + } + Get(db).Invalidate(error.RawMessage()); +} + string ValidChecker::InvalidatedMessage() { lock_guard l(invalidate_lock); return invalidated_msg; diff --git a/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp b/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp index 2112542b3..c7eabd99a 100644 --- a/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp +++ b/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp @@ -384,7 +384,7 @@ class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { unique_ptr VisitReplace(BoundColumnRefExpression &expr, unique_ptr *) override { const auto entry = aggregate_map.find(expr.Binding()); if (entry != aggregate_map.end()) { - expr.BindingMutable() = entry->second; + return expr.WithBinding(entry->second); } return nullptr; } diff --git a/src/duckdb/src/optimizer/aggregate_reuse.cpp b/src/duckdb/src/optimizer/aggregate_reuse.cpp index b50f6bffe..69339b3ed 100644 --- a/src/duckdb/src/optimizer/aggregate_reuse.cpp +++ b/src/duckdb/src/optimizer/aggregate_reuse.cpp @@ -541,7 +541,7 @@ unique_ptr AggregateReuseOptimizer::VisitReplace(BoundColumnRefExpre unique_ptr *expression_ptr) { auto entry = replacement_map.find(expression.Binding()); if (entry != replacement_map.end()) { - expression.BindingMutable() = entry->second; + return expression.WithBinding(entry->second); } return nullptr; } @@ -628,11 +628,10 @@ bool AggregateReuseOptimizer::TryReuseSemiAggregate(unique_ptr } auto state_ref = make_uniq(state_type, ColumnBinding(upper_aggregate_index, ProjectionIndex(0))); - auto finalized = optimizer.BindScalarFunction("finalize", std::move(state_ref)); + auto finalized = optimizer.BindScalarFunction("finalize", std::move(state_ref), outer_aggregate.GetAlias()); if (finalized->GetReturnType() != outer_aggregate.GetReturnType()) { throw InternalException("Aggregate return type changed while binding aggregate reuse finalization"); } - finalized->SetAlias(outer_aggregate.GetAlias()); expressions.push_back(std::move(finalized)); replacement_map[ColumnBinding(aggregate.aggregate_index, ProjectionIndex(0))] = ColumnBinding(projection_index, ProjectionIndex(aggregate.groups.size())); diff --git a/src/duckdb/src/optimizer/aggregate_rewrite.cpp b/src/duckdb/src/optimizer/aggregate_rewrite.cpp index 24d6896e5..862ba08ce 100644 --- a/src/duckdb/src/optimizer/aggregate_rewrite.cpp +++ b/src/duckdb/src/optimizer/aggregate_rewrite.cpp @@ -161,8 +161,8 @@ unique_ptr FrequencyAggregateRewrite::Create(AggregateRewr LogicalType::BOOLEAN, ColumnBinding(frequency_group_index, ProjectionIndex(filter_column.GetIndex()))); } if (ignore_nulls) { - auto not_null = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - not_null->GetChildrenMutable().push_back(value->Copy()); + auto not_null = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, + value->Copy()); if (filter) { filter = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(filter), std::move(not_null)); diff --git a/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp b/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp index a3c0da1b4..e7c769abe 100644 --- a/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp +++ b/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp @@ -44,12 +44,13 @@ static void RebindExpression(unique_ptr &expr, const column_binding_ if (!expr || replacement_map.empty()) { return; } - ExpressionIterator::VisitExpressionMutable( - expr, [&](BoundColumnRefExpression &colref, unique_ptr &) { + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) -> unique_ptr { auto entry = replacement_map.find(colref.Binding()); - if (entry != replacement_map.end()) { - colref.BindingMutable() = entry->second; + if (entry == replacement_map.end()) { + return nullptr; } + return colref.WithBinding(entry->second); }); } @@ -105,7 +106,7 @@ void AggregateRewriteHelper::StageVolatileAggregateInputs(Optimizer &optimizer, StageVolatileExpression(child_expr, projection_index, projection->expressions); } if (aggregate.GetOrderBys()) { - for (auto &order : aggregate.GetOrderBysMutable()->orders) { + for (auto &order : aggregate.GetOrderBys()->orders) { StageVolatileExpression(order.expression, projection_index, projection->expressions); } } diff --git a/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp b/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp index bc2992466..852f461ad 100644 --- a/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp +++ b/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/build_probe_side_optimizer.hpp" +#include "duckdb/optimizer/recursive_join_planning.hpp" #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/type_visitor.hpp" @@ -318,43 +319,6 @@ bool BuildProbeSideOptimizer::TryFlipJoinChildren(LogicalOperator &op) const { return swap; } -bool BuildProbeSideOptimizer::ContainsActiveRecursiveReference(const LogicalOperator &op) const { - if (active_recursive_cte_indexes.empty()) { - return false; - } - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cte_ref = op.Cast(); - for (auto &active_cte_index : active_recursive_cte_indexes) { - if (cte_ref.cte_index == active_cte_index) { - return true; - } - } - } - for (auto &child : op.children) { - if (ContainsActiveRecursiveReference(*child)) { - return true; - } - } - return false; -} - -bool BuildProbeSideOptimizer::ContainsCorrelationSensitiveOperators(const LogicalOperator &op) const { - switch (op.type) { - case LogicalOperatorType::LOGICAL_DELIM_GET: - case LogicalOperatorType::LOGICAL_DELIM_JOIN: - case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN: - return true; - default: - break; - } - for (auto &child : op.children) { - if (ContainsCorrelationSensitiveOperators(*child)) { - return true; - } - } - return false; -} - RecursiveProbeSidePreference BuildProbeSideOptimizer::GetRecursiveProbeSidePreference(const LogicalOperator &op) const { if (active_recursive_cte_indexes.empty() || op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { return RecursiveProbeSidePreference::NONE; @@ -367,16 +331,9 @@ RecursiveProbeSidePreference BuildProbeSideOptimizer::GetRecursiveProbeSidePrefe return RecursiveProbeSidePreference::NONE; } - auto left_depends_on_recursive_cte = ContainsActiveRecursiveReference(*op.children[0]); - auto right_depends_on_recursive_cte = ContainsActiveRecursiveReference(*op.children[1]); - if (left_depends_on_recursive_cte == right_depends_on_recursive_cte) { - return RecursiveProbeSidePreference::NONE; - } - - const auto ¤t_build_side = *op.children[1]; - auto current_orientation_can_reuse = left_depends_on_recursive_cte && !PropagatesBuildSide(join.join_type) && - !ContainsCorrelationSensitiveOperators(current_build_side); - if (current_orientation_can_reuse) { + auto left = RecursiveJoinProperties::Extract(*op.children[0], active_recursive_cte_indexes); + auto right = RecursiveJoinProperties::Extract(*op.children[1], active_recursive_cte_indexes); + if (CanPlaceRecursiveProbe(join.join_type, left, right)) { return RecursiveProbeSidePreference::KEEP; } @@ -384,11 +341,7 @@ RecursiveProbeSidePreference BuildProbeSideOptimizer::GetRecursiveProbeSidePrefe return RecursiveProbeSidePreference::NONE; } - const auto &swapped_build_side = *op.children[0]; - auto swapped_orientation_can_reuse = right_depends_on_recursive_cte && - !PropagatesBuildSide(InverseJoinType(join.join_type)) && - !ContainsCorrelationSensitiveOperators(swapped_build_side); - if (swapped_orientation_can_reuse) { + if (CanPlaceRecursiveProbe(InverseJoinType(join.join_type), right, left)) { return RecursiveProbeSidePreference::SWAP; } @@ -454,9 +407,9 @@ void BuildProbeSideOptimizer::VisitOperator(LogicalOperator &op) { } else { VisitOperator(*op.children[0]); } - active_recursive_cte_indexes.push_back(cte.table_index); + active_recursive_cte_indexes.insert(cte.table_index); VisitOperator(*op.children[1]); - active_recursive_cte_indexes.pop_back(); + active_recursive_cte_indexes.erase(cte.table_index); return; } diff --git a/src/duckdb/src/optimizer/column_binding_replacer.cpp b/src/duckdb/src/optimizer/column_binding_replacer.cpp index a6739de27..e3e66bae1 100644 --- a/src/duckdb/src/optimizer/column_binding_replacer.cpp +++ b/src/duckdb/src/optimizer/column_binding_replacer.cpp @@ -217,24 +217,35 @@ unique_ptr ColumnBindingReplacer::VisitReplace(BoundColumnRefExpress unique_ptr *expr_ptr) { if (use_index) { auto replacement = FindReplacement(expr.Binding()); - if (replacement) { - expr.BindingMutable() = replacement->new_binding; - if (replacement->replace_type) { - expr.SetReturnType(replacement->new_type); - } + if (!replacement) { + return nullptr; } - return nullptr; + if (replacement->replace_type) { + return expr.WithBinding(replacement->new_binding, replacement->new_type); + } + return expr.WithBinding(replacement->new_binding); } + // replacements are applied in order, so a later replacement can apply to the result of an earlier one + auto binding = expr.Binding(); + optional_ptr new_type; + bool replaced = false; for (auto &replacement : replacement_bindings) { - if (expr.Binding() != replacement.old_binding) { + if (binding != replacement.old_binding) { continue; } - expr.BindingMutable() = replacement.new_binding; + binding = replacement.new_binding; + replaced = true; if (replacement.replace_type) { - expr.SetReturnType(replacement.new_type); + new_type = replacement.new_type; } } - return nullptr; + if (!replaced) { + return nullptr; + } + if (new_type) { + return expr.WithBinding(binding, *new_type); + } + return expr.WithBinding(binding); } void CorrelatedColumnBindingReplacer::VisitOperatorBindings(LogicalOperator &op) { @@ -257,8 +268,8 @@ void CorrelatedColumnBindingReplacer::VisitOperatorBindings(LogicalOperator &op) unique_ptr CorrelatedColumnBindingReplacer::VisitReplace(BoundSubqueryExpression &expr, unique_ptr *expr_ptr) { ReplaceCorrelatedColumns(expr.GetBinder()->correlated_columns, *this); - if (expr.SubqueryMutable().plan) { - VisitOperator(*expr.SubqueryMutable().plan); + if (expr.Subquery().plan) { + VisitOperator(*expr.Subquery().plan); } return nullptr; } diff --git a/src/duckdb/src/optimizer/common_aggregate_optimizer.cpp b/src/duckdb/src/optimizer/common_aggregate_optimizer.cpp index 7a6e590d5..328779da4 100644 --- a/src/duckdb/src/optimizer/common_aggregate_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_aggregate_optimizer.cpp @@ -38,7 +38,7 @@ unique_ptr CommonAggregateOptimizer::VisitReplace(BoundColumnRefExpr // check if this column ref points to an aggregate that was remapped; if it does we remap it auto entry = aggregate_map.find(expr.Binding()); if (entry != aggregate_map.end()) { - expr.BindingMutable() = entry->second; + return expr.WithBinding(entry->second); } return nullptr; } diff --git a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index 3e7c65527..511fbc7e1 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -542,7 +542,7 @@ class PlanSignatureTableIndexMap { bool can_materialize = true; LogicalOperatorVisitor::EnumerateExpressions(op, [&](unique_ptr *expr) { ExpressionIterator::EnumerateExpression(*expr, [&](unique_ptr &child) { - ConvertExpression(*child, info_idx, can_materialize); + ConvertExpression(child, info_idx, can_materialize); }); }); if (op.type == LogicalOperatorType::LOGICAL_GET) { @@ -550,46 +550,53 @@ class PlanSignatureTableIndexMap { for (auto &entry : get.table_filters) { auto &expression_filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "CommonSubplanOptimizer::ConvertExpressions"); - ConvertExpression(*expression_filter.expr, info_idx, can_materialize); + ConvertExpression(expression_filter.expr, info_idx, can_materialize); } } return can_materialize; } template - void ConvertExpression(Expression &expr, idx_t &info_idx, bool &can_materialize) { + void ConvertExpression(unique_ptr &expr_p, idx_t &info_idx, bool &can_materialize) { const auto &table_index_mapping = TYPE == ConversionType::TO_CANONICAL ? to_canonical_table_index : restore_original_table_index; - // Replace column binding - if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { - auto &col_ref = expr.Cast(); + // Determine the default fields: these are cleared when converting to canonical and restored afterwards + Identifier alias; + QueryLocation query_location; + switch (TYPE) { + case ConversionType::TO_CANONICAL: + expression_info.emplace_back(expr_p->GetAlias(), expr_p->GetQueryLocation()); + break; + case ConversionType::RESTORE_ORIGINAL: { + auto &info = expression_info[info_idx++]; + alias = Identifier(std::move(info.first)); + query_location = info.second; + break; + } + } + + if (expr_p->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + // Replace column binding + auto &col_ref = expr_p->Cast(); + auto binding = col_ref.Binding(); const auto lookup_idx = TYPE == ConversionType::TO_CANONICAL - ? col_ref.Binding().table_index - : restore_original_table_index.at(col_ref.Binding().table_index); + ? binding.table_index + : restore_original_table_index.at(binding.table_index); auto &table_map = table_index_map.at(lookup_idx); if (!table_map.Empty()) { // Replace column index - col_ref.BindingMutable().column_index = table_map.Get(col_ref.Binding().column_index); + binding.column_index = table_map.Get(binding.column_index); } // Replace table index - col_ref.BindingMutable().table_index = table_index_mapping.at(col_ref.Binding().table_index); - } - - // Replace default fields - switch (TYPE) { - case ConversionType::TO_CANONICAL: - expression_info.emplace_back(expr.GetAlias(), expr.GetQueryLocation()); - expr.ClearAlias(); - expr.SetQueryLocation(optional_idx()); - break; - case ConversionType::RESTORE_ORIGINAL: - auto &info = expression_info[info_idx++]; - expr.SetAlias(Identifier(std::move(info.first))); - expr.SetQueryLocation(info.second); - break; + binding.table_index = table_index_mapping.at(binding.table_index); + expr_p = make_uniq(std::move(alias), col_ref.GetReturnType(), binding, + col_ref.Depth(), query_location); + } else { + expr_p->SetAlias(std::move(alias)); + expr_p->SetQueryLocation(query_location); } - if (expr.IsVolatile()) { + if (expr_p->IsVolatile()) { can_materialize = false; } } @@ -928,9 +935,9 @@ class CommonSubplanFinder { } else { auto &source = *expression_sources.at(binding.table_index); auto expression = source.expressions[binding.column_index]->Copy(); - ExpressionIterator::VisitExpressionMutable( - expression, [&](BoundColumnRefExpression &ref, unique_ptr &) { - ref.BindingMutable() = source.input->Expose(ref.Binding()); + expression = ExpressionIterator::PreorderReplace( + std::move(expression), [&](const BoundColumnRefExpression &ref) { + return ref.WithBinding(source.input->Expose(ref.Binding())); }); result = ColumnBinding(GetExpressionOutputTableIndex(source.op), ProjectionIndex(source.op.expressions.size())); @@ -1297,9 +1304,9 @@ class CommonSubplanFinder { unordered_set used_indexes; for (idx_t i = 0; i < op->expressions.size(); i++) { auto expression = op->expressions[i]->Copy(); - ExpressionIterator::VisitExpressionMutable( - expression, [&](BoundColumnRefExpression &ref, unique_ptr &) { - ref.BindingMutable() = GetCanonicalBinding(ref.Binding()); + expression = ExpressionIterator::PreorderReplace( + std::move(expression), [&](const BoundColumnRefExpression &ref) { + return ref.WithBinding(GetCanonicalBinding(ref.Binding())); }); idx_t index = 0; for (; index < expressions.size(); index++) { diff --git a/src/duckdb/src/optimizer/compressed_materialization.cpp b/src/duckdb/src/optimizer/compressed_materialization.cpp index 63209589e..bc96ae920 100644 --- a/src/duckdb/src/optimizer/compressed_materialization.cpp +++ b/src/duckdb/src/optimizer/compressed_materialization.cpp @@ -63,14 +63,13 @@ struct CMHelper { static unique_ptr CreateProjection(const Optimizer &optimizer, const LogicalOperator &source, vector> projections); - static unique_ptr CreateDefaultStatsAwareCast(ClientContext &context, unique_ptr input, + static unique_ptr CreateStatsAwareCast(ClientContext &context, unique_ptr input, + const LogicalType &target_type, + const BaseStatistics &input_stats, + unique_ptr &result_stats); + static unique_ptr PropagateCastStatistics(ClientContext &context, const LogicalType &source_type, const LogicalType &target_type, - const BaseStatistics &input_stats, - unique_ptr &result_stats); - static unique_ptr PropagateDefaultCastStatistics(ClientContext &context, - const LogicalType &source_type, - const LogicalType &target_type, - const BaseStatistics &input_stats); + const BaseStatistics &input_stats); static void RemapBindingMap(CompressedMaterializationInfo &info, const vector &replacement_bindings); @@ -84,10 +83,10 @@ struct CMHelper { const BaseStatistics &stats, LogicalType &offset_type, Value &min, Value &range_value); static LogicalType GetSameWidthIntegralType(const LogicalType &type, bool use_signed); - static bool ValuePreservingCastFits(const Value &value, const LogicalType &source_type, + static bool ValuePreservingCastFits(ClientContext &context, const Value &value, const LogicalType &source_type, const LogicalType &target_type); - static LogicalType GetIntegralCastType(const LogicalType &source_type, const LogicalType &offset_type, - const BaseStatistics &stats); + static LogicalType GetIntegralCastType(ClientContext &context, const LogicalType &source_type, + const LogicalType &offset_type, const BaseStatistics &stats); static unique_ptr CreateIntegralCastCompress(ClientContext &context, unique_ptr &input, const LogicalType &target_type, @@ -129,13 +128,12 @@ unique_ptr CMHelper::CreateProjection(const Optimizer &optimi return projection; } -unique_ptr CMHelper::CreateDefaultStatsAwareCast(ClientContext &context, unique_ptr input, - const LogicalType &target_type, - const BaseStatistics &input_stats, - unique_ptr &result_stats) { - auto result = BoundCastExpression::AddDefaultCastToType(std::move(input), target_type); +unique_ptr CMHelper::CreateStatsAwareCast(ClientContext &context, unique_ptr input, + const LogicalType &target_type, const BaseStatistics &input_stats, + unique_ptr &result_stats) { + auto result = BoundCastExpression::AddCastToType(context, std::move(input), target_type); if (!BoundCastExpression::IsCast(*result)) { // LCOV_EXCL_START - throw InternalException("Expected a cast in CMHelper::CreateDefaultStatsAwareCast"); + throw InternalException("Expected a cast in CMHelper::CreateStatsAwareCast"); } // LCOV_EXCL_STOP auto &cast = result->Cast(); CMUtils::MarkCast(cast); @@ -147,13 +145,12 @@ unique_ptr CMHelper::CreateDefaultStatsAwareCast(ClientContext &cont return result; } -unique_ptr CMHelper::PropagateDefaultCastStatistics(ClientContext &context, - const LogicalType &source_type, - const LogicalType &target_type, - const BaseStatistics &input_stats) { - CastFunctionSet default_casts; +unique_ptr CMHelper::PropagateCastStatistics(ClientContext &context, const LogicalType &source_type, + const LogicalType &target_type, + const BaseStatistics &input_stats) { + auto &cast_functions = CastFunctionSet::Get(context); GetCastFunctionInput get_input(context); - auto bound_cast = default_casts.GetCastFunction(source_type, target_type, get_input); + auto bound_cast = cast_functions.GetCastFunction(source_type, target_type, get_input); return bound_cast.PropagateStatistics(source_type, target_type, input_stats, context); } @@ -263,15 +260,15 @@ LogicalType CMHelper::GetSameWidthIntegralType(const LogicalType &type, const bo } } -bool CMHelper::ValuePreservingCastFits(const Value &value, const LogicalType &source_type, +bool CMHelper::ValuePreservingCastFits(ClientContext &context, const Value &value, const LogicalType &source_type, const LogicalType &target_type) { optional roundtrip_value; try { - auto cast_value = value.DefaultTryCastAs(target_type, nullptr, true); + auto cast_value = value.TryCastAs(context, target_type, nullptr, true); if (!cast_value) { return false; } - roundtrip_value = cast_value->DefaultTryCastAs(source_type, nullptr, true); + roundtrip_value = cast_value->TryCastAs(context, source_type, nullptr, true); if (!roundtrip_value) { return false; } @@ -281,8 +278,8 @@ bool CMHelper::ValuePreservingCastFits(const Value &value, const LogicalType &so return value == *roundtrip_value; } -LogicalType CMHelper::GetIntegralCastType(const LogicalType &source_type, const LogicalType &offset_type, - const BaseStatistics &stats) { +LogicalType CMHelper::GetIntegralCastType(ClientContext &context, const LogicalType &source_type, + const LogicalType &offset_type, const BaseStatistics &stats) { if (GetTypeIdSize(source_type.InternalType()) <= GetTypeIdSize(offset_type.InternalType())) { return LogicalType::INVALID; } @@ -299,12 +296,12 @@ LogicalType CMHelper::GetIntegralCastType(const LogicalType &source_type, const auto alternate_type = GetSameWidthIntegralType(offset_type, !preferred_signed); const auto min = NumericStats::Min(stats); const auto max = NumericStats::Max(stats); - if (preferred_type.IsValid() && ValuePreservingCastFits(min, source_type, preferred_type) && - ValuePreservingCastFits(max, source_type, preferred_type)) { + if (preferred_type.IsValid() && ValuePreservingCastFits(context, min, source_type, preferred_type) && + ValuePreservingCastFits(context, max, source_type, preferred_type)) { return preferred_type; } - if (alternate_type.IsValid() && ValuePreservingCastFits(min, source_type, alternate_type) && - ValuePreservingCastFits(max, source_type, alternate_type)) { + if (alternate_type.IsValid() && ValuePreservingCastFits(context, min, source_type, alternate_type) && + ValuePreservingCastFits(context, max, source_type, alternate_type)) { return alternate_type; } return LogicalType::INVALID; @@ -315,14 +312,14 @@ unique_ptr CMHelper::CreateIntegralCastCompress(ClientContex const LogicalType &target_type, const BaseStatistics &stats) { const auto source_type = input->GetReturnType(); - auto compress_stats = PropagateDefaultCastStatistics(context, source_type, target_type, stats); + auto compress_stats = PropagateCastStatistics(context, source_type, target_type, stats); if (!compress_stats) { return nullptr; } - if (!PropagateDefaultCastStatistics(context, target_type, source_type, *compress_stats)) { + if (!PropagateCastStatistics(context, target_type, source_type, *compress_stats)) { return nullptr; } - auto compress_expr = CreateDefaultStatsAwareCast(context, std::move(input), target_type, stats, compress_stats); + auto compress_expr = CreateStatsAwareCast(context, std::move(input), target_type, stats, compress_stats); return make_uniq(std::move(compress_expr), std::move(compress_stats), CompressedMaterializationType::CAST); } @@ -582,13 +579,13 @@ unique_ptr CompressedMaterialization::CreateRestoreExpression(unique return GetDecompressExpression(std::move(input), binding_info.type, stats); case CompressedMaterializationType::CAST: { auto source_type = input->GetReturnType(); - auto source_stats = CMHelper::PropagateDefaultCastStatistics(context, binding_info.type, source_type, stats); + auto source_stats = CMHelper::PropagateCastStatistics(context, binding_info.type, source_type, stats); if (!source_stats) { // LCOV_EXCL_START throw InternalException("Could not obtain compressed statistics for cast restoration"); } // LCOV_EXCL_STOP unique_ptr result_stats; - return CMHelper::CreateDefaultStatsAwareCast(context, std::move(input), binding_info.type, *source_stats, - result_stats); + return CMHelper::CreateStatsAwareCast(context, std::move(input), binding_info.type, *source_stats, + result_stats); } default: throw InternalException("Invalid compressed materialization type"); @@ -736,7 +733,7 @@ unique_ptr CompressedMaterialization::GetIntegralCompress(un } D_ASSERT(GetTypeIdSize(cast_type.InternalType()) < GetTypeIdSize(type.InternalType())); - const auto value_preserving_cast_type = CMHelper::GetIntegralCastType(type, cast_type, stats); + const auto value_preserving_cast_type = CMHelper::GetIntegralCastType(context, type, cast_type, stats); if (value_preserving_cast_type.IsValid()) { auto result = CMHelper::CreateIntegralCastCompress(context, input, value_preserving_cast_type, stats); if (result) { diff --git a/src/duckdb/src/optimizer/cse_optimizer.cpp b/src/duckdb/src/optimizer/cse_optimizer.cpp index 387cb942f..b44ca78a6 100644 --- a/src/duckdb/src/optimizer/cse_optimizer.cpp +++ b/src/duckdb/src/optimizer/cse_optimizer.cpp @@ -149,10 +149,10 @@ void CommonSubExpressionOptimizer::PerformCSEReplacement(unique_ptr bound_column_ref.GetAlias(), bound_column_ref.GetReturnType(), bound_column_ref.Binding()); auto new_column_index = ColumnBinding::PushExpression(state.expressions, std::move(new_col_ref)); state.column_map[bound_column_ref.Binding()] = new_column_index; - bound_column_ref.BindingMutable() = ColumnBinding(state.projection_index, new_column_index); + expr_ptr = bound_column_ref.WithBinding(ColumnBinding(state.projection_index, new_column_index)); } else { - // else: just update the column binding! - bound_column_ref.BindingMutable() = ColumnBinding(state.projection_index, column_entry->second); + // else: just point the column reference at the existing column + expr_ptr = bound_column_ref.WithBinding(ColumnBinding(state.projection_index, column_entry->second)); } return; } diff --git a/src/duckdb/src/optimizer/deliminator.cpp b/src/duckdb/src/optimizer/deliminator.cpp index e3a737527..a6375ce17 100644 --- a/src/duckdb/src/optimizer/deliminator.cpp +++ b/src/duckdb/src/optimizer/deliminator.cpp @@ -231,9 +231,8 @@ bool Deliminator::RemoveJoinWithDelimGet(LogicalComparisonJoin &delim_join, cons // Do NOT add for DISTINCT FROM variants, as they handle NULL correctly if (cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM && cond.GetComparisonType() != ExpressionType::COMPARE_DISTINCT_FROM) { - auto is_not_null_expr = - make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - is_not_null_expr->GetChildrenMutable().push_back(other_side.Copy()); + auto is_not_null_expr = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, + LogicalType::BOOLEAN, other_side.Copy()); filter_expressions.push_back(std::move(is_not_null_expr)); } } diff --git a/src/duckdb/src/optimizer/disjunctive_join_rewriter.cpp b/src/duckdb/src/optimizer/disjunctive_join_rewriter.cpp index ba66cb0cd..fc211ddde 100644 --- a/src/duckdb/src/optimizer/disjunctive_join_rewriter.cpp +++ b/src/duckdb/src/optimizer/disjunctive_join_rewriter.cpp @@ -280,12 +280,11 @@ unique_ptr DisjunctiveJoinRewriter::CreateBranchJoin(const CTEI vector> exclusions; if (previous.GetComparisonType() == ExpressionType::COMPARE_EQUAL) { // Preserve UNKNOWN, with separate NULL checks that statistics can simplify. - auto left_null = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - left_null->GetChildrenMutable().push_back(previous.GetLHS().Copy()); + auto left_null = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, + previous.GetLHS().Copy()); exclusions.push_back(std::move(left_null)); - auto right_null = - make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - right_null->GetChildrenMutable().push_back(previous.GetRHS().Copy()); + auto right_null = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, + previous.GetRHS().Copy()); exclusions.push_back(std::move(right_null)); } exclusions.push_back(BoundComparisonExpression::Create(NegateComparisonExpression(previous.GetComparisonType()), diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp new file mode 100644 index 000000000..518e685c6 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp @@ -0,0 +1,1299 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" + +#include "duckdb/common/operator/multiply.hpp" +#include "duckdb/storage/statistics/node_statistics.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" +#include "duckdb/optimizer/aggregate_rewrite_helper.hpp" +#include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#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_operator_expression.hpp" +#include "duckdb/planner/expression/bound_window_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_deep_copy.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/logical_operator_repeatability.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_column_data_get.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_dummy_scan.hpp" +#include "duckdb/planner/operator/logical_expression_get.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/parser/expression_map.hpp" + +#include +#include + +namespace duckdb { + +DuplicateEliminatedDomainOptimizer::DuplicateEliminatedDomainOptimizer(Optimizer &optimizer_p) + : optimizer(optimizer_p) { +} + +static bool HasImplicitBitstringAggregate(const LogicalOperator &op) { + bool found = false; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { + ExpressionIterator::VisitExpression(**expression, [&](const auto &aggregate) { + found |= aggregate.Function().GetName() == "bitstring_agg" && aggregate.Function().HasStatisticsCallback(); + }); + ExpressionIterator::VisitExpression(**expression, [&](const auto &window) { + auto &function = window.AggregateFunction(); + found |= function && function->GetName() == "bitstring_agg" && function->HasStatisticsCallback(); + }); + }); + if (found) { + return true; + } + for (auto &child : op.children) { + if (HasImplicitBitstringAggregate(*child)) { + return true; + } + } + return false; +} + +void DuplicateEliminatedDomainOptimizer::Optimize(unique_ptr &op) { + // Implicit bitstring bounds depend on statistics, including those propagated through CTE references. + if (!HasImplicitBitstringAggregate(*op)) { + VisitOperator(op); + op->ResolveOperatorTypes(); + } +} + +static bool IsWorkReference(const Expression &expression) { + switch (expression.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: + return expression.Cast().Depth() == 0; + case ExpressionClass::BOUND_CONSTANT: + case ExpressionClass::BOUND_PARAMETER: + return true; + default: + return false; + } +} + +static optional_idx ReferenceIndex(const Expression &expression, LogicalOperator &input) { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + expression.Cast().Depth() != 0) { + return {}; + } + return AggregateRewriteHelper::GetDirectReferenceIndex(expression, input); +} + +static optional_idx ReferenceIndex(const Expression &expression, LogicalOperator &input, const LogicalType &type) { + if (!expression.GetReturnType().EqualsIncludingCollation(type)) { + return {}; + } + return ReferenceIndex(expression, input); +} + +static bool HasSimpleGrouping(const LogicalAggregate &aggregate) { + return !aggregate.groups.empty() && aggregate.grouping_functions.empty() && + (aggregate.grouping_sets.empty() || + (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size())); +} + +//! One full grouping set preserves the directly referenced key and its comparison semantics. +static optional_idx GroupKeyIndex(LogicalAggregate &aggregate, idx_t key) { + if (!HasSimpleGrouping(aggregate) || key >= aggregate.groups.size()) { + return {}; + } + return ReferenceIndex(*aggregate.groups[key], *aggregate.children[0]); +} + +static optional_idx GroupKeyIndex(LogicalAggregate &aggregate, idx_t key, const LogicalType &type) { + auto index = GroupKeyIndex(aggregate, key); + if (!index.IsValid() || !aggregate.groups[key]->GetReturnType().EqualsIncludingCollation(type)) { + return {}; + } + return index; +} + +static optional_ptr FindAggregate(LogicalOperator &op, idx_t key) { + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expression : op.expressions) { + if (expression->CanThrow() || expression->IsVolatile()) { + return nullptr; + } + } + auto index = ReferenceIndex(*op.expressions[key], *op.children[0]); + return index.IsValid() ? FindAggregate(*op.children[0], index.GetIndex()) : nullptr; + } + if (op.type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY || key != 0) { + return nullptr; + } + 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; + } + for (auto &expression : aggregate.expressions) { + bool supported = true; + ExpressionIterator::EnumerateChildren(*expression, + [&](const Expression &child) { supported &= IsWorkReference(child); }); + if (!supported) { + return nullptr; + } + } + return LogicalSubtreeIsRepeatable(aggregate) ? &aggregate : nullptr; +} + +//! An upper bound from the actual closed input, not a cardinality estimate. +static optional_idx FixedRowCount(LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + return 1; + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + return 0; + case LogicalOperatorType::LOGICAL_CHUNK_GET: { + auto &get = op.Cast(); + return get.collection ? optional_idx(get.collection->Count()) : optional_idx(); + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + if (op.children.size() == 1 && op.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + return op.Cast().expressions.size(); + } + return {}; + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = op.Cast(); + // Empty grouping sets can produce a row from empty input. + if (aggregate.grouping_sets.size() != 1 || aggregate.grouping_sets[0].empty()) { + return {}; + } + return FixedRowCount(*op.children[0]); + } + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + return FixedRowCount(*op.children[0]); + default: + return {}; + } +} + +static bool AppendFixedKey(vector>> &rows, const Expression &expression, + const LogicalType &type) { + if ((expression.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT && + expression.GetExpressionClass() != ExpressionClass::BOUND_PARAMETER) || + !expression.GetReturnType().EqualsIncludingCollation(type)) { + return false; + } + vector> row; + row.push_back(expression.Copy()); + rows.push_back(std::move(row)); + return true; +} + +//! Copy keys already represented by expressions, leaving columnar inputs on the runtime path. +//! The caller's payload and its evaluation remain in place. +static bool CopyFixedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, + vector>> &rows) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &expression = *op.expressions[key]; + auto index = ReferenceIndex(expression, *op.children[0]); + if (index.IsValid()) { + return CopyFixedKeys(*op.children[0], index.GetIndex(), type, rows); + } + auto count = FixedRowCount(*op.children[0]); + return count.IsValid() && (count.GetIndex() == 0 || AppendFixedKey(rows, expression, type)); + } + case LogicalOperatorType::LOGICAL_FILTER: { + auto binding = op.GetColumnBindings()[key]; + BoundColumnRefExpression reference(type, binding); + auto index = ReferenceIndex(reference, *op.children[0]); + return index.IsValid() && CopyFixedKeys(*op.children[0], index.GetIndex(), type, rows); + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto index = GroupKeyIndex(op.Cast(), key, type); + return index.IsValid() && CopyFixedKeys(*op.children[0], index.GetIndex(), type, rows); + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: { + if (!FixedRowCount(op).IsValid()) { + return false; + } + for (auto &row : op.Cast().expressions) { + if (!AppendFixedKey(rows, *row[key], type)) { + return false; + } + } + return true; + } + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + return true; + default: + return false; + } +} + +//! The old restriction must be proven to contain every demanded key. +static bool CopyExactFixedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, + vector>> &rows) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &expression = *op.expressions[key]; + auto index = ReferenceIndex(expression, *op.children[0], type); + if (index.IsValid()) { + return CopyExactFixedKeys(*op.children[0], index.GetIndex(), type, rows); + } + return op.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN && + AppendFixedKey(rows, expression, type); + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto index = GroupKeyIndex(op.Cast(), key, type); + return index.IsValid() && CopyExactFixedKeys(*op.children[0], index.GetIndex(), type, rows); + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_ANY_JOIN: { + auto &join = op.Cast(); + if (join.join_type != JoinType::LEFT) { + return false; + } + BoundColumnRefExpression reference(type, op.GetColumnBindings()[key]); + auto index = ReferenceIndex(reference, *op.children[0]); + return index.IsValid() && CopyExactFixedKeys(*op.children[0], index.GetIndex(), type, rows); + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + return CopyFixedKeys(op, key, type, rows); + default: + return false; + } +} + +enum class RestrictionAction { KEEP, REPLACE, REMOVE }; + +static unique_ptr CreateKeyDomain(Optimizer &optimizer, unique_ptr input, + unique_ptr key) { + auto domain = make_uniq(optimizer.binder.GenerateTableIndex(), + optimizer.binder.GenerateTableIndex(), vector>()); + domain->groups.push_back(std::move(key)); + domain->grouping_sets.push_back({ProjectionIndex(0)}); + domain->children.push_back(std::move(input)); + return domain; +} + +static unique_ptr DomainKey(const LogicalAggregate &domain) { + return make_uniq(domain.groups[0]->GetReturnType(), + ColumnBinding(domain.group_index, ProjectionIndex(0))); +} + +static optional_ptr +FindVisibleOwner(TableIndex index, const vector> &cte_scopes) { + for (auto &owner : cte_scopes) { + if (owner.get().table_index == index) { + return owner.get(); + } + } + return nullptr; +} + +//! Guaranteed bounds valid before and after expanding a domain; callbacks only modify expression copies. +class DomainAggregateBounds { +public: + DomainAggregateBounds(ClientContext &context_p, const vector> &scopes_p) + : context(context_p), scopes(scopes_p) { + } + + bool CanEvaluate(LogicalAggregate &aggregate) const { + for (auto &expression : aggregate.expressions) { + if (!expression->CanThrow()) { + continue; + } + if (expression->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + return false; + } + auto copy = expression->Copy(); + column_binding_set_t visited; + AggregateStats(copy->Cast(), *aggregate.children[0], visited); + if (copy->CanThrow()) { + return false; + } + } + return true; + } + +private: + optional_idx MaxRows(LogicalOperator &input, unordered_set &visited) const { + switch (input.type) { + case LogicalOperatorType::LOGICAL_GET: { + auto &get = input.Cast(); + if (!get.children.empty() || !get.function.cardinality || !get.bind_data) { + return {}; + } + auto stats = get.function.cardinality(context, get.bind_data.get()); + return stats && stats->has_max_cardinality ? optional_idx(stats->max_cardinality) : optional_idx(); + } + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + return MaxRows(*input.children[0], visited); + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = input.Cast(); + if (aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1) { + return 1; + } + return HasSimpleGrouping(aggregate) ? MaxRows(*input.children[0], visited) : optional_idx(); + } + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &reference = input.Cast(); + auto owner = FindVisibleOwner(reference.cte_index, scopes); + // Reject repeated definitions as well as cycles: a CTE DAG can otherwise require exponential work. + if (!owner || reference.correlated_columns || reference.is_recurring || + !visited.insert(reference.cte_index).second) { + return {}; + } + return MaxRows(*owner->children[0], visited); + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { + if (input.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = input.Cast(); + if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) { + return MaxRows(*input.children[0], visited); + } + if (join.join_type != JoinType::INNER) { + return {}; + } + } + auto left = MaxRows(*input.children[0], visited); + auto right = MaxRows(*input.children[1], visited); + idx_t product; + return left.IsValid() && right.IsValid() && + TryMultiplyOperator::Operation(left.GetIndex(), right.GetIndex(), product) + ? optional_idx(product) + : optional_idx(); + } + default: + return FixedRowCount(input); + } + } + + unique_ptr AggregateStats(BoundAggregateExpression ©, LogicalOperator &input, + column_binding_set_t &visited) const { + if (!copy.Function().HasStatisticsCallback()) { + return nullptr; + } + unordered_set row_visits; + auto maximum = MaxRows(input, row_visits); + if (!maximum.IsValid()) { + return nullptr; + } + vector children; + for (auto &child : copy.GetChildren()) { + auto stats = ExpressionStats(*child, input, visited); + children.push_back(stats ? stats->Copy() : BaseStatistics::CreateUnknown(child->GetReturnType())); + } + NodeStatistics rows(maximum.GetIndex(), maximum.GetIndex()); + AggregateStatisticsInput statistics(copy.BindInfo(), children, &rows); + return copy.Function().GetCallbacks().GetStatisticsCallback()(context, copy, statistics); + } + + unique_ptr ExpressionStats(const Expression &expression, LogicalOperator &input, + column_binding_set_t &visited) const { + if (expression.GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { + auto copy = expression.Copy(); + auto stats = AggregateStats(copy->Cast(), input, visited); + return copy->CanThrow() ? nullptr : std::move(stats); + } + auto index = ReferenceIndex(expression, input); + if (index.IsValid()) { + switch (input.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projected = *input.expressions[index.GetIndex()]; + if (!expression.GetReturnType().EqualsIncludingCollation(projected.GetReturnType())) { + return nullptr; + } + return ExpressionStats(projected, *input.children[0], visited); + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = input.Cast(); + if (HasSimpleGrouping(aggregate)) { + auto binding = expression.Cast().Binding(); + auto &source = aggregate.GetExpression(binding); + if (!expression.GetReturnType().EqualsIncludingCollation(source.GetReturnType())) { + return nullptr; + } + return ExpressionStats(source, *input.children[0], visited); + } + break; + } + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &reference = input.Cast(); + auto owner = FindVisibleOwner(reference.cte_index, scopes); + if (!owner || reference.is_recurring || reference.correlated_columns || + !visited.emplace(reference.cte_index, ProjectionIndex(index.GetIndex())).second) { + break; + } + auto bindings = owner->children[0]->GetColumnBindings(); + if (index.GetIndex() >= bindings.size() || index.GetIndex() >= reference.chunk_types.size() || + !expression.GetReturnType().EqualsIncludingCollation(reference.chunk_types[index.GetIndex()])) { + break; + } + BoundColumnRefExpression source(expression.GetReturnType(), bindings[index.GetIndex()]); + return ExpressionStats(source, *owner->children[0], visited); + } + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + for (auto &child : input.children) { + if (ReferenceIndex(expression, *child).IsValid()) { + return ExpressionStats(expression, *child, visited); + } + } + break; + default: + break; + } + } + // Declared DECIMAL endpoints remain valid without evaluating predicates or propagating statistics. + auto &type = expression.GetReturnType(); + if (type.id() != LogicalTypeId::DECIMAL) { + return nullptr; + } + auto stats = NumericStats::CreateUnknown(type).ToUnique(); + NumericStats::SetMin(*stats, Value::MinimumValue(type)); + NumericStats::SetMax(*stats, Value::MaximumValue(type)); + return stats; + } + +private: + ClientContext &context; + const vector> &scopes; +}; + +//! A matched input restriction and the projections between it and its aggregate. +//! Borrows the plan for one decision. Apply may destroy the matched join. +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]); + } + +public: + optional_ptr GetJoin() const { + return join; + } + + bool HasSimpleProjections() const; + bool CanRemove() const; + bool FiltersNullKeys() const { + return join->conditions[0].GetComparisonType() == ExpressionType::COMPARE_EQUAL && + consumer_comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + } + void Apply(unique_ptr &domain, RestrictionAction action); + +private: + optional_ptr Find(LogicalOperator &input, const Expression &key); + +private: + LogicalAggregate &aggregate; + ExpressionType consumer_comparison; + DomainAggregateBounds bounds; + optional_ptr join; + vector> projections; +}; + +optional_ptr DomainRestriction::Find(LogicalOperator &input, const Expression &key) { + if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto index = ReferenceIndex(key, input); + if (!index.IsValid()) { + return nullptr; + } + projections.push_back(input.Cast()); + return Find(*input.children[0], *input.expressions[index.GetIndex()]); + } + 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()) { + 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; + } + return join; +} + +bool DomainRestriction::HasSimpleProjections() const { + for (auto &projection : projections) { + for (auto &expression : projection.get().expressions) { + if (!IsWorkReference(*expression)) { + return false; + } + } + } + return true; +} + +bool DomainRestriction::CanRemove() const { + if (!HasSimpleProjections()) { + return false; + } + return bounds.CanEvaluate(aggregate); +} + +void DomainRestriction::Apply(unique_ptr &domain, RestrictionAction action) { + auto &restriction = *join; + auto &condition = restriction.conditions[0]; + if (action == RestrictionAction::REPLACE) { + 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); + } + slot = LogicalJoin::PromoteJoinSide(std::move(input), std::move(restriction.left_projection_map)); + join = nullptr; + } +} + +//! Compare alternatives for one aggregate 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, double key_input_rows_p, + double source_read_write_work_p) + : extractor(extractor_p), aggregate(aggregate_p), key_input_rows(key_input_rows_p), + source_read_write_work(source_read_write_work_p) { + } + +public: + bool IsProfitable(LogicalComparisonJoin &restriction, LogicalOperator &domain); + RestrictionAction ChooseRestrictionAction(const DomainRestriction &existing, LogicalAggregate &domain, + bool keys_may_expand = false); + +private: + static bool IsCheaper(double candidate, double original); + static double EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows); + 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); + +private: + RelationStatsExtractor &extractor; + LogicalAggregate &aggregate; + double key_input_rows; + double source_read_write_work; +}; + +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; +} + +double DomainCostModel::EstimateAggregateWork(double input_rows, double group_count) const { + auto aggregate_work_per_row = static_cast(aggregate.expressions.size()) + 1; + return aggregate_work_per_row * input_rows + (aggregate_work_per_row + 1) * group_count; +} + +double DomainCostModel::EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows) { + 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::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]); + } + } + return 0; +} + +double DomainCostModel::EstimateAggregateWork(const RelationStats &input, ColumnBinding group_binding) const { + auto column = input.GetColumnStats(group_binding); + if (!column) { + return std::numeric_limits::quiet_NaN(); + } + auto group_count = + RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, input.cardinality); + return EstimateAggregateWork(static_cast(input.cardinality), static_cast(group_count)); +} + +static optional EstimateRestrictionStats(LogicalComparisonJoin &restriction, const RelationStats &input, + const RelationStats &keys) { + auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(restriction, input, keys); + if (!estimate.used_domain_evidence) { + return {}; + } + auto restricted = input; + RelationStatisticsHelper::ApplySemiAntiJoinStats(restriction, input, keys, restricted); + return restricted; +} + +bool DomainCostModel::IsProfitable(LogicalComparisonJoin &restriction, LogicalOperator &domain) { + auto input = extractor.Extract(*aggregate.children[0]); + auto groups = extractor.Extract(aggregate); + auto keys = extractor.Extract(domain); + if (!input || !groups || !keys) { + return false; + } + auto restricted = EstimateRestrictionStats(restriction, *input, *keys); + if (!restricted) { + return false; + } + auto column = restricted->GetColumnStats(aggregate.groups[0]->Cast().Binding()); + if (!column) { + return false; + } + // The inserted SEMI is the new aggregate input; old input-shape refinements no longer apply. + auto group_count = + RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); + auto input_rows = static_cast(input->cardinality); + auto restricted_rows = static_cast(restricted->cardinality); + auto original_groups = static_cast(groups->cardinality); + auto restricted_groups = static_cast(group_count); + auto distinct_key_rows = static_cast(keys->cardinality); + // Cancel unchanged input/caller work and the consumer's identical output. + auto canonical = EstimateAggregateWork(input_rows, original_groups); + auto candidate = EstimateAggregateWork(restricted_rows, restricted_groups) + + EstimateSemiJoinWork(input_rows, restricted_rows, distinct_key_rows) + + EstimateFixedDomainWork(key_input_rows, distinct_key_rows) + source_read_write_work; + return IsCheaper(candidate, canonical); +} + +RestrictionAction DomainCostModel::ChooseRestrictionAction(const DomainRestriction &existing, LogicalAggregate &domain, + bool keys_may_expand) { + if (keys_may_expand && !existing.CanRemove()) { + return RestrictionAction::KEEP; + } + 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; + } + 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_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 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 action = RestrictionAction::KEEP; + auto consider = [&](double work, RestrictionAction alternative) { + if (IsCheaper(work, best_work)) { + best_work = work; + 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), + RestrictionAction::REMOVE); + } + return action; +} + +static bool HasSharedSource(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF || op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + return true; + } + for (auto &child : op.children) { + if (HasSharedSource(*child)) { + return true; + } + } + return false; +} + +static bool HasRuntimeFilterTargets(LogicalAggregate &aggregate) { + JoinFilterPushdownColumn column; + if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(*aggregate.groups[0], column)) { + return false; + } + vector targets; + JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*aggregate.children[0], {std::move(column)}, targets, + EqualityPropagation::ENABLED); + return !targets.empty(); +} + +static bool TryOptimizeRestriction(Optimizer &optimizer, LogicalAggregate &aggregate, + unique_ptr &domain, ExpressionType consumer_comparison, + const vector> &cte_scopes) { + DomainRestriction existing(optimizer.context, cte_scopes, aggregate, consumer_comparison); + auto restriction = existing.GetJoin(); + if (!restriction || HasSharedSource(*restriction->children[1])) { + return false; + } + auto &condition = restriction->conditions[0]; + auto key = ReferenceIndex(condition.GetRHS(), *restriction->children[1]).GetIndex(); + vector>> original_rows; + if (!CopyExactFixedKeys(*restriction->children[1], key, condition.GetRHS().GetReturnType(), original_rows)) { + return false; + } + expression_set_t original_keys; + for (auto &row : original_rows) { + original_keys.insert(*row[0]); + } + auto &fixed = domain->children[0]->Cast(); + for (auto &row : fixed.expressions) { + if (!original_keys.count(*row[0])) { + return false; + } + } + RelationStatsExtractor extractor(optimizer.context); + DomainCostModel costs(extractor, aggregate, static_cast(fixed.expressions.size()), 0); + auto action = costs.ChooseRestrictionAction(existing, *domain); + if (action == RestrictionAction::KEEP) { + return false; + } + existing.Apply(domain, action); + return true; +} + +static optional_ptr FindSharedKey(LogicalOperator &op, idx_t &key) { + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto index = ReferenceIndex(*op.expressions[key], *op.children[0]); + if (!index.IsValid()) { + return nullptr; + } + key = index.GetIndex(); + return FindSharedKey(*op.children[0], key); + } + if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto &aggregate = op.Cast(); + auto index = GroupKeyIndex(aggregate, key); + if (!index.IsValid()) { + return nullptr; + } + key = index.GetIndex(); + return FindSharedKey(*op.children[0], key); + } + if (op.type != LogicalOperatorType::LOGICAL_CTE_REF) { + return nullptr; + } + auto &reference = op.Cast(); + return reference.is_recurring || reference.correlated_columns ? nullptr : &reference; +} + +struct RuntimeDomainSource { + optional_ptr input; + optional_ptr owner; + idx_t key = 0; +}; + +static bool ReferencesVisibleOwners(LogicalOperator &op, const vector> &cte_scopes) { + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &cte = op.Cast(); + return !cte.is_recurring && !cte.correlated_columns && FindVisibleOwner(cte.cte_index, cte_scopes); + } + for (auto &child : op.children) { + if (!ReferencesVisibleOwners(*child, cte_scopes)) { + return false; + } + } + return true; +} + +static bool CanChangeRuntimeKeyReaders(LogicalOperator &op, const vector> &cte_scopes, + unordered_map &checked_owners) { + if (ClassifyLogicalOperatorRepeatability(op) != LogicalOperatorRepeatability::REPEATABLE) { + return false; + } + // A SINGLE join can throw when additional rows are evaluated. + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op.Cast().join_type == JoinType::SINGLE) { + return false; + } + // Reader changes and materialization can expose rows that later filters or limits would skip. + bool can_throw = false; + LogicalOperatorVisitor::EnumerateExpressions( + op, [&](unique_ptr *expression) { can_throw |= (*expression)->CanThrow(); }); + // Pushed-down scan predicates are not enumerated by the logical operator visitor. + if (op.type == LogicalOperatorType::LOGICAL_GET) { + for (auto &entry : op.Cast().table_filters) { + can_throw |= + ExpressionFilter::GetExpressionFilter(entry.Filter(), "CanChangeRuntimeKeyReaders").expr->CanThrow(); + } + } + if (can_throw) { + return false; + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &cte = op.Cast(); + auto owner = FindVisibleOwner(cte.cte_index, cte_scopes); + if (!owner || cte.is_recurring || cte.correlated_columns) { + return false; + } + auto entry = checked_owners.emplace(cte.cte_index, false); + if (!entry.second) { + return entry.first->second; + } + // 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; + } + for (auto &child : op.children) { + if (!CanChangeRuntimeKeyReaders(*child, cte_scopes, checked_owners)) { + return false; + } + } + return true; +} + +static bool TryGetRuntimeDomainSource(LogicalOperator &demand, idx_t demand_index, + const vector> &cte_scopes, + RuntimeDomainSource &source) { + source.key = demand_index; + auto shared = FindSharedKey(demand, source.key); + unordered_map checked_owners; + if (shared) { + auto owner = FindVisibleOwner(shared->cte_index, cte_scopes); + // Statistics can make the original reader filterable after this pass. + if (!owner || !CanChangeRuntimeKeyReaders(*shared, cte_scopes, checked_owners)) { + return false; + } + source.input = *owner->children[0]; + source.owner = owner; + } else { + if (!CanChangeRuntimeKeyReaders(demand, cte_scopes, checked_owners)) { + return false; + } + source.input = demand; + source.key = demand_index; + } + return true; +} + +static void TraceSharedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, + const vector> &cte_scopes, bool allow_filters, + column_binding_set_t &keys) { + 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()) { + return; + } + binding = expression.Cast().Binding(); + break; + } + case LogicalOperatorType::LOGICAL_FILTER: + if (!allow_filters) { + return; + } + break; + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = current->Cast(); + if (!GroupKeyIndex(aggregate, index.GetIndex(), type).IsValid()) { + return; + } + auto &expression = *aggregate.groups[index.GetIndex()]; + binding = expression.Cast().Binding(); + break; + } + case 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) { + return; + } + current = *owner->children[0]; + binding = current->GetColumnBindings()[index.GetIndex()]; + continue; + } + default: + return; + } + current = *current->children[0]; + } +} + +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); + auto restriction = existing.GetJoin(); + if (!restriction || !existing.HasSimpleProjections()) { + return RestrictionAction::KEEP; + } + unordered_map checked_owners; + if (!CanChangeRuntimeKeyReaders(*restriction->children[1], cte_scopes, checked_owners)) { + return RestrictionAction::KEEP; + } + 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); + bool contains_demand = false; + for (auto &binding : original_keys) { + contains_demand |= demanded_keys.count(binding) != 0; + } + if (!contains_demand) { + return RestrictionAction::KEEP; + } + auto action = costs.ChooseRestrictionAction(existing, *domain, keys_may_expand); + if (action != RestrictionAction::KEEP) { + existing.Apply(domain, action); + } + return action; +} + +struct ScanKeySource { + optional_ptr> input; + idx_t key = 0; + double rows = 0; + double scan_rows = 0; +}; + +static optional_ptr FindClosedScan(LogicalOperator &input) { + if (input.type == LogicalOperatorType::LOGICAL_FILTER || input.type == LogicalOperatorType::LOGICAL_PROJECTION) { + return FindClosedScan(*input.children[0]); + } + if (input.type != LogicalOperatorType::LOGICAL_GET || !input.children.empty()) { + return nullptr; + } + auto &get = input.Cast(); + return get.GetTable() ? &get : nullptr; +} + +//! An INNER equality lets either input supply a superset of the joined key domain. +static void FindScanKeySource(const unique_ptr &input, idx_t key, const LogicalType &type, + RelationStatsExtractor &extractor, ClientContext &context, ScanKeySource &source) { + if (auto scan = FindClosedScan(*input)) { + auto stats = extractor.Extract(*input); + if (stats && (!source.input || static_cast(stats->cardinality) < source.rows)) { + source.input = input; + source.key = key; + source.rows = static_cast(stats->cardinality); + source.scan_rows = static_cast(scan->EstimateSourceCardinality(context)); + } + return; + } + if (input->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto index = ReferenceIndex(*input->expressions[key], *input->children[0], type); + if (index.IsValid()) { + FindScanKeySource(input->children[0], index.GetIndex(), type, extractor, context, source); + } + return; + } + if (input->type == LogicalOperatorType::LOGICAL_FILTER) { + BoundColumnRefExpression reference(type, input->GetColumnBindings()[key]); + auto index = ReferenceIndex(reference, *input->children[0]); + if (index.IsValid()) { + FindScanKeySource(input->children[0], index.GetIndex(), type, extractor, context, source); + } + return; + } + if (input->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return; + } + auto &join = input->Cast(); + if (join.join_type != JoinType::INNER || !join.duplicate_eliminated_columns.empty()) { + return; + } + BoundColumnRefExpression reference(type, join.GetColumnBindings()[key]); + for (idx_t side = 0; side < 2; side++) { + auto index = ReferenceIndex(reference, *join.children[side]); + for (auto &condition : join.conditions) { + if (index.IsValid()) { + break; + } + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL) { + continue; + } + auto &other = side == 0 ? condition.GetRHS() : condition.GetLHS(); + auto &candidate = side == 0 ? condition.GetLHS() : condition.GetRHS(); + if (reference.Equals(other)) { + index = ReferenceIndex(candidate, *join.children[side], type); + } + } + if (index.IsValid()) { + FindScanKeySource(join.children[side], index.GetIndex(), type, extractor, context, source); + } + } +} + +static BindingReplacementGraph MaterializeRuntimeDomain(Optimizer &optimizer, unique_ptr &op, + idx_t demand_side, const LogicalCTERef &domain) { + BindingReplacementGraph replacements; + unique_ptr definition; + ColumnBindingRewrite::RewriteChild( + op, demand_side, [&](unique_ptr &child, BindingReplacementGraph &bindings) { + auto reference = make_uniq(optimizer.binder.GenerateTableIndex(), domain.cte_index, + domain.chunk_types, domain.bound_columns); + auto old_bindings = child->GetColumnBindings(); + auto new_bindings = reference->GetColumnBindings(); + for (idx_t index = 0; index < old_bindings.size(); index++) { + if (!bindings.Find(old_bindings[index])) { + bindings.Add(old_bindings[index], new_bindings[index]); + } + } + replacements.Merge(bindings); + definition = std::move(child); + child = std::move(reference); + }); + op = + make_uniq("domain_source", domain.cte_index, domain.chunk_types.size(), + std::move(definition), std::move(op), CTEMaterialize::CTE_MATERIALIZE_ALWAYS); + return replacements; +} + +bool DuplicateEliminatedDomainOptimizer::TryOptimizeRuntimeDomain(unique_ptr &op, + LogicalAggregate &aggregate, idx_t aggregate_side, + idx_t demand_index, ExpressionType comparison) { + auto &join = op->Cast(); + auto &demand = *join.children[1 - aggregate_side]; + if (!ReferencesVisibleOwners(demand, cte_scopes) || !ReferencesVisibleOwners(aggregate, cte_scopes)) { + return false; + } + RuntimeDomainSource source; + if (!TryGetRuntimeDomainSource(demand, demand_index, cte_scopes, source)) { + return false; + } + // The extractor caches by operator address: retain rejected candidates through fallback costing. + unique_ptr scan_domain; + auto owner_index = source.owner ? source.owner->table_index : optimizer.binder.GenerateTableIndex(); + RelationStatsExtractor extractor(optimizer.context, [&](TableIndex index) -> optional_ptr { + if (index == owner_index) { + return source.input; + } + auto owner = FindVisibleOwner(index, cte_scopes); + return owner ? owner->children[0].get() : nullptr; + }); + auto source_stats = extractor.Extract(*source.input); + if (!source_stats) { + return false; + } + if (source.owner) { + ScanKeySource scan_source; + auto &type = aggregate.groups[0]->GetReturnType(); + FindScanKeySource(source.owner->children[0], source.key, type, extractor, optimizer.context, scan_source); + if (scan_source.input) { + auto parameters = optimizer.binder.GetParameters(); + LogicalOperatorDeepCopy copier(optimizer.binder, parameters ? parameters->GetParametersPtr() : nullptr); + auto scan = copier.DeepCopy(*scan_source.input); + auto key = make_uniq(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); + if (TryOptimizeRuntimeRestriction(optimizer.context, costs, aggregate, demand, demand_index, scan_domain, + comparison, cte_scopes, true) != RestrictionAction::KEEP) { + return true; + } + } + } + source.input->ResolveOperatorTypes(); + auto &source_types = source.input->types; + auto key_reference = + make_uniq(optimizer.binder.GenerateTableIndex(), owner_index, source_types, + AggregateRewriteHelper::GenerateColumnNames("domain", source_types.size())); + auto &domain_reference = *key_reference; + auto key_expression = + make_uniq(source_types[source.key], key_reference->GetColumnBindings()[source.key]); + auto domain = CreateKeyDomain(optimizer, std::move(key_reference), std::move(key_expression)); + auto restriction = make_uniq(JoinType::SEMI); + restriction->conditions.emplace_back(aggregate.groups[0]->Copy(), DomainKey(*domain), comparison); + auto source_rows = static_cast(source_stats->cardinality); + // CTE readers scan the full row. A new owner also writes it and replaces the consumer with another reader. + auto source_read_write_work = (source.owner ? 1 : 3) * source_rows * static_cast(source_types.size()); + DomainCostModel costs(extractor, aggregate, source_rows, source_read_write_work); + auto action = TryOptimizeRuntimeRestriction(optimizer.context, costs, aggregate, demand, demand_index, domain, + comparison, cte_scopes); + if (action != RestrictionAction::KEEP) { + if (action == RestrictionAction::REPLACE && !source.owner) { + replacements.Merge(MaterializeRuntimeDomain(optimizer, op, 1 - aggregate_side, domain_reference)); + } + return true; + } + if (join.join_type != JoinType::SINGLE && HasRuntimeFilterTargets(aggregate)) { + return false; + } + if (!costs.IsProfitable(*restriction, *domain)) { + return false; + } + restriction->children.push_back(std::move(aggregate.children[0])); + restriction->children.push_back(std::move(domain)); + aggregate.children[0] = std::move(restriction); + if (!source.owner) { + replacements.Merge(MaterializeRuntimeDomain(optimizer, op, 1 - aggregate_side, domain_reference)); + } + return true; +} + +bool DuplicateEliminatedDomainOptimizer::TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, + idx_t condition_index) { + auto &join = op->Cast(); + auto &condition = join.conditions[condition_index]; + auto &aggregate_key = aggregate_side == 0 ? condition.GetLHS() : condition.GetRHS(); + auto &demand_key = aggregate_side == 0 ? condition.GetRHS() : condition.GetLHS(); + auto aggregate_index = ReferenceIndex(aggregate_key, *join.children[aggregate_side]); + auto demand_index = ReferenceIndex(demand_key, *join.children[1 - aggregate_side]); + if (!aggregate_index.IsValid() || !demand_index.IsValid() || + !aggregate_key.GetReturnType().EqualsIncludingCollation(demand_key.GetReturnType())) { + return false; + } + auto aggregate = FindAggregate(*join.children[aggregate_side], aggregate_index.GetIndex()); + if (!aggregate) { + return false; + } + vector>> rows; + if (!CopyFixedKeys(*join.children[1 - aggregate_side], demand_index.GetIndex(), demand_key.GetReturnType(), rows)) { + return TryOptimizeRuntimeDomain(op, *aggregate, aggregate_side, demand_index.GetIndex(), + condition.GetComparisonType()); + } + auto key_index = optimizer.binder.GenerateTableIndex(); + auto fixed = + make_uniq(key_index, vector {demand_key.GetReturnType()}, std::move(rows)); + fixed->children.push_back(make_uniq(optimizer.binder.GenerateTableIndex())); + auto key_expression = + make_uniq(demand_key.GetReturnType(), ColumnBinding(key_index, ProjectionIndex(0))); + auto domain = CreateKeyDomain(optimizer, std::move(fixed), std::move(key_expression)); + if (TryOptimizeRestriction(optimizer, *aggregate, domain, condition.GetComparisonType(), cte_scopes)) { + return true; + } + // Replacing an existing restriction keeps its filter opportunity. A new one may duplicate the consumer's work. + if (join.join_type != JoinType::SINGLE && HasRuntimeFilterTargets(*aggregate)) { + return false; + } + auto restriction = make_uniq(JoinType::SEMI); + restriction->conditions.emplace_back(aggregate->groups[0]->Copy(), DomainKey(*domain), + condition.GetComparisonType()); + RelationStatsExtractor extractor(optimizer.context); + auto key_input_rows = static_cast(domain->children[0]->Cast().expressions.size()); + DomainCostModel costs(extractor, *aggregate, key_input_rows, 0); + if (!costs.IsProfitable(*restriction, *domain)) { + return false; + } + // All analysis borrows have expired. Preserve every original binding and payload column. + restriction->children.push_back(std::move(aggregate->children[0])); + restriction->children.push_back(std::move(domain)); + aggregate->children[0] = std::move(restriction); + return true; +} + +void DuplicateEliminatedDomainOptimizer::VisitOperator(unique_ptr &op) { + replacements = BindingReplacementGraph(); + if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + return; + } + BindingReplacementGraph child_replacements; + // Visit only original children; generated domain operators are never reconsidered. + for (idx_t child_index = 0; child_index < op->children.size(); child_index++) { + auto publish_owner = op->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && child_index == 1; + if (publish_owner) { + cte_scopes.push_back(op->Cast()); + } + ColumnBindingRewrite::RewriteChild(op, child_index, + [&](unique_ptr &child, BindingReplacementGraph &bindings) { + VisitOperator(child); + bindings = std::move(replacements); + child_replacements.Merge(bindings); + }); + if (publish_owner) { + cte_scopes.pop_back(); + } + } + replacements = std::move(child_replacements); + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = op->Cast(); + bool safe_conditions = true; + LogicalOperatorVisitor::EnumerateExpressions(join, [&](const unique_ptr *expression) { + safe_conditions &= !(*expression)->CanThrow() && !(*expression)->IsVolatile(); + }); + if (safe_conditions && join.expressions.empty() && join.duplicate_eliminated_columns.empty()) { + for (idx_t condition_index = 0; condition_index < join.conditions.size(); condition_index++) { + auto &condition = join.conditions[condition_index]; + if (condition.IsComparison() && + (condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL || + condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + auto join_type = join.join_type; + auto rewritten = join_type == JoinType::INNER && TryOptimizeDomain(op, 0, condition_index); + if (!rewritten && (join_type == JoinType::INNER || join_type == JoinType::LEFT || + join_type == JoinType::SINGLE)) { + rewritten = TryOptimizeDomain(op, 1, condition_index); + } + if (rewritten) { + break; + } + } + } + } + } + if (!replacements.Empty()) { + replacements = replacements.ScopedToBoundary(op->GetColumnBindings()); + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp b/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp index d9678e000..19c79dc1e 100644 --- a/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp +++ b/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp @@ -472,7 +472,7 @@ unique_ptr GroupingSetsOptimizer::VisitReplace(BoundColumnRefExpress unique_ptr *expr_ptr) { auto entry = replacement_map.find(expr.Binding()); if (entry != replacement_map.end()) { - expr.BindingMutable() = entry->second; + return expr.WithBinding(entry->second); } return nullptr; } diff --git a/src/duckdb/src/optimizer/in_clause_rewriter.cpp b/src/duckdb/src/optimizer/in_clause_rewriter.cpp index a89ae9c39..557c1f82b 100644 --- a/src/duckdb/src/optimizer/in_clause_rewriter.cpp +++ b/src/duckdb/src/optimizer/in_clause_rewriter.cpp @@ -91,22 +91,22 @@ unique_ptr InClauseRewriter::VisitReplace(BoundOperatorExpression &e return nullptr; } D_ASSERT(root); - auto in_type = expr.GetChildrenMutable()[0]->GetReturnType(); + auto in_type = expr.GetChildren()[0]->GetReturnType(); bool is_regular_in = expr.GetExpressionType() == ExpressionType::COMPARE_IN; bool all_scalar = true; // IN clause with many children: try to generate a mark join that replaces this IN expression // we can only do this if the expressions in the expression list are scalar - for (idx_t i = 1; i < expr.GetChildrenMutable().size(); i++) { - if (!expr.GetChildrenMutable()[i]->IsFoldable()) { + for (idx_t i = 1; i < expr.GetChildren().size(); i++) { + if (!expr.GetChildren()[i]->IsFoldable()) { // non-scalar expression all_scalar = false; } } - const bool rewrite_to_join = expr.GetChildrenMutable().size() >= IN_CLAUSE_REWRITE_THRESHOLD && all_scalar; + const bool rewrite_to_join = expr.GetChildren().size() >= IN_CLAUSE_REWRITE_THRESHOLD && all_scalar; if (!rewrite_to_join) { VisitExpressionChildren(expr); } - if (expr.GetChildrenMutable().size() == 2) { + if (expr.GetChildren().size() == 2) { // only one child // IN: turn into X = 1 // NOT IN: turn into X <> 1 @@ -115,7 +115,7 @@ unique_ptr InClauseRewriter::VisitReplace(BoundOperatorExpression &e std::move(expr.GetChildrenMutable()[0]), std::move(expr.GetChildrenMutable()[1])); } if (!rewrite_to_join) { - if (expr.GetChildrenMutable()[0]->IsVolatile()) { + if (expr.GetChildren()[0]->IsVolatile()) { return nullptr; } // low amount of children or not all scalar @@ -123,7 +123,7 @@ unique_ptr InClauseRewriter::VisitReplace(BoundOperatorExpression &e // NOT IN: turn into (X <> 1 AND X <> 2 AND X <> 3 ...) auto conjunction = make_uniq(is_regular_in ? ExpressionType::CONJUNCTION_OR : ExpressionType::CONJUNCTION_AND); - for (idx_t i = 1; i < expr.GetChildrenMutable().size(); i++) { + for (idx_t i = 1; i < expr.GetChildren().size(); i++) { conjunction->GetChildrenMutable().push_back(BoundComparisonExpression::Create( is_regular_in ? ExpressionType::COMPARE_EQUAL : ExpressionType::COMPARE_NOTEQUAL, expr.GetChildrenMutable()[0]->Copy(), std::move(expr.GetChildrenMutable()[i]))); @@ -140,15 +140,15 @@ unique_ptr InClauseRewriter::VisitReplace(BoundOperatorExpression &e DataChunk chunk; chunk.Initialize(context, types); - for (idx_t i = 1; i < expr.GetChildrenMutable().size(); i++) { + for (idx_t i = 1; i < expr.GetChildren().size(); i++) { // resolve this expression to a constant Value value; - if (!ExpressionExecutor::TryEvaluateScalar(context, *expr.GetChildrenMutable()[i], value)) { + if (!ExpressionExecutor::TryEvaluateScalar(context, *expr.GetChildren()[i], value)) { // error while evaluating scalar return nullptr; } chunk.data[0].Append(value); - if (chunk.size() == STANDARD_VECTOR_SIZE || i + 1 == expr.GetChildrenMutable().size()) { + if (chunk.size() == STANDARD_VECTOR_SIZE || i + 1 == expr.GetChildren().size()) { // chunk full: append to chunk collection collection->Append(append_state, chunk); chunk.Reset(); @@ -189,8 +189,8 @@ unique_ptr InClauseRewriter::VisitReplace(BoundOperatorExpression &e ColumnBinding(mark_index, ProjectionIndex(0))); if (!is_regular_in) { // NOT IN: invert - auto invert = make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN); - invert->GetChildrenMutable().push_back(std::move(result)); + auto invert = + make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN, std::move(result)); result = std::move(invert); } return result; diff --git a/src/duckdb/src/optimizer/join_build_properties.cpp b/src/duckdb/src/optimizer/join_build_properties.cpp new file mode 100644 index 000000000..d4a032cbb --- /dev/null +++ b/src/duckdb/src/optimizer/join_build_properties.cpp @@ -0,0 +1,27 @@ +#include "duckdb/optimizer/join_build_properties.hpp" + +#include "duckdb/planner/logical_operator_repeatability.hpp" + +namespace duckdb { + +JoinBuildProperties JoinBuildProperties::Extract(LogicalOperator &op) { + JoinBuildProperties result; + result.repeatable = ClassifyLogicalOperatorRepeatability(op) == LogicalOperatorRepeatability::REPEATABLE; + switch (op.type) { + case LogicalOperatorType::LOGICAL_DELIM_GET: + case LogicalOperatorType::LOGICAL_DELIM_JOIN: + case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN: + result.correlation_sensitive = true; + break; + default: + break; + } + for (auto &child : op.children) { + auto properties = Extract(*child); + result.correlation_sensitive |= properties.correlation_sensitive; + result.repeatable &= properties.repeatable; + } + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp index d6f83ab55..158610a82 100644 --- a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp @@ -7,6 +7,7 @@ #include "duckdb/function/function_binder.hpp" #include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/function/scalar/struct_utils.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -14,6 +15,8 @@ #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression/bound_window_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_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" @@ -58,62 +61,65 @@ static bool IsJoinFilterPushdownVariantIntegralCast(const LogicalType &src, cons struct JoinFilterExpressionPath { ColumnBinding binding; JoinFilterPushdownMode mode = JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION; - vector casts; + unique_ptr input_expression; + bool has_struct_extract = false; }; -static bool PushdownJoinFilterExpressionInternal(const Expression &expr, JoinFilterExpressionPath &path) { +static void CopyJoinFilterExpression(const Expression &expr, JoinFilterExpressionPath &path) { + auto result = expr.Copy(); + result->Cast().GetChildrenMutable()[0] = std::move(path.input_expression); + path.input_expression = std::move(result); +} + +static bool PushdownJoinFilterExpressionInternal(const Expression &expr, JoinFilterExpressionPath &path, + bool allow_struct = false) { const auto &return_type = expr.GetReturnType(); - if (return_type.IsNested() && return_type.id() != LogicalTypeId::VARIANT) { - // nested columns are not supported for pushdown + if (return_type.IsNested() && return_type.id() != LogicalTypeId::VARIANT && + !(allow_struct && StructType::IsStruct(return_type))) { return false; } - if (return_type.id() == LogicalTypeId::INTERVAL) { - // interval is not supported for pushdown + if (return_type.id() == LogicalTypeId::INTERVAL || expr.IsVolatile()) { return false; } switch (expr.GetExpressionClass()) { case ExpressionClass::BOUND_COLUMN_REF: { - // column-ref - pass through the new column binding auto &colref = expr.Cast(); + if (colref.Depth() != 0) { + return false; + } path.binding = colref.Binding(); + path.input_expression = make_uniq(return_type, idx_t(0)); return true; } case ExpressionClass::BOUND_FUNCTION: { + auto &function = expr.Cast(); if (!BoundCastExpression::IsCast(expr)) { - auto &function_expr = expr.Cast(); - if (function_expr.Function().GetName() != "variant_normalize" || function_expr.GetChildren().size() != 1) { + idx_t child_idx; + if (TryGetStructExtractChildIndex(function, child_idx) && !function.GetChildren().empty() && + StructType::IsStruct(function.GetChildren()[0]->GetReturnType())) { + if (!PushdownJoinFilterExpressionInternal(*function.GetChildren()[0], path, true)) { + return false; + } + path.has_struct_extract = true; + } else { + if (function.Function().GetName() != "variant_normalize" || function.GetChildren().size() != 1 || + !PushdownJoinFilterExpressionInternal(*function.GetChildren()[0], path)) { + return false; + } + } + } else { + const auto &source = BoundCastExpression::Child(function).GetReturnType(); + const auto &target = function.GetReturnType(); + if ((!IsJoinFilterPushdownIntegralCast(source, target) && + !IsJoinFilterPushdownVariantIntegralCast(source, target)) || + !PushdownJoinFilterExpressionInternal(BoundCastExpression::Child(function), path)) { return false; } - return PushdownJoinFilterExpressionInternal(*function_expr.GetChildren()[0], path); - } - // We allow pushing through integral casts and integral/VARIANT casts. - const auto &bound_cast = expr.Cast(); - const auto &src = BoundCastExpression::Child(bound_cast).GetReturnType(); - const auto &tgt = bound_cast.GetReturnType(); - const bool integral_cast = IsJoinFilterPushdownIntegralCast(src, tgt); - const bool variant_integral_cast = IsJoinFilterPushdownVariantIntegralCast(src, tgt); - if (!integral_cast && !variant_integral_cast) { - return false; - } - if (!PushdownJoinFilterExpressionInternal(BoundCastExpression::Child(bound_cast), path)) { - return false; - } - if (variant_integral_cast) { - if (tgt.id() == LogicalTypeId::VARIANT) { + if (target.id() == LogicalTypeId::VARIANT) { path.mode = JoinFilterPushdownMode::STORAGE_ONLY; - path.casts.clear(); - } else if (path.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION) { - path.casts.emplace_back(tgt, BoundCastExpression::IsTryCast(bound_cast) - ? RuntimeFilterCastMode::TRY_CAST - : RuntimeFilterCastMode::DEFAULT_CAST); } - return true; - } - if (path.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION) { - path.casts.emplace_back(tgt, BoundCastExpression::IsTryCast(bound_cast) - ? RuntimeFilterCastMode::TRY_CAST - : RuntimeFilterCastMode::DEFAULT_CAST); } + CopyJoinFilterExpression(expr, path); return true; } default: @@ -121,21 +127,53 @@ static bool PushdownJoinFilterExpressionInternal(const Expression &expr, JoinFil } } +static bool RuntimeFilterInputMatchesType(const Expression &expr, const LogicalType &type) { + bool found_reference = false; + bool matches = true; + ExpressionIterator::VisitExpressionClass(expr, ExpressionClass::BOUND_REF, [&](const Expression &child) { + found_reference = true; + auto &ref = child.Cast(); + matches &= ref.Index() == 0 && ref.GetReturnType() == type; + }); + return found_reference && matches; +} + +static bool RuntimeFilterInputHasStructExtract(const Expression &expr) { + bool result = false; + ExpressionIterator::VisitExpressionClass(expr, ExpressionClass::BOUND_FUNCTION, [&](const Expression &child) { + idx_t child_idx; + result |= TryGetStructExtractChildIndex(child.Cast(), child_idx); + }); + return result; +} + bool JoinFilterPushdownUtil::PushdownJoinFilterExpression(const Expression &expr, JoinFilterPushdownColumn &filter) { JoinFilterExpressionPath path; - if (!PushdownJoinFilterExpressionInternal(expr, path)) { + if (!PushdownJoinFilterExpressionInternal(expr, path, filter.input_expression != nullptr)) { return false; } - filter.probe_column_index = path.binding; - if (filter.mode == JoinFilterPushdownMode::STORAGE_ONLY) { - return true; + if (filter.input_expression && !RuntimeFilterInputMatchesType(*filter.input_expression, expr.GetReturnType())) { + return false; + } + const auto storage_only = + path.mode == JoinFilterPushdownMode::STORAGE_ONLY || filter.mode == JoinFilterPushdownMode::STORAGE_ONLY; + if (storage_only && (path.has_struct_extract || + (filter.input_expression && RuntimeFilterInputHasStructExtract(*filter.input_expression)))) { + return false; } - if (path.mode == JoinFilterPushdownMode::STORAGE_ONLY) { + filter.probe_column_index = path.binding; + if (storage_only) { filter.mode = JoinFilterPushdownMode::STORAGE_ONLY; - filter.runtime_filter_casts.clear(); + filter.input_expression.reset(); return true; } - filter.runtime_filter_casts.insert(filter.runtime_filter_casts.begin(), path.casts.begin(), path.casts.end()); + if (filter.input_expression) { + auto combined = filter.input_expression->Copy(); + ExpressionFilter::ReplaceExpressionRecursive(combined, *path.input_expression); + filter.input_expression = std::move(combined); + } else { + filter.input_expression = std::move(path.input_expression); + } return true; } @@ -200,8 +238,8 @@ struct FilterColumnHash { auto result = CombineHash(Hash(column.join_filter_idx), ColumnBindingHashFunction()(column.probe_column_index)); result = CombineHash(result, column.storage_type.Hash()); result = CombineHash(result, Hash(uint8_t(column.mode))); - for (auto &cast : column.runtime_filter_casts) { - result = CombineHash(result, CombineHash(cast.target_type.Hash(), Hash(uint8_t(cast.mode)))); + if (column.input_expression) { + result = CombineHash(result, column.input_expression->Hash()); } return result; } @@ -211,16 +249,10 @@ struct FilterColumnEquality { bool operator()(const JoinFilterPushdownColumn &a, const JoinFilterPushdownColumn &b) const { if (a.join_filter_idx != b.join_filter_idx || a.probe_column_index != b.probe_column_index || a.storage_type != b.storage_type || a.mode != b.mode || - a.runtime_filter_casts.size() != b.runtime_filter_casts.size()) { + bool(a.input_expression) != bool(b.input_expression)) { return false; } - for (idx_t i = 0; i < a.runtime_filter_casts.size(); i++) { - if (a.runtime_filter_casts[i].target_type != b.runtime_filter_casts[i].target_type || - a.runtime_filter_casts[i].mode != b.runtime_filter_casts[i].mode) { - return false; - } - } - return true; + return !a.input_expression || a.input_expression->Equals(*b.input_expression); } }; @@ -252,7 +284,6 @@ static void FindScanFilterTargets(LogicalGet &get, vector accepted_columns; filter_column_set_t seen; @@ -268,13 +299,15 @@ static void FindScanFilterTargets(LogicalGet &get, vector static void SimplifyJoinFilterCastChain(ClientContext &context, JoinFilterPushdownColumn &column, ExpressionType comparison) { if (comparison != ExpressionType::COMPARE_EQUAL || column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION || - !IsJoinFilterPushdownIntegralType(column.storage_type) || column.runtime_filter_casts.size() < 2) { + !IsJoinFilterPushdownIntegralType(column.storage_type) || !column.input_expression) { return; } auto &cast_functions = CastFunctionSet::Get(context); - auto source_type = column.storage_type; - for (auto &cast : column.runtime_filter_casts) { - if (!IsJoinFilterPushdownIntegralType(cast.target_type) || - cast_functions.CanOverrideDefaultCast(source_type, cast.target_type)) { + optional_ptr current = column.input_expression.get(); + idx_t cast_count = 0; + while (BoundCastExpression::IsCast(*current)) { + auto &cast = current->Cast(); + const auto &source_type = BoundCastExpression::Child(cast).GetReturnType(); + const auto &target_type = cast.GetReturnType(); + if (!IsJoinFilterPushdownIntegralType(source_type) || !IsJoinFilterPushdownIntegralType(target_type) || + !RuntimeFilterCastUtil::IsBuiltinCast(cast) || + cast_functions.CanOverrideDefaultCast(source_type, target_type)) { return; } - source_type = cast.target_type; + cast_count++; + current = BoundCastExpression::Child(cast); } - if (cast_functions.CanOverrideDefaultCast(column.storage_type, source_type)) { + if (cast_count < 2 || current->GetExpressionClass() != ExpressionClass::BOUND_REF || + cast_functions.CanOverrideDefaultCast(column.storage_type, column.input_expression->GetReturnType())) { return; } // Successful integer casts preserve the value; extra filter matches are harmless. - auto target_type = column.runtime_filter_casts.back().target_type; - column.runtime_filter_casts.clear(); + auto target_type = column.input_expression->GetReturnType(); + column.input_expression = make_uniq(column.storage_type, idx_t(0)); if (target_type != column.storage_type) { - column.runtime_filter_casts.emplace_back(std::move(target_type), RuntimeFilterCastMode::TRY_CAST); + column.input_expression = + BoundCastExpression::AddCastToType(context, std::move(column.input_expression), target_type, true); } } @@ -801,14 +844,7 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi } } - // Even if we cannot find any table sources in which we can push down filters, - // we still initialize the aggregate states so that we have the possibility of doing a perfect hash join - // TODO: Can ExpressionType::COMPARE_NOT_DISTINCT_FROM be used with perfect hash joins? - const auto compute_aggregates_anyway = - join.join_type == JoinType::INNER && join.conditions.size() == 1 && pushdown_info->join_condition.size() == 1 && - join.conditions[0].IsComparison() && join.conditions[0].GetComparisonType() == ExpressionType::COMPARE_EQUAL && - TypeIsIntegral(join.conditions[0].GetRHS().GetReturnType().InternalType()); - if (pushdown_info->probe_info.empty() && !compute_aggregates_anyway) { + if (pushdown_info->probe_info.empty()) { // no table sources found in which we can push down filters return; } @@ -831,10 +867,8 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi pushdown_info->min_max_aggregates.push_back(std::move(aggr_expr)); } } - if (!pushdown_info->probe_info.empty()) { - const idx_t child_idx = join.children[1]->type == LogicalOperatorType::LOGICAL_DELIM_GET ? 0 : 1; - pushdown_info->build_side_has_filter = IsFiltering(join.children[child_idx]); - } + const idx_t child_idx = join.children[1]->type == LogicalOperatorType::LOGICAL_DELIM_GET ? 0 : 1; + pushdown_info->build_side_has_filter = IsFiltering(join.children[child_idx]); // set up the filter pushdown in the join itself join.filter_pushdown = std::move(pushdown_info); diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 7980c815c..0286bcb3a 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -14,21 +14,49 @@ struct DomainEstimate { DomainEstimate(); public: - idx_t GetDistinctCount() const; + idx_t GetDistinctCount(const JoinPredicate &predicate) const; bool HasReliableDistinctCount() const; idx_t GetReliableDistinctCount() const; - void Update(const DistinctCount &distinct_count); + void Update(ColumnBinding binding, const DistinctCount &distinct_count, + optional_ptr sources); + void AddSource(const JoinColumnSource &source); void Restrict(idx_t bound); private: optional estimate; + //! Row-count fallbacks apply only to predicates involving their relation. + column_binding_map_t local_fallbacks; + column_binding_set_t sources; + idx_t reliable_source_count = 0; + idx_t reliable_source_cardinality = NumericLimits::Maximum(); + vector min_max_candidates; }; DomainEstimate::DomainEstimate() { } -idx_t DomainEstimate::GetDistinctCount() const { - return estimate ? estimate->distinct_count : NumericLimits::Maximum(); +idx_t DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { + auto domain = estimate; + for (bool left : {true, false}) { + auto entry = local_fallbacks.find(predicate.GetStatsBinding(left)); + if (entry != local_fallbacks.end()) { + domain = domain ? RelationStatisticsHelper::SelectTotalDomain({*domain, entry->second}) : entry->second; + } + } + if (!domain) { + return NumericLimits::Maximum(); + } + auto result = domain->distinct_count; + if (!HasReliableDistinctCount() || reliable_source_count != 1) { + return result; + } + auto key_domain = NumericLimits::Maximum(); + for (auto candidate : min_max_candidates) { + if (candidate > result && candidate <= reliable_source_cardinality) { + key_domain = MinValue(key_domain, candidate); + } + } + return key_domain == NumericLimits::Maximum() ? result : key_domain; } bool DomainEstimate::HasReliableDistinctCount() const { @@ -44,15 +72,43 @@ idx_t DomainEstimate::GetReliableDistinctCount() const { void DomainEstimate::Restrict(idx_t bound) { D_ASSERT(estimate); + if (!estimate) { + return; + } estimate->distinct_count = MinValue(estimate->distinct_count, bound); + // the filter bound holds for every column of the class; no candidate overrides it + min_max_candidates.clear(); } -void DomainEstimate::Update(const DistinctCount &distinct_count) { - if (!estimate) { - estimate = distinct_count; +void DomainEstimate::AddSource(const JoinColumnSource &source) { + if (!sources.insert(source.binding).second) { + return; + } + if (source.domain.source == DistinctCountSource::HLL || source.domain.source == DistinctCountSource::EXACT) { + reliable_source_cardinality = MinValue(reliable_source_cardinality, source.source_cardinality); + reliable_source_count++; + } +} + +void DomainEstimate::Update(ColumnBinding binding, const DistinctCount &distinct_count, + optional_ptr column_sources) { + if (column_sources) { + AddSource(column_sources->direct); + for (auto &source : column_sources->equivalents) { + AddSource(source); + } + } else if (distinct_count.source == DistinctCountSource::CARDINALITY) { + local_fallbacks.emplace(binding, distinct_count); return; + } else if (distinct_count.source == DistinctCountSource::HLL || + distinct_count.source == DistinctCountSource::EXACT) { + // A reliable derived domain has no known source population for the uplift guard. + reliable_source_cardinality = 0; } - estimate = RelationStatisticsHelper::SelectTotalDomain({*estimate, distinct_count}); + if (column_sources && distinct_count.source == DistinctCountSource::MIN_MAX) { + min_max_candidates.push_back(MinValue(distinct_count.distinct_count, column_sources->direct.scan_cardinality)); + } + estimate = estimate ? RelationStatisticsHelper::SelectTotalDomain({*estimate, distinct_count}) : distinct_count; } struct RelationsSetToStats { @@ -70,7 +126,8 @@ struct RelationsSetToStats { struct FilterInfoWithTotalDomains { FilterInfoWithTotalDomains(JoinPredicate &predicate, RelationsSetToStats &relation_set_to_stats) - : predicate(predicate), domain_estimate(relation_set_to_stats.domain_estimate) { + : predicate(predicate), domain_estimate(relation_set_to_stats.domain_estimate), + distinct_count(domain_estimate.get().GetDistinctCount(predicate)) { } public: @@ -85,6 +142,7 @@ struct FilterInfoWithTotalDomains { public: reference predicate; reference domain_estimate; + idx_t distinct_count; }; struct SelectivitySubgraph { @@ -136,7 +194,10 @@ struct LogicalJoinStats { struct CardinalityEstimatorState { vector relation_set_stats; + vector edges; vector leaf_cardinalities; + //! Per relation, the columns that together identify a row (empty if unknown). + vector> unique_keys; vector> operators; vector boundaries; reference_map_t inner_selectivities; @@ -153,7 +214,7 @@ CardinalityEstimator::~CardinalityEstimator() { } double FilterInfoWithTotalDomains::GetDistinctCount() const { - return static_cast(domain_estimate.get().GetDistinctCount()); + return static_cast(distinct_count); } bool FilterInfoWithTotalDomains::HasReliableDistinctCount() const { @@ -307,25 +368,6 @@ bool CardinalityEstimator::IsFilterApplicable(const FilterInfo &filter, JoinRela return true; } -vector GetEdges(vector &relations_to_tdom, - JoinRelationSet &requested_set) { - vector res; - for (auto &relation_2_tdom : relations_to_tdom) { - for (auto predicate_ref : relation_2_tdom.predicates) { - auto &predicate = predicate_ref.get(); - auto &filter = predicate.GetFilter(); - if (predicate.GetJoinType() != JoinType::INNER) { - continue; - } - if (JoinRelationSet::IsSubset(requested_set, filter.set.get()) && filter.left_set != filter.right_set) { - FilterInfoWithTotalDomains new_edge(predicate, relation_2_tdom); - res.push_back(new_edge); - } - } - } - return res; -} - static optional_ptr GetEdgeEndpoint(FilterInfoWithTotalDomains &edge, JoinRelationSetManager &set_manager, bool left) { auto &filter = edge.GetFilter(); @@ -459,6 +501,31 @@ double CardinalityEstimator::GetJoinPairCap(JoinRelationSet &join_pair) { return cap == NumericLimits::Maximum() ? 0 : cap; } +double CardinalityEstimator::GetUniqueJoinPairDomain(JoinRelationSet &join_pair) { + D_ASSERT(join_pair.count == 2); + auto equality_pair = predicate_model.GetDirectEqualityPair(join_pair); + if (!equality_pair) { + return 0; + } + double domain = 0; + for (idx_t relation_index = 0; relation_index < join_pair.count; relation_index++) { + auto relation = join_pair.relations[relation_index]; + auto &equality_bindings = + relation_index == 0 ? equality_pair->first_relation_bindings : equality_pair->second_relation_bindings; + auto &unique_key = state->unique_keys.at(relation.index); + bool covered = !unique_key.empty(); + for (auto column : unique_key) { + ColumnBinding binding(TableIndex(relation.index), ProjectionIndex(column)); + covered = covered && equality_bindings.find(binding) != equality_bindings.end(); + } + if (covered) { + // Every row of this relation is a different key combination, so the other side matches at most one row. + domain = MaxValue(domain, GetNumerator(set_manager.GetJoinRelation(relation)).GetDouble()); + } + } + return domain; +} + bool CardinalityEstimator::ApplyJoinPairCap(CardinalityValue &target_selectivity, JoinRelationSet &join_pair, reference_map_t &join_pair_stats, reference_set_t &capped_join_pairs) { @@ -471,9 +538,14 @@ bool CardinalityEstimator::ApplyJoinPairCap(CardinalityValue &target_selectivity } auto &stats = it->second; auto cap = GetJoinPairCap(join_pair); - // The cap is an FK/PK heuristic. Avoid applying it to broad fact-to-fact joins where the base row count is much - // larger than any observed single-column join domain; in that case row count is a poor proxy for composite NDV. - if (!stats.CanApplyCap(cap)) { + auto unique_domain = GetUniqueJoinPairDomain(join_pair); + if (unique_domain > 0) { + // The equalities cover a key: its row count is the composite NDV, not a proxy for it. + cap = unique_domain; + } else if (!stats.CanApplyCap(cap)) { + // The cap is an FK/PK heuristic. Avoid applying it to broad fact-to-fact joins where the base row count is + // much larger than any observed single-column join domain; in that case row count is a poor proxy for + // composite NDV. return false; } auto &first_d = stats.first_distinct_count; @@ -710,9 +782,10 @@ void CardinalityEstimator::MergeDisconnectedSelectivitySubgraphs(SelectivityStat CardinalityValue CardinalityEstimator::GetSelectivity(JoinRelationSet &set) { SelectivityState selectivity_state; - auto edges = GetEdges(state->relation_set_stats, set); - for (auto &edge : edges) { - if (IsFilterApplicable(edge.GetFilter(), set) && !IsResidualFilter(edge.GetFilter())) { + for (auto &edge : state->edges) { + auto &filter = edge.GetFilter(); + if (edge.GetPredicate().GetJoinType() == JoinType::INNER && filter.left_set != filter.right_set && + IsFilterApplicable(filter, set) && !IsResidualFilter(filter)) { ProcessSelectivityEdge(edge, set, selectivity_state); } } @@ -815,28 +888,25 @@ CardinalityValue CardinalityEstimator::GetLeftJoinSelectivity(const JoinOrderOpe unordered_set accounted_predicates; reference_map_t pair_selectivities; reference_map_t pair_stats; - for (auto &domain : state->relation_set_stats) { - for (auto predicate_ref : domain.predicates) { - auto &predicate = predicate_ref.get(); - auto source = predicate.GetFilter().source_operator_index; - if (!source.IsValid() || source.GetIndex() != join_operator.index) { - continue; - } - accounted_predicates.insert(predicate.GetFilter().filter_index); - auto group = predicate.GetFilter().left_equality_group; - if (group.IsValid() && !equality_groups.insert(group.GetIndex()).second) { - continue; - } - FilterInfoWithTotalDomains edge(predicate, domain); - auto factor = CalculateInnerJoinSelectivity(CardinalityValue(1), edge); - auto pair = predicate.GetCompositeJoinPair(); - if (pair) { - pair_stats[*pair].RegisterDistinctCount(edge.GetDistinctCount()); - auto entry = pair_selectivities.emplace(*pair, CardinalityValue(1)).first; - entry->second *= factor; - } else { - selectivity *= factor; - } + for (auto &edge : state->edges) { + auto &predicate = edge.GetPredicate(); + auto source = predicate.GetFilter().source_operator_index; + if (!source.IsValid() || source.GetIndex() != join_operator.index) { + continue; + } + accounted_predicates.insert(predicate.GetFilter().filter_index); + auto group = predicate.GetFilter().left_equality_group; + if (group.IsValid() && !equality_groups.insert(group.GetIndex()).second) { + continue; + } + auto factor = CalculateInnerJoinSelectivity(CardinalityValue(1), edge); + auto pair = predicate.GetCompositeJoinPair(); + if (pair) { + pair_stats[*pair].RegisterDistinctCount(edge.GetDistinctCount()); + auto entry = pair_selectivities.emplace(*pair, CardinalityValue(1)).first; + entry->second *= factor; + } else { + selectivity *= factor; } } for (auto &entry : pair_selectivities) { @@ -872,31 +942,19 @@ static bool IsSelectivityComparison(const JoinPredicate &predicate) { predicate_class == JoinPredicateClass::LEFT_JOIN; } -static bool IsSelectivityOnlyGroup(const RelationsSetToStats &stats) { - if (stats.predicates.empty()) { - return false; +static bool SortEdges(const FilterInfoWithTotalDomains &a, const FilterInfoWithTotalDomains &b) { + // Broad comparison domains must not displace equality edges. + auto a_comparison = IsSelectivityComparison(a.GetPredicate()); + auto b_comparison = IsSelectivityComparison(b.GetPredicate()); + if (a_comparison != b_comparison) { + return b_comparison; } - for (auto &predicate : stats.predicates) { - if (!IsSelectivityComparison(predicate.get())) { - return false; - } - } - return true; -} - -bool SortTdoms(const RelationsSetToStats &a, const RelationsSetToStats &b) { - // process pure selectivity (comparison) edges last so a broad comparison domain - // cannot displace an equality domain from the denominator - auto a_selectivity_only = IsSelectivityOnlyGroup(a); - auto b_selectivity_only = IsSelectivityOnlyGroup(b); - if (a_selectivity_only != b_selectivity_only) { - return b_selectivity_only; - } - return a.domain_estimate.GetDistinctCount() > b.domain_estimate.GetDistinctCount(); + return a.GetDistinctCount() > b.GetDistinctCount(); } void CardinalityEstimator::Initialize(const vector &relations, - const vector> &operators) { + const vector> &operators, + const join_column_sources_t &sources) { D_ASSERT(state->leaf_cardinalities.empty()); InitEquivalentRelations(); for (idx_t i = 0; i < relations.size(); i++) { @@ -904,10 +962,17 @@ void CardinalityEstimator::Initialize(const vector &relations, D_ASSERT(stats.stats_initialized); auto cardinality = CardinalityValue(static_cast(stats.cardinality)); state->leaf_cardinalities.push_back(cardinality); + state->unique_keys.push_back(stats.unique_key); state->cardinalities.emplace(set_manager.GetJoinRelation(RelationIndex(i)), cardinality); - UpdateTotalDomains(RelationIndex(i), stats); + UpdateTotalDomains(RelationIndex(i), stats, sources); } RestrictFilterDomains(relations); + for (auto &domain : state->relation_set_stats) { + for (auto &predicate : domain.predicates) { + state->edges.emplace_back(predicate, domain); + } + } + std::stable_sort(state->edges.begin(), state->edges.end(), SortEdges); for (auto &op : operators) { D_ASSERT(op->index == state->operators.size()); state->operators.push_back(*op); @@ -919,20 +984,22 @@ void CardinalityEstimator::Initialize(const vector &relations, } } -void CardinalityEstimator::UpdateTotalDomains(RelationIndex relation_id, const RelationStats &stats) { +void CardinalityEstimator::UpdateTotalDomains(RelationIndex relation_id, const RelationStats &stats, + const join_column_sources_t &sources) { //! Initialize the distinct count for all columns used in joins with the current relation. for (idx_t i = 0; i < stats.columns.size(); i++) { //! for every column used in a filter in the relation, get the distinct count via HLL, or assume it to be //! the cardinality // Update the relation_to_tdom set with the estimated distinct count (or tdom) calculated above auto key = ColumnBinding(TableIndex(relation_id.index), ProjectionIndex(i)); - auto distinct_count = stats.columns[i].total_domain; + auto entry = sources.find(key); for (auto &relation_to_tdom : state->relation_set_stats) { const auto &i_set = relation_to_tdom.equivalent_relations; if (i_set.find(key) == i_set.end()) { continue; } - relation_to_tdom.domain_estimate.Update(distinct_count); + relation_to_tdom.domain_estimate.Update(key, stats.columns[i].total_domain, + entry == sources.end() ? nullptr : &entry->second); } } } @@ -951,7 +1018,7 @@ void CardinalityEstimator::RestrictFilterDomains(const vector &re break; } auto &column = relation_stats[binding.table_index.index].columns[binding.column_index.GetIndex()]; - auto bound = column.semi_anti_join_domain_evidence.GetFilterDomainBound(); + auto bound = column.semi_anti_join_domain_evidence.GetDomainBound(); // Unknown-NDV filters need their scan selectivities refined before shrinking the join domain. if (!bound.IsValid() || column.total_domain.source == DistinctCountSource::CARDINALITY) { all_filtered = false; @@ -963,7 +1030,6 @@ void CardinalityEstimator::RestrictFilterDomains(const vector &re equivalence.domain_estimate.Restrict(retained_domain); } } - std::sort(state->relation_set_stats.begin(), state->relation_set_stats.end(), SortTdoms); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/cost_model.cpp b/src/duckdb/src/optimizer/join_order/cost_model.cpp index 2b28db39f..e0b8e2390 100644 --- a/src/duckdb/src/optimizer/join_order/cost_model.cpp +++ b/src/duckdb/src/optimizer/join_order/cost_model.cpp @@ -1,5 +1,10 @@ #include "duckdb/optimizer/join_order/cost_model.hpp" +#include "duckdb/optimizer/build_probe_side_optimizer.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" +#include "duckdb/optimizer/join_order/relation_manager.hpp" +#include "duckdb/optimizer/join_order/join_predicate.hpp" +#include "duckdb/main/settings.hpp" +#include "duckdb/storage/buffer_manager.hpp" namespace duckdb { @@ -17,4 +22,91 @@ double CostModel::ComputeCost(const DPJoinNode &left, const DPJoinNode &right, return left.cost + right.cost + input_cost + output_rows; } +void CostModel::InitializeRecursiveMemory(ClientContext &context, RelationManager &relations) { + if (!relations.HasRecursiveRelations() || Settings::Get(context)) { + return; + } + for (idx_t i = 0; i < relations.NumRelations(); i++) { + if (relations.GetRelation(RelationIndex(i)).recursive_properties.build.correlation_sensitive) { + return; + } + } + recursive_relations = relations; + memory_budget = static_cast(BufferManager::GetBufferManager(context).GetOperatorMemoryLimit()); +} + +double CostModel::GetBuildSize(const DPJoinNode &node) { + auto entry = row_widths.find(node.set); + if (entry == row_widths.end()) { + vector types; + for (idx_t i = 0; i < node.set.count; i++) { + auto &relation = recursive_relations->GetRelation(node.set.relations[i]); + types.insert(types.end(), relation.op.types.begin(), relation.op.types.end()); + } + entry = row_widths.emplace(node.set, BuildProbeSideOptimizer::GetBuildSize(std::move(types), 1)).first; + } + return entry->second * node.cardinality.GetDouble(); +} + +static bool HasHashKey(const DPJoinNode &node, const DPJoinNode &left, const DPJoinNode &right) { + for (auto &predicate_ref : node.predicates) { + auto &predicate = predicate_ref.get(); + if (predicate.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + predicate.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + continue; + } + auto lhs = predicate.GetLeftSetOptional(); + auto rhs = predicate.GetRightSetOptional(); + if (!lhs || !rhs || lhs->Empty() || rhs->Empty()) { + continue; + } + if ((JoinRelationSet::IsSubset(left.set, *lhs) && JoinRelationSet::IsSubset(right.set, *rhs)) || + (JoinRelationSet::IsSubset(right.set, *lhs) && JoinRelationSet::IsSubset(left.set, *rhs))) { + return true; + } + } + return false; +} + +void CostModel::UpdateBuildMemory(DPJoinNode &result, const DPJoinNode &left, const DPJoinNode &right) { + auto &properties = result.recursive_properties; + const auto &left_properties = left.recursive_properties; + const auto &right_properties = right.recursive_properties; + properties.depends_on_recursive_input = + left_properties.depends_on_recursive_input || right_properties.depends_on_recursive_input; + properties.build.correlation_sensitive = + left_properties.build.correlation_sensitive || right_properties.build.correlation_sensitive; + properties.build.repeatable = left_properties.build.repeatable && right_properties.build.repeatable; + for (auto &predicate : result.predicates) { + properties.build.repeatable &= !predicate.get().GetFilter().filter->IsVolatile(); + } + if (!recursive_relations) { + return; + } + result.retained_build_size = left.retained_build_size + right.retained_build_size; + double build_size = 0; + if (HasHashKey(result, left, right)) { + optional_ptr build; + if (CanPlaceRecursiveProbe(JoinType::INNER, left_properties, right_properties)) { + build = right; + } else if (CanPlaceRecursiveProbe(JoinType::INNER, right_properties, left_properties)) { + build = left; + } else { + build = GetBuildSize(left) < GetBuildSize(right) ? left : right; + } + build_size = GetBuildSize(*build); + if (!build->recursive_properties.depends_on_recursive_input && build->recursive_properties.build.repeatable) { + result.retained_build_size += build_size; + } + } + result.peak_build_size = build_size + MaxValue(left.peak_build_size + right.retained_build_size, + right.peak_build_size + left.retained_build_size); +} + +JoinPlanCost CostModel::GetCost(const DPJoinNode &node) const { + // Prefer plans whose estimated live hash builds fit the configured budget. + auto excess = recursive_relations ? MaxValue(0.0, node.peak_build_size - memory_budget) : 0; + return {node.cost, excess}; +} + } // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp index 70900b51b..81c384d83 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp @@ -6,6 +6,7 @@ #include "duckdb/optimizer/join_order/cardinality_estimator.hpp" #include "duckdb/optimizer/join_order/cost_model.hpp" #include "duckdb/optimizer/join_order/plan_enumerator.hpp" +#include "duckdb/optimizer/join_order/join_order_source_stats.hpp" #include "duckdb/planner/expression/list.hpp" #include "duckdb/planner/operator/list.hpp" @@ -21,9 +22,14 @@ JoinOrderOptimizer JoinOrderOptimizer::CreateChildOptimizer() { child_optimizer.delim_scan_stats = delim_scan_stats; child_optimizer.depth = depth + 1; child_optimizer.recursive_cte_indexes = recursive_cte_indexes; + child_optimizer.source_stats = source_stats; return child_optimizer; } +const shared_ptr &JoinOrderOptimizer::GetSourceStats() const { + return source_stats; +} + unique_ptr JoinOrderOptimizer::Optimize(unique_ptr plan, optional_ptr stats) { if (depth > MAX_RECURSION_DEPTH) { @@ -34,6 +40,9 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptr(context, op); + } // extract the relations that go into the hyper graph. // We optimize the children of any non-reorderable operations we come across. @@ -49,6 +58,14 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptrtype == JoinOrderOperatorType::INNER || join->type == JoinOrderOperatorType::CROSS_PRODUCT; + } + if (inner_region) { + cost_model.InitializeRecursiveMemory(context, query_graph_manager.relation_manager); + } // Initialize a plan enumerator. auto plan_enumerator = @@ -66,7 +83,7 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptrestimated_cardinality = relation_stats.at(0).cardinality; new_logical_plan->has_estimated_cardinality = true; diff --git a/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp b/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp new file mode 100644 index 000000000..13e0b5ea0 --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp @@ -0,0 +1,219 @@ +#include "duckdb/optimizer/join_order/join_order_source_stats.hpp" + +#include "duckdb/optimizer/join_order/join_predicate.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.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/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_secure_view.hpp" + +namespace duckdb { + +JoinOrderSourceStats::JoinOrderSourceStats(ClientContext &context, LogicalOperator &root) { + AddPlan(context, root); +} + +void JoinOrderSourceStats::AddPlan(ClientContext &context, LogicalOperator &root) { + vector> pending {root}; + vector> pending_projections; + while (!pending.empty()) { + auto &op = pending.back().get(); + pending.pop_back(); + if (op.type == LogicalOperatorType::LOGICAL_GET && op.children.empty()) { + auto &get = op.Cast(); + if (scans.find(get.table_index) == scans.end()) { + auto cardinality = get.EstimateSourceCardinality(context); + auto stats = RelationStatisticsHelper::ExtractGetStats(get, context, cardinality); + scans.emplace(get.table_index, ScanStats {cardinality, std::move(stats)}); + } + } + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + pending_projections.push_back(op.Cast()); + } + for (auto &child : op.children) { + pending.push_back(*child); + } + } + // Capture children first, reusing their summaries when resolving each parent. + for (auto it = pending_projections.rbegin(); it != pending_projections.rend(); ++it) { + auto &projection = it->get(); + if (projections.find(projection.table_index) == projections.end()) { + projections.emplace(projection.table_index, Resolve(projection)); + } + } +} + +optional_ptr JoinOrderSourceStats::FindScanStats(const LogicalGet &get) const { + auto entry = scans.find(get.table_index); + return entry == scans.end() ? nullptr : optional_ptr(entry->second.stats); +} + +static idx_t SourceChildCount(LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_WINDOW: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + return op.children.size(); + case LogicalOperatorType::LOGICAL_SECURE_VIEW: + return op.Cast().propagate_statistics ? op.children.size() : 0; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + switch (op.Cast().join_type) { + case JoinType::INNER: + return 2; + case JoinType::LEFT: + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + return 1; + default: + return 0; + } + default: + return 0; + } +} + +static void AddSourceEquality(JoinEqualityGroups &groups, ExpressionType type, const Expression &left, + const Expression &right) { + if (type != ExpressionType::COMPARE_EQUAL && type != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return; + } + auto lhs = JoinOrderUtil::GetEquivalenceBinding(left); + auto rhs = JoinOrderUtil::GetEquivalenceBinding(right); + if (lhs.table_index.IsValid() && rhs.table_index.IsValid()) { + groups.AddEquality(lhs, rhs); + } +} + +static void AddSourceEqualities(JoinEqualityGroups &groups, const Expression &expression) { + if (expression.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + for (auto &child : expression.Cast().GetChildren()) { + AddSourceEqualities(groups, *child); + } + } else if (BoundComparisonExpression::IsComparison(expression)) { + auto &comparison = expression.Cast(); + AddSourceEquality(groups, expression.GetExpressionType(), BoundComparisonExpression::Left(comparison), + BoundComparisonExpression::Right(comparison)); + } +} + +static void MergeEquivalentSources(LogicalOperator &op, join_column_sources_t &inputs) { + auto is_inner = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op.Cast().join_type == JoinType::INNER; + if (!is_inner && op.type != LogicalOperatorType::LOGICAL_FILTER) { + return; + } + JoinEqualityGroups groups; + column_binding_map_t source_outputs; + for (auto &entry : inputs) { + groups.AddEquality(entry.first, entry.first); + auto first = source_outputs.emplace(entry.second.direct.binding, entry.first); + groups.AddEquality(entry.first, first.first->second); + for (auto &source : entry.second.equivalents) { + auto first = source_outputs.emplace(source.binding, entry.first); + groups.AddEquality(entry.first, first.first->second); + } + } + if (is_inner) { + for (auto &condition : op.Cast().conditions) { + if (condition.IsComparison()) { + AddSourceEquality(groups, condition.GetComparisonType(), condition.GetLHS(), condition.GetRHS()); + } + } + } else { + for (auto &expression : op.expressions) { + AddSourceEqualities(groups, *expression); + } + } + unordered_map> contributors; + for (auto &entry : inputs) { + auto &group = contributors[groups.GetGroup(entry.first)]; + group.emplace(entry.second.direct.binding, entry.second.direct); + for (auto &source : entry.second.equivalents) { + group.emplace(source.binding, source); + } + } + for (auto &entry : inputs) { + auto &group = contributors.at(groups.GetGroup(entry.first)); + entry.second.equivalents.clear(); + for (auto &source : group) { + if (source.first != entry.second.direct.binding) { + entry.second.equivalents.push_back(source.second); + } + } + } +} + +join_column_sources_t JoinOrderSourceStats::Resolve(LogicalOperator &root) const { + struct Frame { + explicit Frame(LogicalOperator &op) : op(op) { + } + + reference op; + idx_t next_child = 0; + join_column_sources_t inputs; + }; + vector stack; + stack.emplace_back(root); + while (true) { + auto &frame = stack.back(); + auto &op = frame.op.get(); + auto cached = op.type == LogicalOperatorType::LOGICAL_PROJECTION + ? projections.find(op.Cast().table_index) + : projections.end(); + if (cached == projections.end() && frame.next_child < SourceChildCount(op)) { + auto &child = *op.children[frame.next_child++]; + stack.emplace_back(child); + continue; + } + MergeEquivalentSources(op, frame.inputs); + join_column_sources_t output; + if (cached != projections.end()) { + output = cached->second; + } else if (op.type == LogicalOperatorType::LOGICAL_GET && op.children.empty()) { + auto &get = op.Cast(); + auto entry = scans.find(get.table_index); + if (entry != scans.end() && !get.extra_info.sample_options) { + auto &scan = entry->second; + for (auto &column : scan.stats.columns) { + output.emplace(column.binding, JoinColumnSources({column.binding, scan.cardinality, + scan.stats.cardinality, column.total_domain})); + } + } + } else if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto bindings = op.GetColumnBindings(); + for (idx_t i = 0; i < op.expressions.size(); i++) { + auto &expr = *op.expressions[i]; + if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + continue; + } + auto &column = expr.Cast(); + auto entry = frame.inputs.find(column.Binding()); + if (column.Depth() == 0 && entry != frame.inputs.end()) { + output.emplace(bindings[i], entry->second); + } + } + } else { + for (auto &binding : op.GetColumnBindings()) { + auto entry = frame.inputs.find(binding); + if (entry != frame.inputs.end()) { + output.emplace(binding, entry->second); + } + } + } + stack.pop_back(); + if (stack.empty()) { + return output; + } + for (auto &entry : output) { + stack.back().inputs.emplace(entry.first, std::move(entry.second)); + } + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_predicate.cpp b/src/duckdb/src/optimizer/join_order/join_predicate.cpp index f3a96bd16..318d052bc 100644 --- a/src/duckdb/src/optimizer/join_order/join_predicate.cpp +++ b/src/duckdb/src/optimizer/join_order/join_predicate.cpp @@ -10,8 +10,7 @@ namespace duckdb { ColumnBinding JoinOrderUtil::GetEquivalenceBinding(const Expression &expression) { if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { auto &colref = expression.Cast(); - D_ASSERT(colref.Depth() == 0); - return colref.Binding(); + return colref.Depth() == 0 ? colref.Binding() : ColumnBinding(); } if (BoundCastExpression::IsCast(expression)) { auto &cast = expression.Cast(); @@ -322,12 +321,17 @@ const vector &JoinPredicateModel::GetEqualityClasses() const return equality_classes; } -bool JoinPredicateModel::HasDirectCompositeEquality(JoinRelationSet &pair) const { +optional_ptr JoinPredicateModel::GetDirectEqualityPair(JoinRelationSet &pair) const { auto entry = equality_pairs.find(pair); if (entry == equality_pairs.end()) { - return false; + return nullptr; } - return entry->second.HasDirectCompositeEquality(); + return entry->second; +} + +bool JoinPredicateModel::HasDirectCompositeEquality(JoinRelationSet &pair) const { + auto summary = GetDirectEqualityPair(pair); + return summary && summary->HasDirectCompositeEquality(); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp index fbde2dfd3..a1ccc205e 100644 --- a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp +++ b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp @@ -121,6 +121,21 @@ const vector> &PlanEnumerator::GetAllNeighborRelation return inserted.first->second; } +static bool EnablesJoinKey(const JoinPredicateModel &predicates, JoinRelationSet &set, JoinRelationSet &left, + JoinRelationSet &right) { + auto needs_both_inputs = [&](optional_ptr key) { + return key && JoinRelationSet::Intersects(left, *key) && JoinRelationSet::Intersects(right, *key); + }; + for (auto &predicate_ref : predicates.GetGraphPredicates()) { + auto &predicate = predicate_ref.get(); + if (!JoinRelationSet::IsSubset(set, predicate.GetSet()) && + (needs_both_inputs(predicate.GetLeftSetOptional()) || needs_both_inputs(predicate.GetRightSetOptional()))) { + return true; + } + } + return false; +} + //! Create a new JoinTree node by joining together two previous JoinTree nodes unique_ptr PlanEnumerator::CreateJoinTree(JoinRelationSet &set, const vector> &possible_connections, @@ -183,10 +198,21 @@ unique_ptr PlanEnumerator::CreateJoinTree(JoinRelationSet &set, return nullptr; } auto cardinality = cost_model.GetCardinalityEstimator().EstimateCardinality(set); + // Avoid large expanding independent builds unless the inputs contribute to the same join key. + if (recursive_frontier_estimate > 0 && !left.recursive_properties.depends_on_recursive_input && + !right.recursive_properties.depends_on_recursive_input) { + auto output = cardinality.GetDouble(); + if (output > left.cardinality.GetDouble() && output > right.cardinality.GetDouble() && + output > recursive_frontier_estimate && + !EnablesJoinKey(query_graph_manager.GetPredicateModel(), set, left.set, right.set)) { + return nullptr; + } + } auto cost = cost_model.ComputeCost(left, right, best_candidate->join_operator, cardinality.GetDouble()); auto result = make_uniq(set, best_candidate->join_operator, std::move(best_candidate->predicates), best_candidate->generated_cross_product, left.set, right.set, cost); result->cardinality = cardinality; + cost_model.UpdateBuildMemory(*result, left, right); return result; } @@ -206,10 +232,10 @@ optional_ptr PlanEnumerator::EmitPair(JoinRelationSet &left, JoinRel } // check if this plan is the optimal plan we found for this set of relations auto entry = plans.find(new_set); - auto new_cost = new_plan->cost; - double old_cost = NumericLimits::Maximum(); + auto new_cost = cost_model.GetCost(*new_plan); + JoinPlanCost old_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; if (entry != plans.end()) { - old_cost = entry->second->cost; + old_cost = cost_model.GetCost(*entry->second); } if (entry == plans.end() || new_cost < old_cost) { // the new plan costs less than the old plan. Update our DP table. @@ -433,7 +459,7 @@ bool PlanEnumerator::SolveJoinOrderApproximately() { struct GreedyCandidate { optional_ptr left; optional_ptr right; - double cost; + JoinPlanCost cost; }; vector candidates; auto EmitOrientation = [&](JoinRelationSet &left, JoinRelationSet &right) -> optional_ptr { @@ -450,7 +476,7 @@ bool PlanEnumerator::SolveJoinOrderApproximately() { node = EmitOrientation(right, left); } if (node) { - candidates.push_back({&left, &right, node->cost}); + candidates.push_back({&left, &right, cost_model.GetCost(*node)}); } }; auto InitializeCandidates = [&]() { @@ -466,7 +492,7 @@ bool PlanEnumerator::SolveJoinOrderApproximately() { while (join_relations.size() > 1) { optional_ptr best_left; optional_ptr best_right; - double best_cost = NumericLimits::Maximum(); + JoinPlanCost best_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; for (auto &candidate : candidates) { if (!best_left || candidate.cost < best_cost) { best_cost = candidate.cost; @@ -491,7 +517,10 @@ bool PlanEnumerator::SolveJoinOrderApproximately() { auto left_plan = plans.find(left); auto right_plan = plans.find(right); D_ASSERT(left_plan != plans.end() && right_plan != plans.end()); - auto cost = left_plan->second->cost + right_plan->second->cost; + auto left_cost = cost_model.GetCost(*left_plan->second); + auto right_cost = cost_model.GetCost(*right_plan->second); + JoinPlanCost cost {left_cost.work + right_cost.work, + MaxValue(left_cost.memory_excess, right_cost.memory_excess)}; if (!best_left || cost < best_cost) { best_cost = cost; best_left = left; @@ -577,12 +606,21 @@ bool PlanEnumerator::PlanUsesCrossProduct(const DPJoinNode &node) const { void PlanEnumerator::InitLeafPlans() { auto relation_stats = query_graph_manager.relation_manager.GetRelationStats(); auto &estimator = cost_model.GetCardinalityEstimator(); - estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators()); + estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators(), + query_graph_manager.relation_manager.GetColumnSources()); for (idx_t i = 0; i < relation_stats.size(); i++) { auto &relation_set = query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i)); auto join_node = make_uniq(relation_set); join_node->cost = 0; join_node->cardinality = estimator.EstimateCardinality(relation_set); + if (query_graph_manager.relation_manager.HasRecursiveRelations()) { + auto &relation = query_graph_manager.relation_manager.GetRelation(RelationIndex(i)); + relation.op.ResolveOperatorTypes(); + join_node->recursive_properties = relation.recursive_properties; + if (join_node->recursive_properties.depends_on_recursive_input) { + recursive_frontier_estimate = MaxValue(recursive_frontier_estimate, join_node->cardinality.GetDouble()); + } + } plans[relation_set] = std::move(join_node); } } diff --git a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp index 88a21e45d..ae4b8cad4 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp @@ -1,4 +1,6 @@ #include "duckdb/optimizer/join_order/query_graph_manager.hpp" +#include "duckdb/optimizer/join_order/join_order_optimizer.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" #include "duckdb/common/assert.hpp" #include "duckdb/common/enums/join_type.hpp" @@ -248,6 +250,7 @@ void QueryGraphManager::BuildInnerCompanionSets() { } bool QueryGraphManager::Build(JoinOrderOptimizer &optimizer, LogicalOperator &op) { + relation_manager.SetSourceStats(optimizer.GetSourceStats()); // have the relation manager extract the join relations and create a reference list of all the // filter operators. auto can_reorder = relation_manager.ExtractJoinRelations(optimizer, op, filter_operators); @@ -263,6 +266,7 @@ bool QueryGraphManager::Build(JoinOrderOptimizer &optimizer, LogicalOperator &op } bool QueryGraphManager::BuildForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op) { + relation_manager.SetSourceStats(extractor.GetSourceStats(op)); if (!relation_manager.ExtractJoinRelationsForEstimation(extractor, op, filter_operators) || relation_manager.NumRelations() <= 1) { return false; diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index e80cc24c0..722f7dbbc 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -29,6 +29,15 @@ SingleJoinRelation::SingleJoinRelation(LogicalOperator &op, optional_ptr stats) { + D_ASSERT(relations.empty()); + source_stats = std::move(stats); +} + +const join_column_sources_t &RelationManager::GetColumnSources() const { + return column_sources; +} + static bool OperatorNeedsRelation(LogicalOperatorType op_type); static bool OperatorIsNonReorderable(const LogicalOperator &op); @@ -75,6 +84,66 @@ bool RelationManager::AddRelation(LogicalOperator &op, optional_ptr FindUniqueKey(LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = op.Cast(); + // An absent grouping-set list denotes the single set containing all groups. + if (aggregate.groups.empty() || aggregate.grouping_sets.size() > 1 || + (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() != aggregate.groups.size())) { + return {}; + } + vector key; + for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { + key.emplace_back(aggregate.group_index, ProjectionIndex(group_idx)); + } + return key; + } + case LogicalOperatorType::LOGICAL_FILTER: { + auto key = FindUniqueKey(*op.children[0]); + // A projection map can remove key columns. + auto bindings = op.GetColumnBindings(); + for (auto &binding : key) { + if (std::find(bindings.begin(), bindings.end(), binding) == bindings.end()) { + return {}; + } + } + return key; + } + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + vector key; + for (auto &binding : FindUniqueKey(*op.children[0])) { + optional_idx projected; + for (idx_t i = 0; i < projection.expressions.size() && !projected.IsValid(); i++) { + auto &expression = *projection.expressions[i]; + if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + expression.Cast().Binding() == binding) { + projected = i; + } + } + if (!projected.IsValid()) { + return {}; + } + key.emplace_back(projection.table_index, ProjectionIndex(projected.GetIndex())); + } + return key; + } + default: + return {}; + } +} + bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats) { D_ASSERT(!parent || parent->children.size() >= 2); if (!stats.stats_initialized || !stats.MatchesBindings(op.GetColumnBindings())) { @@ -82,7 +151,20 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr(op, parent, std::move(stats)); + if (!active_recursive_ctes.empty()) { + relation->recursive_properties = RecursiveJoinProperties::Extract(op, active_recursive_ctes); + has_recursive_relations |= relation->recursive_properties.depends_on_recursive_input; + } RelationIndex relation_id(relations.size()); + relation->stats.unique_key.clear(); + for (auto &binding : FindUniqueKey(op)) { + auto column = relation->stats.FindColumn(binding); + if (!column.IsValid()) { + relation->stats.unique_key.clear(); + break; + } + relation->stats.unique_key.push_back(column.GetIndex()); + } unordered_set relation_bindings; auto table_indexes = op.GetTableIndex(); @@ -105,6 +187,15 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptrstats); + if (source_stats) { + auto sources = source_stats->Resolve(op); + for (idx_t i = 0; i < relation->stats.columns.size(); i++) { + auto entry = sources.find(relation->stats.columns[i].binding); + if (entry != sources.end()) { + column_sources.emplace(ColumnBinding(TableIndex(relation_id.index), ProjectionIndex(i)), entry->second); + } + } + } operator_relations[op] = relation_id; relations.push_back(std::move(relation)); return true; @@ -437,6 +528,7 @@ bool RelationManager::AddRelationWithChildren(JoinOrderOptimizer &optimizer, Log bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, LogicalOperator &input_op, vector> &filter_operators, optional_ptr parent) { + active_recursive_ctes = optimizer.recursive_cte_indexes; // Keep the join-region walk off the call stack: leaf extraction has a substantial frame, and generated // plans (e.g. many DISTINCT aggregates) can contain hundreds of nested binary joins. vector pending_relations {{input_op, parent, false}}; @@ -527,7 +619,8 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto child_optimizer = optimizer.CreateChildOptimizer(); op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats); auto &aggr = op->Cast(); - auto operator_stats = RelationStatisticsHelper::ExtractAggregationStats(aggr, child_stats, context); + RelationStatsExtractor extractor(context, optimizer.GetSourceStats()); + auto operator_stats = RelationStatisticsHelper::ExtractAggregationStats(aggr, child_stats, extractor, true); if (!operator_stats) { stats_complete = false; return false; @@ -627,7 +720,8 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending RelationStats child_stats; return AddRelationWithChildren(optimizer, *op, input_op, parent, child_stats); } - auto stats = RelationStatisticsHelper::ExtractGetStats(get, context); + auto captured = source_stats ? source_stats->FindScanStats(get) : nullptr; + auto stats = captured ? *captured : RelationStatisticsHelper::ExtractGetStats(get, context); // if there is another logical filter that could not be pushed down into the // table scan, apply another selectivity. get.SetEstimatedCardinality(stats.cardinality); @@ -650,7 +744,10 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending return false; } // A projection must preserve the recursive reference's join-order restriction. - return !IsProjectedRecursiveCTERef(proj, optimizer) || RecursiveCTERefCanReorder(parent); + if (!IsProjectedRecursiveCTERef(proj, optimizer)) { + return true; + } + return RecursiveCTERefCanReorder(parent); } case LogicalOperatorType::LOGICAL_EMPTY_RESULT: { // optimize the child and copy the stats @@ -754,7 +851,9 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending dummy_aggr->grouping_sets.back().insert(ProjectionIndex(dummy_aggr->groups.size())); dummy_aggr->groups.push_back(delim_col->Copy()); } - auto lhs_delim_stats = RelationStatisticsHelper::ExtractAggregationStats(*dummy_aggr, lhs_stats, context); + RelationStatsExtractor extractor(context, optimizer.GetSourceStats()); + auto lhs_delim_stats = + RelationStatisticsHelper::ExtractAggregationStats(*dummy_aggr, lhs_stats, extractor, true); if (!lhs_delim_stats) { stats_complete = false; return false; diff --git a/src/duckdb/src/optimizer/late_materialization.cpp b/src/duckdb/src/optimizer/late_materialization.cpp index b1223c886..345159652 100644 --- a/src/duckdb/src/optimizer/late_materialization.cpp +++ b/src/duckdb/src/optimizer/late_materialization.cpp @@ -121,9 +121,10 @@ void LateMaterialization::ReplaceTopLevelTableIndex(LogicalOperator &root, Table } void LateMaterialization::ReplaceTableReferences(unique_ptr &root_expr, TableIndex new_table_index) { - ExpressionIterator::VisitExpressionMutable( - root_expr, [&](BoundColumnRefExpression &bound_column_ref, unique_ptr &expr) { - bound_column_ref.BindingMutable().table_index = new_table_index; + root_expr = ExpressionIterator::PreorderReplace( + std::move(root_expr), [&](const BoundColumnRefExpression &bound_column_ref) { + return bound_column_ref.WithBinding( + ColumnBinding(new_table_index, bound_column_ref.Binding().column_index)); }); } diff --git a/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp b/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp index 4aba67e43..5ba9834ee 100644 --- a/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp +++ b/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp @@ -269,11 +269,19 @@ static bool IsDomainCorrelationFilter(const TableFilter &filter, const TableColu return false; } auto &expression = *filter.Cast().expr; - if (expression.GetExpressionType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM || expression.IsVolatile()) { + if (expression.IsVolatile()) { return false; } vector> children; ExpressionIterator::EnumerateChildren(expression, [&](const Expression &child) { children.push_back(child); }); + // The ordinary equality in the domain SEMI already rejects NULL core keys. + if (expression.GetExpressionType() == ExpressionType::OPERATOR_IS_NOT_NULL && children.size() == 1 && + children[0].get().GetExpressionClass() == ExpressionClass::BOUND_REF) { + return true; + } + if (expression.GetExpressionType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return false; + } if (children.size() == 2 && Expression::Equals(children[0].get(), children[1].get())) { return true; } diff --git a/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp b/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp index 21fab9393..5ca4e5455 100644 --- a/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp +++ b/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp @@ -273,12 +273,13 @@ static void RebindRewriteExpression(unique_ptr &expr, if (!expr || replacement_map.empty()) { return; } - ExpressionIterator::VisitExpressionMutable( - expr, [&](BoundColumnRefExpression &colref, unique_ptr &) { + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) -> unique_ptr { auto entry = replacement_map.find(colref.Binding()); - if (entry != replacement_map.end()) { - colref.BindingMutable() = entry->second; + if (entry == replacement_map.end()) { + return nullptr; } + return colref.WithBinding(entry->second); }); } @@ -897,7 +898,7 @@ unique_ptr MultiStageAggregateRewriter::VisitReplace(BoundColumnRefE unique_ptr *expr_ptr) { auto entry = replacement_map.find(expr.Binding()); if (entry != replacement_map.end()) { - expr.BindingMutable() = entry->second; + return expr.WithBinding(entry->second); } return nullptr; } diff --git a/src/duckdb/src/optimizer/optimizer.cpp b/src/duckdb/src/optimizer/optimizer.cpp index b65d87f6a..45df21e00 100644 --- a/src/duckdb/src/optimizer/optimizer.cpp +++ b/src/duckdb/src/optimizer/optimizer.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" #include "duckdb/common/enums/optimizer_type.hpp" #include "duckdb/function/function_binder.hpp" @@ -261,6 +262,11 @@ void Optimizer::RunBuiltInOptimizers() { }); if (!CTEContainsDML(*plan)) { + RunOptimizer(OptimizerType::DUPLICATE_ELIMINATED_DOMAIN, [&]() { + DuplicateEliminatedDomainOptimizer domain_optimizer(*this); + domain_optimizer.Optimize(plan); + }); + FilterStatisticsOptimizer filter_statistics(*this); filter_statistics.Optimize(plan); } @@ -478,9 +484,11 @@ void Optimizer::RunBuiltInOptimizers() { } // rewrite row_number window function + filter on row_number to aggregate + bool topn_used_late_materialization = false; RunOptimizer(OptimizerType::TOP_N_WINDOW_ELIMINATION, [&]() { TopNWindowElimination topn_window_elimination(context, *this, &statistics_map); plan = topn_window_elimination.Optimize(std::move(plan)); + topn_used_late_materialization = topn_window_elimination.UsedLateMaterialization(); }); // remove duplicate aggregates @@ -490,8 +498,9 @@ void Optimizer::RunBuiltInOptimizers() { }); // statistics propagation removes filters, join conditions and aggregate children that it proves redundant. - // this can leave columns in a scan that nothing references any more - prune them again - if (removed_expressions) { + // this can leave columns in a scan that nothing references any more - prune them again. so does a top-N rewrite + // with late materialization, which reads the payload in a second scan + if (removed_expressions || topn_used_late_materialization) { RunOptimizer(OptimizerType::UNUSED_COLUMNS, [&]() { ClearProjectionMaps(*plan); RemoveUnusedColumns unused(*this); @@ -595,18 +604,19 @@ unique_ptr Optimizer::Optimize(unique_ptr plan return std::move(plan); } -unique_ptr Optimizer::BindScalarFunction(const Identifier &name, unique_ptr c1) { +unique_ptr Optimizer::BindScalarFunction(const Identifier &name, unique_ptr c1, + Identifier alias) { vector> children; children.push_back(std::move(c1)); - return BindScalarFunction(name, std::move(children)); + return BindScalarFunction(name, std::move(children), std::move(alias)); } unique_ptr Optimizer::BindScalarFunction(const Identifier &name, unique_ptr c1, - unique_ptr c2) { + unique_ptr c2, Identifier alias) { vector> children; children.push_back(std::move(c1)); children.push_back(std::move(c2)); - return BindScalarFunction(name, std::move(children)); + return BindScalarFunction(name, std::move(children), std::move(alias)); } unique_ptr Optimizer::BindScalarFunction(const Identifier &name, unique_ptr c1, @@ -618,10 +628,12 @@ unique_ptr Optimizer::BindScalarFunction(const Identifier &name, uni return BindScalarFunction(name, std::move(children)); } -unique_ptr Optimizer::BindScalarFunction(const Identifier &name, vector> children) { +unique_ptr Optimizer::BindScalarFunction(const Identifier &name, vector> children, + Identifier alias) { FunctionBinder binder(context); ErrorData error; - auto expr = binder.BindScalarFunction(Identifier::DefaultSchema(), name, std::move(children), error); + auto expr = binder.BindScalarFunction(Identifier::DefaultSchema(), name, std::move(children), error, false, nullptr, + std::move(alias)); if (error.HasError()) { throw InternalException("Optimizer exception - failed to bind function %s: %s", name, error.Message()); } diff --git a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp index 255b565e4..56c33f572 100644 --- a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp +++ b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp @@ -8,6 +8,8 @@ #include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" @@ -17,6 +19,8 @@ #include "duckdb/planner/expression_iterator.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_materialized_cte.hpp" #include "duckdb/planner/operator/logical_projection.hpp" namespace duckdb { @@ -114,6 +118,94 @@ static bool IsSupportedAggregate(const BoundAggregateExpression &expr) { return true; } +static bool OwnsTableIndex(const LogicalOperator &op, TableIndex table_index) { + for (auto &index : op.GetTableIndex()) { + if (index == table_index) { + return true; + } + } + return false; +} + +// The statistics of the base table column behind a binding, found through the operators that pass it on unchanged +static unique_ptr GetBaseColumnStatistics(ClientContext &context, LogicalOperator &op, + ColumnBinding binding) { + if (!OwnsTableIndex(op, binding.table_index)) { + for (auto &child : op.children) { + auto stats = GetBaseColumnStatistics(context, *child, binding); + if (stats) { + return stats; + } + } + return nullptr; + } + const auto column_index = binding.column_index.GetIndex(); + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + ColumnBinding child_binding; + if (!GetColumnBinding(*op.Cast().expressions[column_index], child_binding)) { + return nullptr; + } + return GetBaseColumnStatistics(context, *op.children[0], child_binding); + } + if (op.type != LogicalOperatorType::LOGICAL_GET) { + return nullptr; + } + auto &get = op.Cast(); + auto &column_ids = get.GetColumnIds(); + if (column_index >= column_ids.size()) { + return nullptr; + } + unique_ptr stats; + if (get.function.statistics_extended) { + TableFunctionGetStatisticsInput input(get.bind_data.get(), column_ids[column_index]); + stats = get.function.statistics_extended(context, input); + } else if (get.function.statistics) { + stats = get.function.statistics(context, get.bind_data.get(), column_ids[column_index].GetPrimaryIndex()); + } + if (stats) { + // an outer join above the scan can add NULL values + stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES); + } + return stats; +} + +// An argument that can throw is safe when the bounds of the base table columns it references prove it cannot fail +static bool ArgumentCanThrow(Optimizer &optimizer, unique_ptr &aggr, const Expression &argument) { + if (!argument.CanThrow()) { + return false; + } + column_binding_map_t> column_statistics; + ExpressionIterator::VisitExpression(argument, [&](const BoundColumnRefExpression &ref) { + if (column_statistics.find(ref.Binding()) != column_statistics.end()) { + return; + } + auto stats = GetBaseColumnStatistics(optimizer.context, *aggr->children[0], ref.Binding()); + if (stats) { + column_statistics[ref.Binding()] = std::move(stats); + } + }); + if (column_statistics.empty()) { + return true; + } + auto copy = argument.Copy(); + StatisticsPropagator propagator(optimizer, aggr); + propagator.PropagateExpressionStatistics(copy, std::move(column_statistics)); + return copy->CanThrow(); +} + +// Below an inner join a throwing argument would also run on the rows the join removes +static bool AggregateArgumentsCanThrow(Optimizer &optimizer, unique_ptr &op) { + auto &aggr = op->Cast(); + for (auto &expr : aggr.expressions) { + for (auto &child : expr->Cast().GetChildren()) { + if (ArgumentCanThrow(optimizer, op, *child)) { + return true; + } + } + } + return false; +} + static bool ContainsAggregateInput(const LogicalOperator &op) { if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { return true; @@ -408,7 +500,32 @@ static bool BindPushdownAggregates(ClientContext &context, LogicalAggregate &agg return true; } -static unique_ptr CreateLowerAggregate(LogicalAggregate &aggr, LogicalComparisonJoin &join, +//! The lower aggregate has at most one row per input row and per combination of its group values +static void CapLowerAggregateCardinality(ClientContext &context, LogicalAggregate &lower_aggr) { + auto &input = *lower_aggr.children[0]; + if (!input.has_estimated_cardinality) { + return; + } + auto cardinality = input.estimated_cardinality; + if (lower_aggr.has_estimated_cardinality) { + cardinality = MinValue(cardinality, lower_aggr.estimated_cardinality); + } + idx_t group_count = 1; + for (auto &group : lower_aggr.groups) { + ColumnBinding binding; + auto stats = GetColumnBinding(*group, binding) ? GetBaseColumnStatistics(context, input, binding) : nullptr; + auto distinct_count = stats ? stats->GetDistinctCount() : 0; + if (distinct_count == 0 || group_count > cardinality / distinct_count) { + group_count = cardinality; + break; + } + group_count *= distinct_count; + } + lower_aggr.SetEstimatedCardinality(MinValue(cardinality, group_count)); +} + +static unique_ptr CreateLowerAggregate(ClientContext &context, LogicalAggregate &aggr, + LogicalComparisonJoin &join, PartialAggregatePushdownInfo &info, vector> lower_aggregates) { auto lower_aggr = @@ -417,6 +534,7 @@ static unique_ptr CreateLowerAggregate(LogicalAggregate &aggr, lower_aggr->children.push_back(std::move(join.children[info.aggregate_side])); lower_aggr->ResolveOperatorTypes(); CopyCardinality(*lower_aggr, aggr); + CapLowerAggregateCardinality(context, *lower_aggr); return lower_aggr; } @@ -579,21 +697,72 @@ struct DoubleEagerHeuristics { static constexpr idx_t MIN_LARGE_COLLAPSE = 8; }; -static bool DEEstimateCollapse(const LogicalComparisonJoin &join, idx_t &effective_ndv) { - if (!join.has_estimated_cardinality || !join.children[0]->has_estimated_cardinality || - !join.children[1]->has_estimated_cardinality) { +static idx_t DERequiredCollapse(idx_t group_count) { + return group_count <= DoubleEagerHeuristics::MAX_SMALL_GROUP_COUNT ? DoubleEagerHeuristics::MIN_SMALL_COLLAPSE + : DoubleEagerHeuristics::MIN_LARGE_COLLAPSE; +} + +static bool DEEstimateCollapse(RelationStatsExtractor &extractor, LogicalComparisonJoin &join, + const DoubleEagerSide (&sides)[2], idx_t (&lower_cardinalities)[2], + idx_t &join_cardinality) { + if (!join.has_estimated_cardinality) { + return false; + } + // Reject selective joins before extracting their input statistics. + for (auto &child : join.children) { + if (child->has_estimated_cardinality && + static_cast(join.estimated_cardinality) < PartialAggregatePushdownHeuristics::MIN_JOIN_RETENTION * + static_cast(child->estimated_cardinality)) { + return false; + } + } + double retained_fraction = 1; + double input_cardinality = 0; + idx_t work_margin = DoubleEagerHeuristics::MIN_LARGE_COLLAPSE; + bool both_inputs_collapse = true; + for (idx_t side = 0; side < 2; side++) { + auto stats = extractor.Extract(*join.children[side]); + if (!stats) { + return false; + } + const auto cardinality = stats->cardinality; + const auto join_retains_rows = + static_cast(join.estimated_cardinality) >= + PartialAggregatePushdownHeuristics::MIN_JOIN_RETENTION * static_cast(cardinality); + if (!join_retains_rows || cardinality == 0) { + return false; + } + vector groups; + for (auto &group : sides[side].groups) { + auto column = stats->FindColumn(group->Cast().Binding()); + if (!column.IsValid()) { + return false; + } + groups.push_back(column.GetIndex()); + } + lower_cardinalities[side] = RelationStatisticsHelper::EstimateGroupCardinality(*join.children[side], *stats, + std::move(groups), extractor); + const auto min_collapse = DERequiredCollapse(lower_cardinalities[side]); + const auto input_collapses = cardinality / min_collapse >= lower_cardinalities[side]; + both_inputs_collapse &= input_collapses; + if (input_collapses) { + work_margin = MinValue(work_margin, min_collapse); + } + input_cardinality += static_cast(cardinality); + retained_fraction *= static_cast(lower_cardinalities[side]) / static_cast(cardinality); + } + // Scale the join estimate by grouping reduction without interpreting its selectivity as an NDV. + const auto cross_product = + static_cast(lower_cardinalities[0]) * static_cast(lower_cardinalities[1]); + join_cardinality = RelationStatisticsHelper::CardinalityFromDouble( + MinValue(cross_product, static_cast(join.estimated_cardinality) * retained_fraction)); + // Uneven collapse must save enough join output work to pay for aggregating both inputs. + if (!both_inputs_collapse && + static_cast(join.estimated_cardinality) < + static_cast(work_margin) * (input_cardinality + static_cast(join_cardinality))) { return false; } - const auto c0 = static_cast(MaxValue(join.children[0]->estimated_cardinality, 1)); - const auto c1 = static_cast(MaxValue(join.children[1]->estimated_cardinality, 1)); - const auto cj = static_cast(MaxValue(join.estimated_cardinality, 1)); - double ndv = MaxValue(1.0, (c0 * c1) / cj); - ndv = MinValue(ndv, MinValue(c0, c1)); - effective_ndv = MaxValue(static_cast(ndv), 1); - const auto min_collapse = effective_ndv <= DoubleEagerHeuristics::MAX_SMALL_GROUP_COUNT - ? DoubleEagerHeuristics::MIN_SMALL_COLLAPSE - : DoubleEagerHeuristics::MIN_LARGE_COLLAPSE; - return c0 >= static_cast(min_collapse) * ndv && c1 >= static_cast(min_collapse) * ndv; + return true; } static bool DECanRepeatAggregateState(const BoundAggregateExpression &aggr) { @@ -674,16 +843,21 @@ static bool DEValidateGroups(const LogicalAggregate &aggr, const unordered_set &aggregates, - const unordered_set (&side_bindings)[2], - const vector (&join_keys)[2], - const vector (&join_key_types)[2], DoubleEagerSide (&sides)[2]) { +static void DECollectLowerGroups(Optimizer &optimizer, const LogicalAggregate &aggr, + const unordered_set (&side_bindings)[2], + const vector (&join_keys)[2], + const vector (&join_key_types)[2], DoubleEagerSide (&sides)[2]) { for (idx_t s = 0; s < 2; s++) { sides[s].group_index = optimizer.binder.GenerateTableIndex(); - sides[s].aggregate_index = optimizer.binder.GenerateTableIndex(); CollectLowerSideGroups(sides[s].group_index, join_keys[s], join_key_types[s], aggr.groups, s, side_bindings, sides[s].groups, sides[s].group_map, sides[s].group_types); + } +} + +static bool DEBuildLowerSides(Optimizer &optimizer, const LogicalAggregate &aggr, + vector &aggregates, DoubleEagerSide (&sides)[2]) { + for (idx_t s = 0; s < 2; s++) { + sides[s].aggregate_index = optimizer.binder.GenerateTableIndex(); auto count_star = DEBindAggregate(optimizer.context, "count_star", {}); if (!count_star) { return false; @@ -705,15 +879,15 @@ static bool DEBuildLowerSides(Optimizer &optimizer, const LogicalAggregate &aggr return true; } -static void DECreateLowerAggregates(LogicalComparisonJoin &join, DoubleEagerSide (&sides)[2], idx_t effective_ndv, - unique_ptr (&lower)[2]) { +static void DECreateLowerAggregates(LogicalComparisonJoin &join, DoubleEagerSide (&sides)[2], + const idx_t (&lower_cardinalities)[2], unique_ptr (&lower)[2]) { for (idx_t s = 0; s < 2; s++) { lower[s] = make_uniq(sides[s].group_index, sides[s].aggregate_index, std::move(sides[s].aggregates)); lower[s]->groups = std::move(sides[s].groups); lower[s]->children.push_back(std::move(join.children[s])); lower[s]->ResolveOperatorTypes(); - lower[s]->SetEstimatedCardinality(effective_ndv); + lower[s]->SetEstimatedCardinality(lower_cardinalities[s]); } } @@ -730,7 +904,7 @@ static void DEGetCountBindings(const DoubleEagerSide (&sides)[2], const unique_p static unique_ptr DECreateJoin(DoubleEagerSide (&sides)[2], const vector (&join_keys)[2], const vector (&join_key_types)[2], - unique_ptr (&lower)[2], idx_t effective_ndv) { + unique_ptr (&lower)[2], idx_t cardinality) { auto new_join = make_uniq(JoinType::INNER); auto lower_key_expr = [&](idx_t s, idx_t k) { auto binding = sides[s].group_map.at(join_keys[s][k]); @@ -742,7 +916,7 @@ static unique_ptr DECreateJoin(DoubleEagerSide (&sides)[2 new_join->children.push_back(std::move(lower[0])); new_join->children.push_back(std::move(lower[1])); new_join->ResolveOperatorTypes(); - new_join->SetEstimatedCardinality(effective_ndv); + new_join->SetEstimatedCardinality(cardinality); return new_join; } @@ -818,11 +992,6 @@ bool PartialAggregatePushdown::TryDoubleEagerPushdown(unique_ptr side_bindings[2]; LogicalJoin::GetTableReferences(*join.children[0], side_bindings[0]); LogicalJoin::GetTableReferences(*join.children[1], side_bindings[1]); @@ -837,21 +1006,34 @@ bool PartialAggregatePushdown::TryDoubleEagerPushdown(unique_ptr optional_ptr { + auto entry = cte_definitions.find(index.index); + if (entry == cte_definitions.end()) { + return nullptr; + } + return entry->second.get().children[0].get(); + }); + if (!DEEstimateCollapse(extractor, join, sides, lower_cardinalities, join_cardinality)) { + return false; + } + if (AggregateArgumentsCanThrow(optimizer, op) || !DEBuildLowerSides(optimizer, aggr, aggregates, sides)) { return false; } unique_ptr lower[2]; - DECreateLowerAggregates(join, sides, effective_ndv, lower); + DECreateLowerAggregates(join, sides, lower_cardinalities, lower); ColumnBinding cnt_binding[2]; LogicalType cnt_type[2]; idx_t lower_group_count[2]; DEGetCountBindings(sides, lower, cnt_binding, cnt_type, lower_group_count); - auto new_join = DECreateJoin(sides, join_keys, join_key_types, lower, effective_ndv); + auto new_join = DECreateJoin(sides, join_keys, join_key_types, lower, join_cardinality); vector> upper_aggregates; if (!DECreateUpperAggregates(optimizer, aggregates, sides, *new_join, cnt_binding, cnt_type, lower_group_count, @@ -979,9 +1161,9 @@ bool PartialAggregatePushdown::TryOwnerOuterCountPushdown(unique_ptr(count_type, ColumnBinding(lower_aggregate_index, ProjectionIndex(0))); - auto count_value = make_uniq(ExpressionType::OPERATOR_COALESCE, count_type); - count_value->GetChildrenMutable().push_back(std::move(count_ref)); - count_value->GetChildrenMutable().push_back(make_uniq(Value::BIGINT(count_star ? 1 : 0))); + auto count_value = + make_uniq(ExpressionType::OPERATOR_COALESCE, count_type, std::move(count_ref), + make_uniq(Value::BIGINT(count_star ? 1 : 0))); vector> sum_children; sum_children.push_back(std::move(count_value)); auto upper_sum = DEBindAggregate(optimizer.context, "sum", std::move(sum_children)); @@ -1083,6 +1265,10 @@ bool PartialAggregatePushdown::FuseInterveningProjections(LogicalOperator &op) { } void PartialAggregatePushdown::VisitOperator(unique_ptr &op) { + if (op->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + auto &cte = op->Cast(); + cte_definitions.emplace(cte.table_index.index, cte); + } LogicalOperatorVisitor::VisitOperator(op); FuseInterveningProjections(*op); if (TryDoubleEagerPushdown(op) || TryOwnerOuterCountPushdown(op) || TryPushdownAggregate(op)) { @@ -1095,7 +1281,7 @@ unique_ptr PartialAggregatePushdown::VisitReplace(BoundColumnRefExpr unique_ptr *expr_ptr) { auto entry = replacement_map.find(expr.Binding()); if (entry != replacement_map.end()) { - expr.BindingMutable() = entry->second; + return expr.WithBinding(entry->second); } return nullptr; } @@ -1119,6 +1305,10 @@ bool PartialAggregatePushdown::TryPushdownAggregate(unique_ptr if (!PassesLowerGroupHeuristic(*aggr, info)) { 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)) { + return false; + } vector> lower_aggregates; vector> upper_aggregates; @@ -1127,7 +1317,7 @@ bool PartialAggregatePushdown::TryPushdownAggregate(unique_ptr return false; } - auto lower_aggr = CreateLowerAggregate(*aggr, *join, info, std::move(lower_aggregates)); + auto lower_aggr = CreateLowerAggregate(optimizer.context, *aggr, *join, info, std::move(lower_aggregates)); auto new_join = CreateJoin(*join, info, std::move(lower_aggr)); auto upper_aggr = CreateUpperAggregate(*aggr, std::move(new_join), info, std::move(upper_aggregates)); auto final_projection = diff --git a/src/duckdb/src/optimizer/projection_placement.cpp b/src/duckdb/src/optimizer/projection_placement.cpp index ec8c75fe4..e2023d486 100644 --- a/src/duckdb/src/optimizer/projection_placement.cpp +++ b/src/duckdb/src/optimizer/projection_placement.cpp @@ -20,6 +20,9 @@ namespace duckdb { namespace { constexpr double MINIMUM_COST_RATIO = 0.75; +//! An expression up to this cost (e.g. a comparison of a numeric column with a constant) is not moved below joins +//! unless that frees one of its inputs +constexpr idx_t MAXIMUM_CHEAP_EXPRESSION_COST = 20; struct PathStep { reference op; @@ -201,25 +204,25 @@ static bool BindingsBelongToChild(const Expression &expression, LogicalOperator static bool RewriteThroughProjection(unique_ptr &expression, LogicalProjection &projection) { bool valid = true; - ExpressionIterator::VisitExpressionMutable( - expression, [&](BoundColumnRefExpression &colref, unique_ptr &) { + expression = ExpressionIterator::PreorderReplace( + std::move(expression), [&](const BoundColumnRefExpression &colref) -> unique_ptr { if (!valid || colref.Depth() != 0 || colref.Binding().table_index != projection.table_index || colref.Binding().column_index.GetIndex() >= projection.expressions.size()) { valid = false; - return; + return nullptr; } auto &source = *projection.expressions[colref.Binding().column_index.GetIndex()]; if (source.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || source.GetReturnType() != colref.GetReturnType()) { valid = false; - return; + return nullptr; } auto &source_colref = source.Cast(); if (source_colref.Depth() != 0) { valid = false; - return; + return nullptr; } - colref.BindingMutable() = source_colref.Binding(); + return colref.WithBinding(source_colref.Binding()); }); return valid; } @@ -562,17 +565,17 @@ static ProjectionRewrite RebuildProjection(Optimizer &optimizer, } static void RewriteLiftedExpression(unique_ptr &expression, const vector &dependencies) { - ExpressionIterator::VisitExpressionMutable( - expression, [&](BoundColumnRefExpression &colref, unique_ptr &) { + expression = ExpressionIterator::PreorderReplace( + std::move(expression), [&](const BoundColumnRefExpression &colref) -> unique_ptr { if (colref.Depth() != 0) { - return; + return nullptr; } for (auto &dependency : dependencies) { if (colref.Binding() == dependency.original_binding) { - colref.BindingMutable() = dependency.current_binding; - return; + return colref.WithBinding(dependency.current_binding); } } + return nullptr; }); } @@ -775,6 +778,11 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, return false; } auto exclusive_input_width = GetExclusiveInputWidth(reading_expressions, input_bindings); + if (exclusive_input_width == 0 && ExpressionHeuristics::Cost(expression) <= MAXIMUM_CHEAP_EXPRESSION_COST) { + // the other expressions of the projection still read every input, so moving a cheap expression only adds + // a column that the joins below have to carry + return false; + } idx_t output_width; if (!GetBindingWidth(ColumnBinding(projection.table_index, ProjectionIndex(expression_index)), expression.GetReturnType(), statistics_map, output_width)) { @@ -951,8 +959,7 @@ static void ApplyPlacementGroup(Optimizer &optimizer, column_binding_map_tGetAlias(); auto replacement = make_uniq( - upper_projection.expressions[expression_index]->GetReturnType(), computed_bindings[i]); - replacement->SetAlias(std::move(alias)); + std::move(alias), upper_projection.expressions[expression_index]->GetReturnType(), computed_bindings[i]); upper_projection.expressions[expression_index] = std::move(replacement); } } diff --git a/src/duckdb/src/optimizer/pullup/pullup_projection.cpp b/src/duckdb/src/optimizer/pullup/pullup_projection.cpp index c9c940e3f..64d14c85d 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_projection.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_projection.cpp @@ -17,33 +17,21 @@ static void RevertFilterPullup(LogicalProjection &proj, vector> &proj_expressions, Expression &expr, +static void ReplaceExpressionBinding(vector> &proj_expressions, unique_ptr &expr, TableIndex proj_table_idx) { - if (expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - bool found_proj_col = false; - BoundColumnRefExpression &colref = expr.Cast(); - // find the corresponding column index in the projection expressions - for (idx_t proj_idx = 0; proj_idx < proj_expressions.size(); proj_idx++) { - auto &proj_expr = *proj_expressions[proj_idx]; - if (proj_expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - if (colref.Equals(proj_expr)) { - colref.BindingMutable().table_index = proj_table_idx; - colref.BindingMutable().column_index = ProjectionIndex(proj_idx); - found_proj_col = true; - break; - } - } - } - if (!found_proj_col) { - // Project a new column - auto new_colref = colref.Copy(); - colref.BindingMutable().table_index = proj_table_idx; - colref.BindingMutable().column_index = - ColumnBinding::PushExpression(proj_expressions, std::move(new_colref)); - } - } - ExpressionIterator::EnumerateChildren( - expr, [&](Expression &child) { return ReplaceExpressionBinding(proj_expressions, child, proj_table_idx); }); + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) { + // find the corresponding column index in the projection expressions + for (idx_t proj_idx = 0; proj_idx < proj_expressions.size(); proj_idx++) { + auto &proj_expr = *proj_expressions[proj_idx]; + if (proj_expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF && colref.Equals(proj_expr)) { + return colref.WithBinding(ColumnBinding(proj_table_idx, ProjectionIndex(proj_idx))); + } + } + // Project a new column + auto column_index = ColumnBinding::PushExpression(proj_expressions, colref.Copy()); + return colref.WithBinding(ColumnBinding(proj_table_idx, column_index)); + }); } void FilterPullup::ProjectSetOperation(LogicalProjection &proj) { @@ -57,7 +45,7 @@ void FilterPullup::ProjectSetOperation(LogicalProjection &proj) { vector> changed_filter_expressions; for (idx_t i = 0; i < filters_expr_pullup.size(); ++i) { auto copy_filter_expr = filters_expr_pullup[i]->Copy(); - ReplaceExpressionBinding(copy_proj_expressions, (Expression &)*copy_filter_expr, proj.table_index); + ReplaceExpressionBinding(copy_proj_expressions, copy_filter_expr, proj.table_index); changed_filter_expressions.push_back(std::move(copy_filter_expr)); } @@ -95,8 +83,7 @@ unique_ptr FilterPullup::PullupProjection(unique_ptr(); - D_ASSERT(colref.Depth() == 0); - - colref.BindingMutable().table_index = setop.table_index; - return; - } - ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { ReplaceFilterTableIndex(child, setop); }); +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)); + }); } unique_ptr FilterPullup::PullupSetOperation(unique_ptr op) { @@ -26,7 +23,7 @@ unique_ptr FilterPullup::PullupSetOperation(unique_ptrCast(); auto &setop = filter.children[0]->Cast(); for (idx_t i = 0; i < filter.expressions.size(); ++i) { - ReplaceFilterTableIndex(*filter.expressions[i], setop); + ReplaceFilterTableIndex(filter.expressions[i], setop); } } return op; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp index 3109bd72f..e9ef36ae6 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp @@ -11,6 +11,11 @@ namespace duckdb { +static unique_ptr RenameColumnRef(const BoundColumnRefExpression &ref, Identifier alias) { + return make_uniq(std::move(alias), ref.GetReturnType(), ref.Binding(), ref.Depth(), + ref.GetQueryLocation()); +} + /** * When a BoundColumnRefExpression that's part of expr (a filter) arrives here, its * name will be set to the projection name i.e. "other" for SELECT col as other. @@ -21,23 +26,23 @@ namespace duckdb { */ static void NormalizeColumnRefAliases(unique_ptr &expr, const LogicalGet &get) { const vector &column_ids = get.GetColumnIds(); - ExpressionIterator::VisitExpressionMutable(expr, [&](auto &ref, auto &) { + ExpressionIterator::VisitExpressionMutable(expr, [&](auto &ref, auto &slot) { const ColumnBinding &binding = ref.Binding(); if (binding.table_index != get.table_index || binding.column_index >= column_ids.size()) { return; } const ColumnIndex &col_idx = column_ids[binding.column_index]; if (!col_idx.HasPrimaryIndex()) { - ref.SetAlias(Identifier(col_idx.GetFieldName())); + slot = RenameColumnRef(ref, Identifier(col_idx.GetFieldName())); return; } const idx_t primary = col_idx.GetPrimaryIndex(); if (col_idx.IsVirtualColumn()) { if (const auto it = get.virtual_columns.find(primary); it != get.virtual_columns.end()) { - ref.SetAlias(Identifier(it->second.name.GetIdentifierName())); + slot = RenameColumnRef(ref, Identifier(it->second.name.GetIdentifierName())); } } else if (primary < get.names.size()) { - ref.SetAlias(Identifier(col_idx.GetName(get.names[primary].GetIdentifierName()))); + slot = RenameColumnRef(ref, Identifier(col_idx.GetName(get.names[primary].GetIdentifierName()))); } }); } diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp index 4c375253f..5db52b01d 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp @@ -1,3 +1,4 @@ +#include "duckdb/function/scalar/compressed_materialization_utils.hpp" #include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/binder.hpp" @@ -21,6 +22,18 @@ static bool IsVolatile(LogicalProjection &proj, const Expression &expr) { return is_volatile; } +// A compress expression only holds where it was placed, so a filter must not inline it into a position below +static bool ReferencesCompressExpression(LogicalProjection &proj, const Expression &expr) { + bool references_compress_expression = false; + ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { + D_ASSERT(colref.Depth() == 0); + if (CMUtils::CompressesInput(proj.GetExpression(colref.Binding()))) { + references_compress_expression = true; + } + }); + return references_compress_expression; +} + static bool ReferencesComputedExpression(LogicalProjection &proj, const Expression &expr) { bool references_computed_expression = false; ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { @@ -34,10 +47,7 @@ static bool ReferencesComputedExpression(LogicalProjection &proj, const Expressi } static unique_ptr CreateColumnReference(const Expression &expr, ColumnBinding binding) { - unique_ptr result = make_uniq(expr.GetReturnType(), binding); - if (!expr.GetAlias().empty()) { - result->SetAlias(expr.GetAlias()); - } + unique_ptr result = make_uniq(expr.GetAlias(), expr.GetReturnType(), binding); return result; } @@ -67,31 +77,31 @@ static void CollectReferencedProjections(LogicalProjection &proj, const Expressi static void ReplaceFilterBindings(LogicalProjection &proj, unique_ptr &expr, TableIndex lower_table_index, const vector &lower_projection_indexes) { - ExpressionIterator::VisitExpressionMutable( - expr, [&](BoundColumnRefExpression &colref, unique_ptr &) { + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) { D_ASSERT(colref.Depth() == 0); D_ASSERT(colref.Binding().table_index == proj.table_index); const auto projection_index = lower_projection_indexes[colref.Binding().column_index]; D_ASSERT(projection_index.IsValid()); - colref.BindingMutable() = ColumnBinding(lower_table_index, projection_index); + return colref.WithBinding(ColumnBinding(lower_table_index, projection_index)); }); } static void AddPassThroughColumns(unique_ptr &expr, TableIndex lower_table_index, vector> &lower_expressions, column_binding_map_t &pass_through_indexes) { - ExpressionIterator::VisitExpressionMutable( - expr, [&](BoundColumnRefExpression &colref, unique_ptr &colref_expr) { + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) -> unique_ptr { if (colref.Depth() != 0) { - return; + return nullptr; } auto entry = pass_through_indexes.find(colref.Binding()); if (entry == pass_through_indexes.end()) { const auto projection_index = ProjectionIndex(lower_expressions.size()); entry = pass_through_indexes.emplace(colref.Binding(), projection_index).first; - lower_expressions.push_back(colref_expr->Copy()); + lower_expressions.push_back(colref.Copy()); } - colref.BindingMutable() = ColumnBinding(lower_table_index, entry->second); + return colref.WithBinding(ColumnBinding(lower_table_index, entry->second)); }); } @@ -158,7 +168,8 @@ unique_ptr FilterPushdown::PushdownProjection(unique_ptr> remain_expressions; vector> split_expressions; auto stays_on_top = [&](const Filter &f) { - return IsVolatile(proj, *f.filter) || (f.filter->CanThrow() && !f.has_barrier); + return IsVolatile(proj, *f.filter) || ReferencesCompressExpression(proj, *f.filter) || + (f.filter->CanThrow() && !f.has_barrier); }; auto splits_off = [&](const Filter &f) { return projection_mode == ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS && @@ -176,9 +187,10 @@ unique_ptr FilterPushdown::PushdownProjection(unique_ptr &bindings, Filter &filter, unique_ptr &root_expr, LogicalSetOperation &setop) { - ExpressionIterator::VisitExpressionMutable( - root_expr, [&](BoundColumnRefExpression &colref, unique_ptr &expr) { + root_expr = ExpressionIterator::PreorderReplace( + std::move(root_expr), [&](const BoundColumnRefExpression &colref) { D_ASSERT(colref.Binding().table_index == setop.table_index); D_ASSERT(colref.Depth() == 0); // rewrite the binding by looking into the bound_tables list of the subquery - colref.BindingMutable() = bindings[colref.Binding().column_index]; - filter.bindings.insert(colref.Binding().table_index); + auto &new_binding = bindings[colref.Binding().column_index]; + filter.bindings.insert(new_binding.table_index); + return colref.WithBinding(new_binding); }); } diff --git a/src/duckdb/src/optimizer/recursive_join_planning.cpp b/src/duckdb/src/optimizer/recursive_join_planning.cpp new file mode 100644 index 000000000..0541b00b3 --- /dev/null +++ b/src/duckdb/src/optimizer/recursive_join_planning.cpp @@ -0,0 +1,33 @@ +#include "duckdb/optimizer/recursive_join_planning.hpp" + +#include "duckdb/planner/operator/logical_cteref.hpp" + +namespace duckdb { + +static bool ContainsActiveRecursiveReference(const LogicalOperator &op, const unordered_set &active_ctes) { + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF && active_ctes.count(op.Cast().cte_index) != 0) { + return true; + } + for (auto &child : op.children) { + if (ContainsActiveRecursiveReference(*child, active_ctes)) { + return true; + } + } + return false; +} + +RecursiveJoinProperties RecursiveJoinProperties::Extract(LogicalOperator &op, + const unordered_set &active_ctes) { + RecursiveJoinProperties result; + result.build = JoinBuildProperties::Extract(op); + result.depends_on_recursive_input = !active_ctes.empty() && ContainsActiveRecursiveReference(op, active_ctes); + return result; +} + +bool CanPlaceRecursiveProbe(JoinType type, const RecursiveJoinProperties &probe_side, + const RecursiveJoinProperties &build_side) { + return probe_side.depends_on_recursive_input && !build_side.depends_on_recursive_input && + !build_side.build.correlation_sensitive && !PropagatesBuildSide(type); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp index 1350f10e4..c8733e6db 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp @@ -6,9 +6,9 @@ DistinctCount::DistinctCount(idx_t distinct_count, DistinctCountSource source) : distinct_count(distinct_count), source(source) { } -void SemiAntiJoinDomainEvidence::TightenFilterDomainBound(idx_t bound) { - if (!filter_domain_bound.IsValid() || bound < filter_domain_bound.GetIndex()) { - filter_domain_bound = optional_idx(bound); +void SemiAntiJoinDomainEvidence::TightenDomainBound(idx_t bound) { + if (!domain_bound.IsValid() || bound < domain_bound.GetIndex()) { + domain_bound = optional_idx(bound); } } @@ -17,12 +17,12 @@ void SemiAntiJoinDomainEvidence::MarkUnique() { } void SemiAntiJoinDomainEvidence::Invalidate() { - filter_domain_bound = optional_idx(); + domain_bound = optional_idx(); is_unique = false; } -optional_idx SemiAntiJoinDomainEvidence::GetFilterDomainBound() const { - return filter_domain_bound; +optional_idx SemiAntiJoinDomainEvidence::GetDomainBound() const { + return domain_bound; } optional_idx SemiAntiJoinDomainEvidence::GetSupportedDomainSize(idx_t current_domain) const { @@ -30,9 +30,9 @@ optional_idx SemiAntiJoinDomainEvidence::GetSupportedDomainSize(idx_t current_do if (is_unique) { result = optional_idx(current_domain); } - if (filter_domain_bound.IsValid()) { - result = optional_idx(result.IsValid() ? MinValue(result.GetIndex(), filter_domain_bound.GetIndex()) - : filter_domain_bound.GetIndex()); + if (domain_bound.IsValid()) { + result = optional_idx(result.IsValid() ? MinValue(result.GetIndex(), domain_bound.GetIndex()) + : domain_bound.GetIndex()); } return result; } diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp index c3563e809..f8f7a1eda 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp @@ -4,7 +4,9 @@ #include "duckdb/planner/operator/logical_cteref.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" #include "duckdb/optimizer/join_order/query_graph_manager.hpp" +#include "duckdb/planner/operator/logical_get.hpp" namespace duckdb { @@ -15,11 +17,17 @@ RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, relation_ : context(context), cte_callback(std::move(cte_callback)) { } +RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, + shared_ptr source_stats) + : context(context), inherited_source_stats(std::move(source_stats)) { +} + optional_ptr RelationStatsExtractor::Extract(LogicalOperator &op) { auto cache_entry = cache.find(op); if (cache_entry != cache.end()) { return cache_entry->second; } + GetSourceStats(op); if (failed_operators.find(op) != failed_operators.end() || !active_operators.insert(op).second) { return nullptr; } @@ -36,6 +44,18 @@ optional_ptr RelationStatsExtractor::Extract(LogicalOperato return inserted.first->second; } +shared_ptr RelationStatsExtractor::GetSourceStats(LogicalOperator &root) { + if (inherited_source_stats) { + return inherited_source_stats; + } + if (!source_stats) { + source_stats = make_shared_ptr(context, root); + } else if (active_operators.empty()) { + source_stats->AddPlan(context, root); + } + return source_stats; +} + idx_t RelationStatsExtractor::ExtractedOperatorCount() const { return extracted_operator_count; } @@ -51,9 +71,35 @@ static bool IsInnerJoinRegion(LogicalOperator &op) { } optional RelationStatsExtractor::ExtractInternal(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_GET && op.children.empty()) { + auto captured = GetSourceStats(op)->FindScanStats(op.Cast()); + D_ASSERT(captured); + return *captured; + } if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { return ExtractCTERef(op.Cast()); } + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + if (op.HasSideEffects()) { + return {}; + } + auto &cte = op.Cast(); + // An extraction exception invalidates this extractor; restore the outer lookup on normal return. + auto outer_callback = cte_callback; + cte_callback = [&cte, outer_callback](TableIndex index) -> optional_ptr { + if (index == cte.table_index) { + return cte.children[0].get(); + } + return outer_callback ? outer_callback(index) : nullptr; + }; + optional result; + auto stats = Extract(*cte.children[1]); + if (stats) { + result = RelationStatisticsHelper::ProjectOutputStats(*stats, cte); + } + cte_callback = std::move(outer_callback); + return result; + } if (op.type == LogicalOperatorType::LOGICAL_EXPLAIN) { return RelationStatisticsHelper::ExtractExplainStats(op); } @@ -87,7 +133,7 @@ optional RelationStatsExtractor::ExtractJoinStats(LogicalOperator } auto relation_stats = graph.relation_manager.GetRelationStats(); CardinalityEstimator estimator(graph.set_manager, graph.GetPredicateModel()); - estimator.Initialize(relation_stats, graph.GetJoinOperators()); + estimator.Initialize(relation_stats, graph.GetJoinOperators(), graph.relation_manager.GetColumnSources()); unordered_set relations; for (idx_t i = 0; i < relation_stats.size(); i++) { relations.insert(RelationIndex(i)); @@ -100,14 +146,22 @@ optional RelationStatsExtractor::ExtractJoinStats(LogicalOperator return graph.CombineRelationStats(op.GetColumnBindings(), relation_stats, estimate.GetIndex()); } -optional RelationStatsExtractor::ExtractCTERef(LogicalCTERef &cte_ref) { +optional_ptr RelationStatsExtractor::GetCTEDefinition(const LogicalCTERef &cte_ref) const { if (cte_ref.is_recurring || !cte_callback) { - return {}; + return nullptr; } - auto definition = cte_callback(cte_ref.cte_index); + return cte_callback(cte_ref.cte_index); +} + +optional RelationStatsExtractor::ExtractCTERef(LogicalCTERef &cte_ref) { + auto definition = GetCTEDefinition(cte_ref); if (!definition) { return {}; } + // Inherited snapshots already contain the entire plan and remain read-only. + if (source_stats && cache.find(*definition) == cache.end()) { + source_stats->AddPlan(context, *definition); + } auto definition_stats = Extract(*definition); if (!definition_stats) { return {}; diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp index a36f3e54d..99c3862b8 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -210,8 +210,9 @@ optional RelationStatisticsHelper::ExtractProjectionStats(Logical semi_anti_join_domain_evidence = child_column->semi_anti_join_domain_evidence; } } - result.columns.emplace_back(bindings[expression_idx], distinct_count, current_domain, - Identifier(expression.GetName()), semi_anti_join_domain_evidence); + // a name would render the expression as SQL, which can cost more than running the query + result.columns.emplace_back(bindings[expression_idx], distinct_count, current_domain, Identifier(), + semi_anti_join_domain_evidence); } result.Verify(bindings); return result; @@ -226,14 +227,20 @@ idx_t RelationStatisticsHelper::EstimateDistinctCardinality(const vector(MaxValue(distinct_count.distinct_count, 1)); + largest_domain = MaxValue(largest_domain, distinct_count.distinct_count); + varying_groups += distinct_count.distinct_count > 1; } - product *= pow(0.95, static_cast(distinct_counts.size() - 1)); + if (varying_groups <= 1) { + return MinValue(largest_domain, input_cardinality); + } + product *= pow(0.95, static_cast(varying_groups - 1)); const auto multiplier = 1.0 - exp(-static_cast(input_cardinality) / product); const auto estimate = multiplier == 0 ? static_cast(input_cardinality) : product * multiplier; - auto result = MinValue(CardinalityFromDouble(estimate), input_cardinality); - return input_cardinality > 0 ? MaxValue(result, 1) : 0; + return MinValue(MaxValue(CardinalityFromDouble(estimate), largest_domain), input_cardinality); } DistinctCount RelationStatisticsHelper::EstimateCurrentDomain(const DistinctCount ¤t_domain, @@ -329,41 +336,71 @@ SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCa return {RoundSemiAntiCardinality(preserved_cardinality, selectivity), true}; } +static bool TryMapProjectionGroups(LogicalOperator &op, vector &groups) { + auto child_bindings = op.children[0]->GetColumnBindings(); + vector mapped; + for (auto index : groups) { + if (index >= op.expressions.size()) { + return false; + } + auto &expr = *op.expressions[index]; + if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return false; + } + auto binding = expr.Cast().Binding(); + auto match = std::find(child_bindings.begin(), child_bindings.end(), binding); + if (match == child_bindings.end()) { + return false; + } + mapped.push_back(idx_t(match - child_bindings.begin())); + } + groups = std::move(mapped); + return true; +} + static optional_idx EstimateUnionGroups(LogicalOperator &input, vector groups, idx_t maximum, - RelationStatsExtractor &extractor, bool use_cached_cardinality) { + RelationStatsExtractor &extractor, bool use_operator_cardinality) { + static constexpr idx_t MAX_VISITED_OPERATORS = 1024; vector, vector>> pending; pending.emplace_back(input, std::move(groups)); + idx_t visited = 0; idx_t result = 0; bool found_union = false; while (!pending.empty()) { + if (visited++ == MAX_VISITED_OPERATORS) { + // Abandon the whole refinement when shared CTE expansion exceeds the work budget. + return {}; + } auto entry = std::move(pending.back()); pending.pop_back(); - while (entry.first.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto &projection = entry.first.get(); - auto bindings = projection.children[0]->GetColumnBindings(); - vector mapped; - for (auto index : entry.second) { - auto &expr = *projection.expressions[index]; - if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - break; - } - auto binding = expr.Cast().Binding(); - auto match = std::find(bindings.begin(), bindings.end(), binding); - if (match == bindings.end()) { - break; - } - mapped.push_back(idx_t(match - bindings.begin())); + auto &op = entry.first.get(); + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && op.children.size() == 1 && + TryMapProjectionGroups(op, entry.second)) { + pending.emplace_back(*op.children[0], std::move(entry.second)); + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto definition = extractor.GetCTEDefinition(ref); + if (!definition || definition->GetColumnBindings().size() != ref.chunk_types.size()) { + return {}; } - if (mapped.size() != entry.second.size()) { - break; + pending.emplace_back(*definition, std::move(entry.second)); + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + if (op.children.size() != 2) { + return {}; } - entry.first = *projection.children[0]; - entry.second = std::move(mapped); + pending.emplace_back(*op.children[1], std::move(entry.second)); + continue; } - auto &op = entry.first.get(); if (op.type == LogicalOperatorType::LOGICAL_UNION) { found_union = true; for (auto &child : op.children) { + if (child->GetColumnBindings().size() != op.Cast().column_count) { + return {}; + } pending.emplace_back(*child, entry.second); } continue; @@ -376,9 +413,12 @@ static optional_idx EstimateUnionGroups(LogicalOperator &input, vector gr return {}; } auto cardinality = - use_cached_cardinality && op.has_estimated_cardinality ? op.estimated_cardinality : stats->cardinality; + use_operator_cardinality && op.has_estimated_cardinality ? op.estimated_cardinality : stats->cardinality; auto estimate = MinValue(cardinality, 1); for (auto index : entry.second) { + if (index >= stats->columns.size()) { + return {}; + } auto domain = MaxValue(stats->columns[index].current_domain.distinct_count, 1); if (estimate > cardinality / domain) { estimate = cardinality; @@ -388,29 +428,61 @@ static optional_idx EstimateUnionGroups(LogicalOperator &input, vector gr } result += MinValue(estimate, maximum - result); } - return optional_idx(result); + return result; +} + +idx_t RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, + vector groups, RelationStatsExtractor &extractor, + bool use_operator_cardinality) { + vector counts; + for (auto index : groups) { + auto count = input_stats.columns[index].current_domain; + count.distinct_count = MaxValue(count.distinct_count, 1); + counts.push_back(count); + } + auto estimate = EstimateDistinctCardinality(counts, input_stats.cardinality); + auto union_groups = + EstimateUnionGroups(input, std::move(groups), input_stats.cardinality, extractor, use_operator_cardinality); + if (union_groups.IsValid()) { + // Per-arm domain products avoid inventing cross-arm combinations of grouping keys. + estimate = MinValue(estimate, union_groups.GetIndex()); + } + return estimate; } static optional ExtractAggregationStatsInternal(LogicalAggregate &aggregate, const RelationStats &child_stats, RelationStatsExtractor &extractor, - bool use_cached_cardinality) { + bool use_operator_cardinality) { RelationColumnStatsLookup child_columns(child_stats); vector cardinality_counts; + auto add_group = [&](const Expression &group, vector &counts) { + if (group.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return true; + } + auto column = child_columns.Find(group.Cast().Binding()); + if (!column) { + return false; + } + auto count = column->current_domain; + count.distinct_count = MaxValue(count.distinct_count, 1); + counts.push_back(count); + return true; + }; + // An absent grouping-set list denotes the single set containing all groups. + if (aggregate.grouping_sets.empty()) { + for (auto &group : aggregate.groups) { + if (!add_group(*group, cardinality_counts)) { + return {}; + } + } + } for (auto &grouping_set : aggregate.grouping_sets) { vector set_counts; for (auto group_idx : grouping_set) { - auto &group = aggregate.GetGroupExpression(group_idx); - if (group.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - continue; - } - auto column = child_columns.Find(group.Cast().Binding()); - if (!column) { + if (!add_group(aggregate.GetGroupExpression(group_idx), set_counts)) { return {}; } - auto count = column->current_domain; - count.distinct_count = MaxValue(count.distinct_count, 1); - set_counts.push_back(count); } if (set_counts.size() > cardinality_counts.size()) { cardinality_counts = std::move(set_counts); @@ -418,27 +490,25 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate } RelationStats result; - result.cardinality = - aggregate.groups.empty() - ? 1 - : RelationStatisticsHelper::EstimateDistinctCardinality(cardinality_counts, child_stats.cardinality); result.table_name = Identifier(aggregate.GetName()); result.stats_initialized = true; auto bindings = aggregate.GetColumnBindings(); auto preserves_group_evidence = - aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size(); + aggregate.grouping_sets.empty() || + (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size()); if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1 && cardinality_counts.size() == aggregate.groups.size()) { vector groups; for (auto &group : aggregate.groups) { groups.push_back(child_stats.FindColumn(group->Cast().Binding()).GetIndex()); } - auto union_groups = EstimateUnionGroups(*aggregate.children[0], std::move(groups), child_stats.cardinality, - extractor, use_cached_cardinality); - if (union_groups.IsValid()) { - // Per-arm domain products avoid inventing cross-arm combinations of grouping keys. - result.cardinality = MinValue(result.cardinality, union_groups.GetIndex()); - } + result.cardinality = RelationStatisticsHelper::EstimateGroupCardinality( + *aggregate.children[0], child_stats, std::move(groups), extractor, use_operator_cardinality); + } else { + result.cardinality = + aggregate.groups.empty() + ? 1 + : RelationStatisticsHelper::EstimateDistinctCardinality(cardinality_counts, child_stats.cardinality); } for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { auto &group = *aggregate.groups[group_idx]; @@ -459,17 +529,16 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate current_domain = child_stats.GetColumnStats(group.Cast().Binding())->current_domain; } - if (aggregate.groups.size() == 1 && aggregate.grouping_sets.size() == 1 && - aggregate.grouping_sets[0].size() == 1 && aggregate.grouping_sets[0].count(ProjectionIndex(0)) > 0) { + if (aggregate.groups.size() == 1 && preserves_group_evidence) { semi_anti_join_domain_evidence.MarkUnique(); } - result.columns.emplace_back(bindings[result.columns.size()], distinct_count, current_domain, - Identifier(group.GetName()), semi_anti_join_domain_evidence); + // a name would render the group as SQL, which can cost more than running the query + result.columns.emplace_back(bindings[result.columns.size()], distinct_count, current_domain, Identifier(), + semi_anti_join_domain_evidence); } - for (auto &expression : aggregate.expressions) { + 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(expression->GetName())); + DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), 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)); @@ -492,8 +561,9 @@ optional RelationStatisticsHelper::ExtractAggregationStats(Logica optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, - RelationStatsExtractor &extractor) { - return ExtractAggregationStatsInternal(aggregate, child_stats, extractor, false); + RelationStatsExtractor &extractor, + bool use_operator_cardinality) { + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor, use_operator_cardinality); } optional RelationStatisticsHelper::ExtractWindowStats(LogicalWindow &window, 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 e1b9f51ec..26e9042bf 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp @@ -363,7 +363,7 @@ static void ApplyFilterDomainCap(RelationColumnStats &column, optional_idx cap) } column.current_domain = DistinctCount(MinValue(column.current_domain.distinct_count, cap.GetIndex()), DistinctCountSource::CARDINALITY); - column.semi_anti_join_domain_evidence.TightenFilterDomainBound(cap.GetIndex()); + column.semi_anti_join_domain_evidence.TightenDomainBound(cap.GetIndex()); } static void ApplyDirectFilterDomain(RelationColumnStats &column, const Expression &expression, @@ -385,8 +385,12 @@ unique_ptr RelationStatisticsHelper::GetColumnStatistics(Logical } RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientContext &context) { + return ExtractGetStats(get, context, get.EstimateSourceCardinality(context)); +} + +RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientContext &context, + idx_t base_table_cardinality) { RelationStats result; - auto base_table_cardinality = get.EstimateSourceCardinality(context); result.cardinality = base_table_cardinality; result.row_retention = base_table_cardinality == 0 ? 0 : 1; result.table_name = get.GetTable() ? get.GetTable()->name : Identifier(get.GetName()); @@ -508,6 +512,10 @@ RelationStats RelationStatisticsHelper::ExtractExpressionGetStats(LogicalExpress for (auto &binding : expression_get.GetColumnBindings()) { result.columns.emplace_back(binding, DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), Identifier("expression_get_column")); + if (expression_get.children.size() == 1 && + expression_get.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + result.columns.back().semi_anti_join_domain_evidence.TightenDomainBound(expression_get.expressions.size()); + } } result.Verify(expression_get.GetColumnBindings()); return result; @@ -522,6 +530,7 @@ RelationStats RelationStatisticsHelper::ExtractColumnDataGetStats(LogicalColumnD for (auto &binding : column_data_get.GetColumnBindings()) { result.columns.emplace_back(binding, DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), Identifier("column_data")); + result.columns.back().semi_anti_join_domain_evidence.TightenDomainBound(result.cardinality); } result.Verify(column_data_get.GetColumnBindings()); return result; diff --git a/src/duckdb/src/optimizer/remove_unused_columns.cpp b/src/duckdb/src/optimizer/remove_unused_columns.cpp index 468fa39e0..02059896f 100644 --- a/src/duckdb/src/optimizer/remove_unused_columns.cpp +++ b/src/duckdb/src/optimizer/remove_unused_columns.cpp @@ -218,9 +218,10 @@ idx_t BaseColumnPruner::ReplaceBinding(ColumnBinding current_binding, ColumnBind } else { //! No pushdown extract, just rewrite the existing bindings for (auto &colref_p : col.bindings) { - auto &colref = colref_p.get(); + auto &colref_slot = colref_p.get(); + auto &colref = colref_slot->Cast(); D_ASSERT(colref.Binding() == current_binding); - colref.BindingMutable() = new_binding; + colref_slot = colref.WithBinding(new_binding); } created_bindings = 1; } @@ -642,10 +643,11 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { if (colrefs == column_references.end()) { continue; } + auto lhs_binding = lhs_col.Binding(); for (auto &entry : colrefs->second.bindings) { - auto &colref = entry.get(); - colref.BindingMutable() = lhs_col.Binding(); - AddBinding(colref); + auto &colref_slot = entry.get(); + colref_slot = colref_slot->Cast().WithBinding(lhs_binding); + AddBinding(colref_slot); } column_references.erase(rhs_col.Binding()); } @@ -1089,17 +1091,15 @@ void RemoveUnusedColumns::WritePushdownExtractColumns( auto return_type = expr->GetReturnType(); - auto &colref = col.bindings[struct_extract.bindings_idx]; - auto old_binding = colref.get().Binding(); + auto &colref = col.bindings[struct_extract.bindings_idx].get()->Cast(); + auto old_binding = colref.Binding(); auto source = root.active_secure_views.empty() ? nullptr : expr->Copy(); - auto colref_copy = colref.get().Copy(); - expr = std::move(colref_copy); - auto &new_expr = expr->Cast(); - new_expr.SetReturnType(return_type); auto column_index = callback(*entry, component.cast ? &(*component.cast)->GetReturnType() : nullptr); - new_expr.BindingMutable().column_index = column_index; - RecordSecureViewReplacement(old_binding, new_expr.Binding(), std::move(source)); + auto new_binding = ColumnBinding(old_binding.table_index, column_index); + expr = make_uniq(colref.GetAlias(), return_type, new_binding, colref.Depth(), + colref.GetQueryLocation()); + RecordSecureViewReplacement(old_binding, new_binding, std::move(source)); } } @@ -1176,8 +1176,7 @@ void RemoveUnusedColumns::RewriteExpressions(LogicalProjection &proj, idx_t expr return new_binding_entry->second; } // binding does not exist - create it - auto target = make_uniq(column_type, original_binding); - target->SetAlias(expr.GetAlias()); + auto target = make_uniq(expr.GetAlias(), column_type, original_binding); auto new_extract = ConstructStructExtractFromPath(context, std::move(target), extract_path); if (cast_type) { auto cast = BoundCastExpression::AddCastToType(context, std::move(new_extract), *cast_type); @@ -1559,8 +1558,7 @@ BaseColumnPrunerMode BaseColumnPruner::GetMode() const { return mode; } -bool BaseColumnPruner::HandleStructExtract(unique_ptr &expr_p, - optional_ptr &colref, +bool BaseColumnPruner::HandleStructExtract(unique_ptr &expr_p, optional_ptr> &colref, reference &path_ref, vector &expressions) { auto &function = expr_p->Cast(); @@ -1574,7 +1572,7 @@ bool BaseColumnPruner::HandleStructExtract(unique_ptr &expr_p, if (ref.GetReturnType().id() != LogicalTypeId::STRUCT) { return false; } - colref = &ref; + colref = &child; auto &path = path_ref.get(); path.AddChildIndex(ColumnIndex(bind_data.index)); path_ref = path.GetChildIndex(0); @@ -1594,7 +1592,7 @@ bool BaseColumnPruner::HandleStructExtract(unique_ptr &expr_p, } bool BaseColumnPruner::HandleVariantExtract(unique_ptr &expr_p, - optional_ptr &colref, + optional_ptr> &colref, reference &path_ref, vector &expressions) { auto &function = expr_p->Cast(); @@ -1612,7 +1610,7 @@ bool BaseColumnPruner::HandleVariantExtract(unique_ptr &expr_p, if (ref.GetReturnType().id() != LogicalTypeId::VARIANT) { return false; } - colref = &ref; + colref = &child; auto &path = path_ref.get(); path.AddChildIndex(ColumnIndex(bind_data.component.key)); @@ -1635,7 +1633,7 @@ bool BaseColumnPruner::HandleVariantExtract(unique_ptr &expr_p, } bool BaseColumnPruner::HandleExtractRecursive(unique_ptr &expr_p, - optional_ptr &colref, + optional_ptr> &colref, reference &path_ref, vector &expressions) { auto &expr = *expr_p; @@ -1673,7 +1671,7 @@ static bool ExtractCastCanBePushedDown(const BoundColumnRefExpression &colref, c bool BaseColumnPruner::HandleExtractExpression(unique_ptr *expression, optional_ptr> cast_expression) { - optional_ptr colref; + optional_ptr> colref; vector expressions; ColumnIndex path(0); @@ -1681,7 +1679,8 @@ bool BaseColumnPruner::HandleExtractExpression(unique_ptr *expressio if (!HandleExtractRecursive(*expression, colref, path_ref, expressions)) { return false; } - if (cast_expression && !ExtractCastCanBePushedDown(*colref, **cast_expression)) { + if (cast_expression && + !ExtractCastCanBePushedDown((*colref)->Cast(), **cast_expression)) { // the cast stays on top of the pushed-down extract cast_expression = nullptr; } @@ -1695,6 +1694,10 @@ bool BaseColumnPruner::HandleExtractExpression(unique_ptr *expressio return true; } +static ColumnBinding ColRefBinding(const unique_ptr &col) { + return col->Cast().Binding(); +} + void BaseColumnPruner::MergeChildColumns(vector ¤t_child_columns, ColumnIndex &new_child_column) { if (current_child_columns.empty()) { // there's already a reference to the full column - we can't extract only a subfield @@ -1735,14 +1738,14 @@ void BaseColumnPruner::MergeChildColumns(vector ¤t_child_colu current_child_columns.push_back(std::move(new_child_column)); } -void BaseColumnPruner::AddBinding(BoundColumnRefExpression &col, ColumnIndex child_column) { - auto entry = column_references.find(col.Binding()); +void BaseColumnPruner::AddBinding(unique_ptr &col, ColumnIndex child_column) { + auto entry = column_references.find(ColRefBinding(col)); if (entry == column_references.end()) { // column not referenced yet - add a binding to it entirely ReferencedColumn column; column.bindings.push_back(col); column.child_columns.push_back(std::move(child_column)); - entry = column_references.emplace(make_pair(col.Binding(), std::move(column))).first; + entry = column_references.emplace(make_pair(ColRefBinding(col), std::move(column))).first; } else { // column reference already exists - check add the binding auto &column = entry->second; @@ -1790,10 +1793,10 @@ void ReferencedColumn::AddPath(const ColumnIndex &path) { unique_paths.emplace(path); } -void BaseColumnPruner::AddBinding(BoundColumnRefExpression &col, ColumnIndex child_column, +void BaseColumnPruner::AddBinding(unique_ptr &col, ColumnIndex child_column, const vector &parent) { AddBinding(col, child_column); - auto entry = column_references.find(col.Binding()); + auto entry = column_references.find(ColRefBinding(col)); if (entry == column_references.end()) { throw InternalException("ColumnBinding for the col was somehow not added by the previous step?"); } @@ -1808,11 +1811,11 @@ void BaseColumnPruner::AddBinding(BoundColumnRefExpression &col, ColumnIndex chi std::move(child_column)); } -void BaseColumnPruner::AddBinding(BoundColumnRefExpression &col) { - auto entry = column_references.find(col.Binding()); +void BaseColumnPruner::AddBinding(unique_ptr &col) { + auto entry = column_references.find(ColRefBinding(col)); if (entry == column_references.end()) { // column not referenced yet - add a binding to it entirely - column_references[col.Binding()].bindings.push_back(col); + column_references[ColRefBinding(col)].bindings.push_back(col); } else { // column reference already exists - add the binding and clear any sub-references auto &column = entry->second; @@ -1827,7 +1830,8 @@ static bool TryGetCastChild(unique_ptr &expr, optional_ptrCast(); - if (BoundCastExpression::IsTryCast(cast)) { + //! A pushed-down cast runs on every row of the child, including rows that are later filtered out + if (BoundCastExpression::IsTryCast(cast) || cast.CanThrow()) { return false; } child = BoundCastExpression::ChildMutable(cast); @@ -1835,21 +1839,9 @@ static bool TryGetCastChild(unique_ptr &expr, optional_ptr *expression) { - if ((*expression)->GetExpressionType() == ExpressionType::OPERATOR_TRY || - (*expression)->GetExpressionType() == ExpressionType::OPERATOR_HAS_ERROR) { - const auto was_inside_try = inside_try; - inside_try = true; - LogicalOperatorVisitor::VisitExpression(expression); - inside_try = was_inside_try; - return; - } - - //! Check if this is a struct extract wrapped in a cast. TRY_CAST is already - //! skipped by TryGetCastChild. A throwing CAST under TRY must also stay put: - //! unused-columns would otherwise emit CAST(struct_extract) in a child - //! projection and leave TRY wrapping only the already-cast column (#25236). + //! Check if this is a struct extract wrapped in a cast optional_ptr> cast_child; - if (!inside_try && TryGetCastChild(*expression, cast_child)) { + if (TryGetCastChild(*expression, cast_child)) { if (HandleExtractExpression(cast_child.get(), expression)) { // already handled return; @@ -1868,7 +1860,7 @@ void BaseColumnPruner::VisitExpression(unique_ptr *expression) { unique_ptr BaseColumnPruner::VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) { // add a reference to the entire column - AddBinding(expr); + AddBinding(*expr_ptr); return nullptr; } diff --git a/src/duckdb/src/optimizer/row_group_pruner.cpp b/src/duckdb/src/optimizer/row_group_pruner.cpp index 3b76f64e2..9a9dc4e25 100644 --- a/src/duckdb/src/optimizer/row_group_pruner.cpp +++ b/src/duckdb/src/optimizer/row_group_pruner.cpp @@ -143,11 +143,8 @@ optional_ptr RowGroupPruner::FindLogicalGet(const LogicalOrder &logi } auto &pushed_column = pushdown_targets[0].columns[0]; - if (pushed_column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION || - RuntimeFilterCastUtil::RuntimeFilterUsesTryCast(pushed_column)) { - // the sort key reaches the scan through a cast chain that does not preserve the raw column's - // ordering (an explicit TRY_CAST, or a cast that can throw) - ordering row groups by the raw - // column statistics would be incorrect - bail out + if (!RuntimeFilterCastUtil::PreservesStorageOrdering(pushed_column)) { + // Field extractions and casts that can fail cannot use the raw column's ordering statistics. return nullptr; } diff --git a/src/duckdb/src/optimizer/rule/case_simplification.cpp b/src/duckdb/src/optimizer/rule/case_simplification.cpp index 5bfc5ccd4..07355db43 100644 --- a/src/duckdb/src/optimizer/rule/case_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/case_simplification.cpp @@ -14,7 +14,7 @@ CaseSimplificationRule::CaseSimplificationRule(ExpressionRewriter &rewriter) : R unique_ptr CaseSimplificationRule::Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, bool is_root) { auto &root = bindings[0].get().Cast(); - for (idx_t i = 0; i < root.CaseChecksMutable().size(); i++) { + for (idx_t i = 0; i < root.CaseChecks().size(); i++) { auto &case_check = root.CaseChecksMutable()[i]; if (case_check.when_expr->IsFoldable()) { // the WHEN check is a foldable expression @@ -37,12 +37,12 @@ unique_ptr CaseSimplificationRule::Apply(LogicalOperator &op, vector root.ElseMutable() = std::move(case_check.then_expr); // remove this case check and any case checks after this one root.CaseChecksMutable().erase(root.CaseChecksMutable().begin() + NumericCast(i), - root.CaseChecksMutable().end()); + root.CaseChecks().end()); break; } } } - if (root.CaseChecksMutable().empty()) { + if (root.CaseChecks().empty()) { // no case checks left: return the ELSE expression return Expression::PreserveReturnType(root.GetReturnType(), std::move(root.ElseMutable())); } diff --git a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp index 042b900d9..983cdc3ca 100644 --- a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp @@ -162,8 +162,7 @@ static unique_ptr SimplifyEqualityCastComparison(ClientContext &cont static unique_ptr CreateNullCheckExpression(ExpressionType expression_type, unique_ptr child) { D_ASSERT(expression_type == ExpressionType::OPERATOR_IS_NULL || expression_type == ExpressionType::OPERATOR_IS_NOT_NULL); - auto result = make_uniq(expression_type, LogicalType::BOOLEAN); - result->GetChildrenMutable().push_back(std::move(child)); + auto result = make_uniq(expression_type, LogicalType::BOOLEAN, std::move(child)); return std::move(result); } diff --git a/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp b/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp index b7300921d..32d1cf177 100644 --- a/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp @@ -17,14 +17,14 @@ ConjunctionSimplificationRule::ConjunctionSimplificationRule(ExpressionRewriter unique_ptr ConjunctionSimplificationRule::RemoveExpression(BoundConjunctionExpression &conj, const Expression &expr) { - for (idx_t i = 0; i < conj.GetChildrenMutable().size(); i++) { - if (conj.GetChildrenMutable()[i].get() == &expr) { + for (idx_t i = 0; i < conj.GetChildren().size(); i++) { + if (conj.GetChildren()[i].get() == &expr) { // erase the expression conj.GetChildrenMutable().erase_at(i); break; } } - if (conj.GetChildrenMutable().size() == 1) { + if (conj.GetChildren().size() == 1) { // one expression remaining: simply return that expression and erase the conjunction return std::move(conj.GetChildrenMutable()[0]); } diff --git a/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp b/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp index d94a72573..4e136f420 100644 --- a/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp +++ b/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp @@ -67,8 +67,8 @@ unique_ptr ContainsToInClauseRule::Apply(LogicalOperator &op, vector return nullptr; } - auto in_expr = make_uniq(ExpressionType::COMPARE_IN, LogicalType::BOOLEAN); - in_expr->GetChildrenMutable().push_back(probe_arg->Copy()); + auto in_expr = + make_uniq(ExpressionType::COMPARE_IN, LogicalType::BOOLEAN, probe_arg->Copy()); for (auto &v : non_null_elements) { in_expr->GetChildrenMutable().push_back(make_uniq(std::move(v))); } diff --git a/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp b/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp index 787a721ba..906148deb 100644 --- a/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/rule/date_trunc_simplification.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/enums/expression_type.hpp" @@ -88,6 +89,13 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v auto &column_side = col_is_lhs ? left : right; auto &constant_side = col_is_lhs ? right : left; + // the rewrites rely on built-in casts inverting date_trunc - a registered cast need not + if (CastFunctionSet::Get(rewriter.context) + .CanOverrideDefaultCast(rhs.GetReturnType(), column_part.GetReturnType()) || + !CreateTrunc(date_part, rhs, rhs.GetReturnType())) { + return nullptr; + } + // date_trunc preserves temporal infinities, so only remove the function call. if (IsInfinity(rhs.GetValue())) { ReplaceDateTruncWithColumn(column_side, constant_side, column_part); @@ -131,8 +139,8 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v { // First check if we can just return `column IS NULL`. if (rhs_comparison_type == ExpressionType::COMPARE_NOT_DISTINCT_FROM && rhs.GetValue().IsNull()) { - auto op = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - op->GetChildrenMutable().push_back(column_part.Copy()); + auto op = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, + column_part.Copy()); return std::move(op); } else { if (!is_truncated) { @@ -164,9 +172,8 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v auto comp = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(gteq), std::move(lt)); - auto isnotnull = - make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - isnotnull->GetChildrenMutable().push_back(column_part.Copy()); + auto isnotnull = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, + LogicalType::BOOLEAN, column_part.Copy()); return make_uniq(ExpressionType::CONJUNCTION_AND, std::move(comp), std::move(isnotnull)); @@ -203,9 +210,8 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v { if (rhs_comparison_type == ExpressionType::COMPARE_DISTINCT_FROM && rhs.GetValue().IsNull()) { // Return 'column IS NOT NULL'. - auto op = - make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - op->GetChildrenMutable().push_back(column_part.Copy()); + auto op = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, + column_part.Copy()); return std::move(op); } else { if (!is_truncated) { @@ -237,9 +243,8 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v auto comp = make_uniq(ExpressionType::CONJUNCTION_OR, std::move(gteq), std::move(lt)); - auto isnull = - make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - isnull->GetChildrenMutable().push_back(column_part.Copy()); + auto isnull = make_uniq(ExpressionType::OPERATOR_IS_NULL, + LogicalType::BOOLEAN, column_part.Copy()); return make_uniq(ExpressionType::CONJUNCTION_OR, std::move(comp), std::move(isnull)); @@ -378,7 +383,10 @@ unique_ptr DateTruncSimplificationRule::CreateTrunc(const BoundConst // Ensure that the RHS type matches the column type. if (trunc->GetReturnType().id() != return_type.id()) { - trunc = BoundCastExpression::AddDefaultCastToType(std::move(trunc), return_type, true); + if (CastFunctionSet::Get(rewriter.context).CanOverrideDefaultCast(trunc->GetReturnType(), return_type)) { + return nullptr; + } + trunc = BoundCastExpression::AddCastToType(rewriter.context, std::move(trunc), return_type, true); } if (trunc->IsFoldable()) { @@ -429,7 +437,10 @@ unique_ptr DateTruncSimplificationRule::CreateTruncAdd(const BoundCo // Ensure that the RHS type matches the column type. if (trunc->GetReturnType().id() != return_type.id()) { - trunc = BoundCastExpression::AddDefaultCastToType(std::move(trunc), return_type, true); + if (CastFunctionSet::Get(rewriter.context).CanOverrideDefaultCast(trunc->GetReturnType(), return_type)) { + return nullptr; + } + trunc = BoundCastExpression::AddCastToType(rewriter.context, std::move(trunc), return_type, true); } if (trunc->IsFoldable()) { @@ -493,7 +504,7 @@ void DateTruncSimplificationRule::ReplaceDateTruncWithColumn(unique_ptr DateTruncSimplificationRule::CastAndEvaluate(unique_ptr rhs, const LogicalType &return_type) { - auto cast = BoundCastExpression::AddDefaultCastToType(std::move(rhs), return_type, true); + auto cast = BoundCastExpression::AddCastToType(rewriter.context, std::move(rhs), return_type, true); if (cast->IsFoldable()) { Value result; if (!ExpressionExecutor::TryEvaluateScalar(rewriter.context, *cast, result)) { diff --git a/src/duckdb/src/optimizer/rule/distributivity.cpp b/src/duckdb/src/optimizer/rule/distributivity.cpp index 2763c9c63..14a2d3c13 100644 --- a/src/duckdb/src/optimizer/rule/distributivity.cpp +++ b/src/duckdb/src/optimizer/rule/distributivity.cpp @@ -18,7 +18,7 @@ void DistributivityRule::AddExpressionSet(Expression &expr, expression_set_t &se // a volatile conjunct in two branches is two evaluations, so it is never common to the branches if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { auto &and_expr = expr.Cast(); - for (auto &child : and_expr.GetChildrenMutable()) { + for (auto &child : and_expr.GetChildren()) { if (!child->IsVolatile()) { set.insert(*child); } @@ -35,14 +35,14 @@ unique_ptr DistributivityRule::ExtractExpression(BoundConjunctionExp if (child->GetExpressionType() == ExpressionType::CONJUNCTION_AND) { // AND, remove expression from the list auto &and_expr = child->Cast(); - for (idx_t i = 0; i < and_expr.GetChildrenMutable().size(); i++) { - if (and_expr.GetChildrenMutable()[i]->Equals(expr)) { + for (idx_t i = 0; i < and_expr.GetChildren().size(); i++) { + if (and_expr.GetChildren()[i]->Equals(expr)) { result = std::move(and_expr.GetChildrenMutable()[i]); and_expr.GetChildrenMutable().erase_at(i); break; } } - if (and_expr.GetChildrenMutable().size() == 1) { + if (and_expr.GetChildren().size() == 1) { conj.GetChildrenMutable()[idx] = std::move(and_expr.GetChildrenMutable()[0]); } } @@ -66,13 +66,13 @@ unique_ptr DistributivityRule::Apply(LogicalOperator &op, vector DistributivityRule::Apply(LogicalOperator &op, vector(ExpressionType::CONJUNCTION_AND); for (auto &expr : candidate_set) { - D_ASSERT(initial_or.GetChildrenMutable().size() > 0); + D_ASSERT(initial_or.GetChildren().size() > 0); // extract the expression from the first child of the OR auto result = ExtractExpression(initial_or, 0, expr.get()); // now for the subsequent expressions, simply remove the expression - for (idx_t i = 1; i < initial_or.GetChildrenMutable().size(); i++) { + for (idx_t i = 1; i < initial_or.GetChildren().size(); i++) { ExtractExpression(initial_or, i, *result); } // now we add the expression to the new root @@ -108,9 +108,9 @@ unique_ptr DistributivityRule::Apply(LogicalOperator &op, vectorGetChildrenMutable().size() <= 1) { + for (idx_t i = 0; i < initial_or.GetChildren().size(); i++) { + if (!initial_or.GetChildren()[i]) { + if (new_root->GetChildren().size() <= 1) { return std::move(new_root->GetChildrenMutable()[0]); } else { return std::move(new_root); @@ -118,10 +118,10 @@ unique_ptr DistributivityRule::Apply(LogicalOperator &op, vectorGetChildrenMutable().push_back(std::move(initial_or.GetChildrenMutable()[0])); - } else if (initial_or.GetChildrenMutable().size() > 1) { + } else if (initial_or.GetChildren().size() > 1) { // multiple children still remain: push them into a new OR and add that to the new root auto new_or = make_uniq(ExpressionType::CONJUNCTION_OR); for (auto &child : initial_or.GetChildrenMutable()) { @@ -130,7 +130,7 @@ unique_ptr DistributivityRule::Apply(LogicalOperator &op, vectorGetChildrenMutable().push_back(std::move(new_or)); } // finally return the new root - if (new_root->GetChildrenMutable().size() == 1) { + if (new_root->GetChildren().size() == 1) { return std::move(new_root->GetChildrenMutable()[0]); } return std::move(new_root); diff --git a/src/duckdb/src/optimizer/rule/empty_needle_removal.cpp b/src/duckdb/src/optimizer/rule/empty_needle_removal.cpp index c7e606f96..3e62c251f 100644 --- a/src/duckdb/src/optimizer/rule/empty_needle_removal.cpp +++ b/src/duckdb/src/optimizer/rule/empty_needle_removal.cpp @@ -50,6 +50,10 @@ unique_ptr EmptyNeedleRemovalRule::Apply(LogicalOperator &op, vector if (root.Function().GetName() == "||") { return TryRemoveEmptyStringConcat(GetContext(), root); } + auto &input_expr = bindings[1].get(); + if (input_expr.GetReturnType().InternalType() != PhysicalType::VARCHAR) { + return nullptr; + } auto &prefix_expr = bindings[2].get(); // the constant_expr is a scalar expression that we have to fold diff --git a/src/duckdb/src/optimizer/rule/enum_comparison.cpp b/src/duckdb/src/optimizer/rule/enum_comparison.cpp index c9eff1040..a19dc3e42 100644 --- a/src/duckdb/src/optimizer/rule/enum_comparison.cpp +++ b/src/duckdb/src/optimizer/rule/enum_comparison.cpp @@ -1,5 +1,6 @@ #include "duckdb/optimizer/rule/enum_comparison.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -52,6 +53,16 @@ unique_ptr EnumComparisonRule::Apply(LogicalOperator &op, vector(); auto &right_child = bindings[3].get().Cast(); + // the rewrite relies on the built-in enum casts - a registered cast need not match by label + auto &casts = CastFunctionSet::Get(GetContext()); + auto &left_type = BoundCastExpression::Child(left_child).GetReturnType(); + auto &right_type = BoundCastExpression::Child(right_child).GetReturnType(); + if (casts.CanOverrideDefaultCast(left_type, left_child.GetReturnType()) || + casts.CanOverrideDefaultCast(right_type, right_child.GetReturnType()) || + casts.CanOverrideDefaultCast(left_type, right_type)) { + return nullptr; + } + if (!AreMatchesPossible(BoundCastExpression::Child(left_child).GetReturnType(), BoundCastExpression::Child(right_child).GetReturnType())) { vector> children; @@ -65,8 +76,8 @@ unique_ptr EnumComparisonRule::Apply(LogicalOperator &op, vector SimplifyEqualityCast(ClientContext &context, Bound unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, bool is_root) { auto &expr = bindings[0].get().Cast(); - if (!BoundCastExpression::IsCast(*expr.GetChildrenMutable()[0])) { + if (!BoundCastExpression::IsCast(*expr.GetChildren()[0])) { return nullptr; } auto &cast_expression = expr.GetChildrenMutable()[0]->Cast(); @@ -77,12 +77,12 @@ unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, ve } vector> cast_list; //! First check if we can cast all children - for (size_t i = 1; i < expr.GetChildrenMutable().size(); i++) { - if (expr.GetChildrenMutable()[i]->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + for (size_t i = 1; i < expr.GetChildren().size(); i++) { + if (expr.GetChildren()[i]->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { return nullptr; } - D_ASSERT(expr.GetChildrenMutable()[i]->IsFoldable()); - auto constant_value = ExpressionExecutor::EvaluateScalar(GetContext(), *expr.GetChildrenMutable()[i]); + D_ASSERT(expr.GetChildren()[i]->IsFoldable()); + auto constant_value = ExpressionExecutor::EvaluateScalar(GetContext(), *expr.GetChildren()[i]); if (!BoundCastExpression::CastIsInvertible(constant_value.type(), target_type)) { return nullptr; } @@ -95,7 +95,7 @@ unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, ve } } //! We can cast, so we move the new constant - for (size_t i = 1; i < expr.GetChildrenMutable().size(); i++) { + for (size_t i = 1; i < expr.GetChildren().size(); i++) { expr.GetChildrenMutable()[i] = std::move(cast_list[i - 1]); // expr->children[i] = std::move(new_constant_expr); diff --git a/src/duckdb/src/optimizer/rule/join_dependent_filter.cpp b/src/duckdb/src/optimizer/rule/join_dependent_filter.cpp index 624e29b1a..d6b73c5a6 100644 --- a/src/duckdb/src/optimizer/rule/join_dependent_filter.cpp +++ b/src/duckdb/src/optimizer/rule/join_dependent_filter.cpp @@ -129,7 +129,7 @@ unique_ptr JoinDependentFilterRule::Apply(LogicalOperator &op, vecto derived_filter->GetChildrenMutable().push_back(std::move(derived_entry_filter)); } - if (derived_filter->GetChildrenMutable().empty()) { + if (derived_filter->GetChildren().empty()) { return nullptr; // Could not derive filters that can be pushed down } @@ -138,7 +138,7 @@ unique_ptr JoinDependentFilterRule::Apply(LogicalOperator &op, vecto auto &result_conjunction = result->Cast(); result_conjunction.GetChildrenMutable().push_back(conjunction.Copy()); - if (derived_filter->GetChildrenMutable().size() == 1) { + if (derived_filter->GetChildren().size() == 1) { result_conjunction.GetChildrenMutable().push_back(std::move(derived_filter->GetChildrenMutable()[0])); } else { result_conjunction.GetChildrenMutable().push_back(std::move(derived_filter)); diff --git a/src/duckdb/src/optimizer/rule/like_optimizations.cpp b/src/duckdb/src/optimizer/rule/like_optimizations.cpp index 77aac2cf3..06ce72548 100644 --- a/src/duckdb/src/optimizer/rule/like_optimizations.cpp +++ b/src/duckdb/src/optimizer/rule/like_optimizations.cpp @@ -195,8 +195,8 @@ unique_ptr LikeOptimizationRule::ApplyRule(BoundFunctionExpression & return std::move(result); } - auto negation = make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN); - negation->GetChildrenMutable().push_back(std::move(result)); + auto negation = + make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN, std::move(result)); return std::move(negation); } diff --git a/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp b/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp index ee4356164..12ca6113b 100644 --- a/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp +++ b/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp @@ -79,12 +79,11 @@ bool UsesIndexParameter(Expression &expr) { } void RemoveIndexInputSlot(unique_ptr &expr) { - ExpressionIterator::VisitExpressionClassMutable(expr, ExpressionClass::BOUND_REF, - [&](unique_ptr &child) { - auto &ref = child->Cast(); - D_ASSERT(ref.Index() > 0); - ref.IndexMutable()--; - }); + expr = ExpressionIterator::PreorderReplace(std::move(expr), + [&](const BoundReferenceExpression &ref) { + D_ASSERT(ref.Index() > 0); + return ref.WithIndex(ref.Index() - 1); + }); } bool MatchesStructFieldProjection(Expression &expr, const string &field_name, bool allow_boolean_cast = false) { diff --git a/src/duckdb/src/optimizer/rule/move_constants.cpp b/src/duckdb/src/optimizer/rule/move_constants.cpp index 6b1e7afc7..857e0e6ac 100644 --- a/src/duckdb/src/optimizer/rule/move_constants.cpp +++ b/src/duckdb/src/optimizer/rule/move_constants.cpp @@ -66,11 +66,13 @@ unique_ptr MoveConstantsRule::Apply(LogicalOperator &op, vector(Value(comparison.GetReturnType())); } + const bool constant_is_left = RefersToSameObject(BoundComparisonExpression::Left(comparison), outer_constant); + Value new_constant; auto &constant_type = outer_constant.GetReturnType(); hugeint_t outer_value = IntegralValue::Get(outer_constant.GetValue()); hugeint_t inner_value = IntegralValue::Get(inner_constant.GetValue()); - idx_t arithmetic_child_index = arithmetic.GetChildrenMutable()[0].get() == &inner_constant ? 1 : 0; + idx_t arithmetic_child_index = arithmetic.GetChildren()[0].get() == &inner_constant ? 1 : 0; auto &op_type = arithmetic.Function().GetName(); if (op_type == "+") { // [x + 1 COMP 10] OR [1 + x COMP 10] @@ -91,7 +93,7 @@ unique_ptr MoveConstantsRule::Apply(LogicalOperator &op, vector MoveConstantsRule::Apply(LogicalOperator &op, vector MoveConstantsRule::Apply(LogicalOperator &op, vector 2] BoundComparisonExpression::FlipType(comparison); @@ -180,15 +182,18 @@ unique_ptr MoveConstantsRule::Apply(LogicalOperator &op, vector CreateIsNanCall(ClientContext &context, const Expr } static unique_ptr CreateNotIsNanGuard(ClientContext &context, const Expression &expr) { - auto not_isnan = make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN); - not_isnan->GetChildrenMutable().push_back(CreateIsNanCall(context, expr)); + auto not_isnan = make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN, + CreateIsNanCall(context, expr)); return std::move(not_isnan); } @@ -270,6 +275,8 @@ unique_ptr MoveUnaryMinusRule::Apply(LogicalOperator &op, vector(Value(comparison.GetReturnType())); } + const bool negation_is_left = RefersToSameObject(BoundComparisonExpression::Left(comparison), negation); + Value new_constant; auto &constant_type = outer_constant.GetReturnType(); unique_ptr nan_guard; bool nan_guard_disjunctive = false; @@ -306,7 +313,7 @@ unique_ptr MoveUnaryMinusRule::Apply(LogicalOperator &op, vector MoveUnaryMinusRule::Apply(LogicalOperator &op, vector(negated_value), width, scale)); + new_constant = Value::DECIMAL(Cast::Operation(negated_value), width, scale); break; case PhysicalType::INT32: - outer_constant.SetValue(Value::DECIMAL(Cast::Operation(negated_value), width, scale)); + new_constant = Value::DECIMAL(Cast::Operation(negated_value), width, scale); break; case PhysicalType::INT64: - outer_constant.SetValue(Value::DECIMAL(Cast::Operation(negated_value), width, scale)); + new_constant = Value::DECIMAL(Cast::Operation(negated_value), width, scale); break; case PhysicalType::INT128: - outer_constant.SetValue(Value::DECIMAL(negated_value, width, scale)); + new_constant = Value::DECIMAL(negated_value, width, scale); break; default: throw InternalException("Unknown DECIMAL physical type"); @@ -346,14 +353,17 @@ unique_ptr MoveUnaryMinusRule::Apply(LogicalOperator &op, vector [x FLIPPED_COMP -c] auto inner_expr = std::move(negation.GetChildrenMutable()[0]); - if (RefersToSameObject(BoundComparisonExpression::Left(comparison), negation)) { + auto new_constant_expr = outer_constant.WithValue(std::move(new_constant)); + if (negation_is_left) { BoundComparisonExpression::LeftMutable(comparison) = std::move(inner_expr); + BoundComparisonExpression::RightMutable(comparison) = std::move(new_constant_expr); } else { BoundComparisonExpression::RightMutable(comparison) = std::move(inner_expr); + BoundComparisonExpression::LeftMutable(comparison) = std::move(new_constant_expr); } BoundComparisonExpression::FlipType(comparison); if (nan_guard) { diff --git a/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp b/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp index 76206aaf4..9893f1c0f 100644 --- a/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp @@ -34,9 +34,8 @@ unique_ptr NotConjunctionSimplificationRule::Apply(LogicalOperator & auto result = make_uniq(negated_type); result->GetChildrenMutable().reserve(conjunction.GetChildren().size()); for (auto &conj_child : conjunction.GetChildrenMutable()) { - auto negated_child = make_uniq(ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN); - negated_child->GetChildrenMutable().push_back(std::move(conj_child)); - result->GetChildrenMutable().push_back(std::move(negated_child)); + result->GetChildrenMutable().push_back(make_uniq( + ExpressionType::OPERATOR_NOT, LogicalType::BOOLEAN, std::move(conj_child))); } changes_made = true; diff --git a/src/duckdb/src/optimizer/rule/ordered_aggregate_optimizer.cpp b/src/duckdb/src/optimizer/rule/ordered_aggregate_optimizer.cpp index 212668aa9..a113e81d2 100644 --- a/src/duckdb/src/optimizer/rule/ordered_aggregate_optimizer.cpp +++ b/src/duckdb/src/optimizer/rule/ordered_aggregate_optimizer.cpp @@ -30,7 +30,7 @@ unique_ptr OrderedAggregateOptimizer::Apply(ClientContext &context, } // Remove unnecessary ORDER BY clauses and return if nothing remains - if (aggr.GetOrderBysMutable()->Simplify(groups, grouping_sets)) { + if (aggr.GetOrderBys()->Simplify(groups, grouping_sets)) { aggr.GetOrderBysMutable().reset(); changes_made = true; return nullptr; diff --git a/src/duckdb/src/optimizer/rule/predicate_factoring.cpp b/src/duckdb/src/optimizer/rule/predicate_factoring.cpp index 35ce8b9bd..526425849 100644 --- a/src/duckdb/src/optimizer/rule/predicate_factoring.cpp +++ b/src/duckdb/src/optimizer/rule/predicate_factoring.cpp @@ -160,9 +160,8 @@ unique_ptr PredicateFactoringRule::Apply(LogicalOperator &op, vector if (!column_filter) { column_filter = expr.get().Copy(); } else { - auto new_disjunction = make_uniq(ExpressionType::CONJUNCTION_OR); - new_disjunction->GetChildrenMutable().push_back(std::move(column_filter)); - new_disjunction->GetChildrenMutable().push_back(expr.get().Copy()); + auto new_disjunction = make_uniq( + ExpressionType::CONJUNCTION_OR, std::move(column_filter), expr.get().Copy()); column_filter = std::move(new_disjunction); } } @@ -171,17 +170,15 @@ unique_ptr PredicateFactoringRule::Apply(LogicalOperator &op, vector if (!derived_filter) { derived_filter = std::move(column_filter); } else { - auto new_conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); - new_conjunction->GetChildrenMutable().push_back(std::move(column_filter)); - new_conjunction->GetChildrenMutable().push_back(std::move(derived_filter)); + auto new_conjunction = make_uniq( + ExpressionType::CONJUNCTION_AND, std::move(column_filter), std::move(derived_filter)); derived_filter = std::move(new_conjunction); } } // Now add the derived filter as an AND to the original expression - auto result = make_uniq(ExpressionType::CONJUNCTION_AND); - result->GetChildrenMutable().push_back(bindings[0].get().Copy()); - result->GetChildrenMutable().push_back(std::move(derived_filter)); + auto result = make_uniq(ExpressionType::CONJUNCTION_AND, bindings[0].get().Copy(), + std::move(derived_filter)); return std::move(result); } diff --git a/src/duckdb/src/optimizer/rule/regex_optimizations.cpp b/src/duckdb/src/optimizer/rule/regex_optimizations.cpp index 7d6f4fc9f..e3fa9578f 100644 --- a/src/duckdb/src/optimizer/rule/regex_optimizations.cpp +++ b/src/duckdb/src/optimizer/rule/regex_optimizations.cpp @@ -164,7 +164,7 @@ unique_ptr RegexOptimizationRule::Apply(LogicalOperator &op, vector< bool &changes_made, bool is_root) { auto &root = bindings[0].get().Cast(); auto &constant_expr = bindings[2].get().Cast(); - D_ASSERT(root.GetChildrenMutable().size() == 2 || root.GetChildrenMutable().size() == 3); + D_ASSERT(root.GetChildren().size() == 2 || root.GetChildren().size() == 3); for (idx_t i = 0; i < 2; i++) { const auto &type = root.GetChildren()[i]->GetReturnType(); if (type.id() == LogicalTypeId::VARCHAR && !StringType::GetCollation(type).empty()) { @@ -208,9 +208,9 @@ unique_ptr RegexOptimizationRule::Apply(LogicalOperator &op, vector< } // if regexp had options, remove them so the new Contains Expression can be matched for other optimizers. - if (root.GetChildrenMutable().size() == 3) { + if (root.GetChildren().size() == 3) { root.GetChildrenMutable().pop_back(); - D_ASSERT(root.GetChildrenMutable().size() == 2); + D_ASSERT(root.GetChildren().size() == 2); } auto parameter = make_uniq(Value(std::move(escaped_like_string.like_string))); @@ -230,9 +230,9 @@ unique_ptr RegexOptimizationRule::Apply(LogicalOperator &op, vector< } // if regexp had options, remove them so the new Like Expression can be matched for other optimizers. - if (root.GetChildrenMutable().size() == 3) { + if (root.GetChildren().size() == 3) { root.GetChildrenMutable().pop_back(); - D_ASSERT(root.GetChildrenMutable().size() == 2); + D_ASSERT(root.GetChildren().size() == 2); } auto like_expression = BindBuiltinScalarFunction(GetContext(), LikeFun::Name, std::move(root.GetChildrenMutable())); @@ -306,7 +306,7 @@ unique_ptr RegexpReplaceExtractRule::Apply(LogicalOperator &op, vect } string options_str = "k"; - if (root.GetChildrenMutable().size() == 4) { + if (root.GetChildren().size() == 4) { auto &options_const = root.GetChildrenMutable()[3]->Cast(); if (options_const.GetValue().IsNull() || options_const.GetValue().type().id() != LogicalTypeId::VARCHAR) { return nullptr; diff --git a/src/duckdb/src/optimizer/runtime_filter_cast.cpp b/src/duckdb/src/optimizer/runtime_filter_cast.cpp index 1f2f69812..3c92f146d 100644 --- a/src/duckdb/src/optimizer/runtime_filter_cast.cpp +++ b/src/duckdb/src/optimizer/runtime_filter_cast.cpp @@ -1,8 +1,10 @@ #include "duckdb/optimizer/runtime_filter_cast.hpp" #include "duckdb/execution/operator/join/join_filter_pushdown.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" namespace duckdb { @@ -14,7 +16,6 @@ bool RuntimeFilterCastUtil::RuntimeFilterCastCanFail(const LogicalType &source_t !source_type.IsIntegral() || !target_type.IsIntegral()) { return true; } - const auto source_size = GetTypeIdSize(source_type.InternalType()); const auto target_size = GetTypeIdSize(target_type.InternalType()); if (source_size > target_size) { @@ -29,39 +30,97 @@ bool RuntimeFilterCastUtil::RuntimeFilterCastCanFail(const LogicalType &source_t return source_size >= target_size; } +bool RuntimeFilterCastUtil::IsBuiltinCast(const Expression &expr) { + if (!BoundCastExpression::IsCast(expr)) { + return false; + } + auto &cast = expr.Cast(); + if (!BoundCastExpression::HasValidBindData(cast)) { + return false; + } + auto &bound_cast = BoundCastExpression::GetBoundCast(cast); + if (bound_cast.GetCastData()) { + return false; + } + CastFunctionSet default_casts; + auto input = GetCastFunctionInput::Default(); + auto default_cast = + default_casts.GetCastFunction(BoundCastExpression::Child(cast).GetReturnType(), cast.GetReturnType(), input); + return !default_cast.GetCastData() && + (bound_cast.Equals(default_cast) || bound_cast.HasSameStatisticsCallback(default_cast)); +} + +static bool RuntimeFilterCastNeedsTryCast(const BoundFunctionExpression &cast) { + return BoundCastExpression::IsTryCast(cast) || !RuntimeFilterCastUtil::IsBuiltinCast(cast) || + RuntimeFilterCastUtil::RuntimeFilterCastCanFail(BoundCastExpression::Child(cast).GetReturnType(), + cast.GetReturnType()); +} + bool RuntimeFilterCastUtil::RuntimeFilterUsesTryCast(const JoinFilterPushdownColumn &column) { - auto source_type = column.storage_type; - for (auto &cast : column.runtime_filter_casts) { - if (cast.mode == RuntimeFilterCastMode::TRY_CAST || RuntimeFilterCastCanFail(source_type, cast.target_type)) { - return true; - } - source_type = cast.target_type; + if (!column.input_expression) { + return false; } - return false; + bool result = false; + ExpressionIterator::VisitExpressionClass( + *column.input_expression, ExpressionClass::BOUND_FUNCTION, [&](const Expression &expr) { + if (BoundCastExpression::IsCast(expr)) { + result |= RuntimeFilterCastNeedsTryCast(expr.Cast()); + } + }); + return result; +} + +static bool ExpressionPreservesStorageOrdering(const Expression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_REF) { + return true; + } + if (!BoundCastExpression::IsCast(expr)) { + return false; + } + auto &cast = expr.Cast(); + return !RuntimeFilterCastNeedsTryCast(cast) && ExpressionPreservesStorageOrdering(BoundCastExpression::Child(cast)); +} + +bool RuntimeFilterCastUtil::PreservesStorageOrdering(const JoinFilterPushdownColumn &column) { + return column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && + (!column.input_expression || ExpressionPreservesStorageOrdering(*column.input_expression)); } LogicalType RuntimeFilterCastUtil::GetRuntimeFilterInputType(const JoinFilterPushdownColumn &column, const LogicalType &runtime_type) { - if (column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && !column.runtime_filter_casts.empty()) { - return column.runtime_filter_casts.back().target_type; + if (column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && column.input_expression) { + return column.input_expression->GetReturnType(); } return runtime_type; } bool RuntimeFilterCastUtil::RequiresRuntimeFilterExpressionReconstruction(const JoinFilterPushdownColumn &column, const LogicalType &runtime_type) { - if (column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION) { - return false; + return column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && column.input_expression && + !PreservesStorageOrdering(column); +} + +static void PreserveRuntimeFilterCastErrors(unique_ptr &expr, bool &preserves_cast_errors) { + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { PreserveRuntimeFilterCastErrors(child, preserves_cast_errors); }); + if (!BoundCastExpression::IsCast(*expr)) { + return; } - auto source_type = column.storage_type; - for (auto &cast : column.runtime_filter_casts) { - if (RuntimeFilterCastCanFail(source_type, cast.target_type)) { - return true; - } - source_type = cast.target_type; + auto &cast = expr->Cast(); + if (BoundCastExpression::IsTryCast(cast) || !RuntimeFilterCastNeedsTryCast(cast)) { + return; } - D_ASSERT(source_type == GetRuntimeFilterInputType(column, runtime_type)); - return false; + 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); + safe_cast->SetAlias(cast.GetAlias()); + safe_cast->SetQueryLocation(cast.GetQueryLocation()); + expr = std::move(safe_cast); + preserves_cast_errors = true; } unique_ptr RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression(ClientContext &context, @@ -69,17 +128,9 @@ unique_ptr RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression bool &preserves_cast_errors) { D_ASSERT(column.storage_type.IsValid()); preserves_cast_errors = false; - unique_ptr input = make_uniq(column.storage_type, idx_t(0)); - auto source_type = column.storage_type; - for (auto &cast : column.runtime_filter_casts) { - const auto cast_can_fail = RuntimeFilterCastCanFail(source_type, cast.target_type); - const auto is_try_cast = cast.mode == RuntimeFilterCastMode::TRY_CAST || cast_can_fail; - if (source_type != cast.target_type) { - input = BoundCastExpression::AddCastToType(context, std::move(input), cast.target_type, is_try_cast); - } - preserves_cast_errors |= cast.mode == RuntimeFilterCastMode::DEFAULT_CAST && cast_can_fail; - source_type = cast.target_type; - } + auto input = column.input_expression ? column.input_expression->Copy() + : make_uniq(column.storage_type, idx_t(0)); + PreserveRuntimeFilterCastErrors(input, preserves_cast_errors); return input; } diff --git a/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp b/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp index 514867158..d3242c79f 100644 --- a/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp +++ b/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp @@ -258,15 +258,15 @@ static void CollectBindings(const Expression &expr, column_binding_set_t &bindin } //! Points every column reference of `expr` that `remap` names at its new binding -static void RemapBindings(Expression &expr, const column_binding_map_t &remap) { - if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { - auto &binding = expr.Cast().BindingMutable(); - auto entry = remap.find(binding); - if (entry != remap.end()) { - binding = entry->second; - } - } - ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { RemapBindings(child, remap); }); +static void RemapBindings(unique_ptr &expr, const column_binding_map_t &remap) { + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) -> unique_ptr { + auto entry = remap.find(colref.Binding()); + if (entry == remap.end()) { + return nullptr; + } + return colref.WithBinding(entry->second); + }); } static unique_ptr MakeConjunction(ExpressionType type, vector> terms) { @@ -514,7 +514,7 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector for (idx_t k = 0; k < group.size(); k++) { for (auto &conjunct : branches[group[k]].conjuncts) { auto copy = conjunct.get().Copy(); - RemapBindings(*copy, remaps[k]); + RemapBindings(copy, remaps[k]); conjuncts[k].push_back(std::move(copy)); } } @@ -582,7 +582,7 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector offsets[k] = aggregates.size(); for (auto &expr : branches[group[k]].aggregate.get().expressions) { auto copy = expr->Copy(); - RemapBindings(*copy, remaps[k]); + RemapBindings(copy, remaps[k]); auto &aggregate = copy->Cast(); if (predicates[k]) { auto filter = predicates[k]->Copy(); @@ -612,7 +612,7 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector auto &expressions = branch.projection->expressions; for (idx_t i = 0; i < expressions.size(); i++) { auto copy = expressions[i]->Copy(); - RemapBindings(*copy, to_merged); + RemapBindings(copy, to_merged); replacements.emplace_back(ColumnBinding(branch.projection->table_index, ProjectionIndex(i)), ColumnBinding(projection_index, ProjectionIndex(columns.size()))); columns.push_back(std::move(copy)); diff --git a/src/duckdb/src/optimizer/scalar_fn_pushdown.cpp b/src/duckdb/src/optimizer/scalar_fn_pushdown.cpp index ea8b12da7..4ad168072 100644 --- a/src/duckdb/src/optimizer/scalar_fn_pushdown.cpp +++ b/src/duckdb/src/optimizer/scalar_fn_pushdown.cpp @@ -74,10 +74,11 @@ unique_ptr ScalarFnReplace::VisitReplace(BoundColumnRefExpression &e const auto &[analysis, column_index, projection, projection_column_index] = *binding; if (CanPushdownColumn(analysis, column_index)) { const LogicalType return_type = analysis.get.returned_types[analysis.StorageIndex(column_index)]; - expr.SetReturnType(return_type); + auto retyped = expr.WithReturnType(return_type); if (projection != nullptr && !projection->types.empty()) { projection->types[projection_column_index] = return_type; } + return retyped; } return std::move(*ptr); @@ -105,7 +106,7 @@ unique_ptr ScalarFnReplace::VisitReplace(BoundFunctionExpression &ex } const LogicalType return_type = analysis.get.returned_types[analysis.StorageIndex(column_index)]; - bound_col_base->SetReturnType(return_type); + bound_col_base = bound_col.WithReturnType(return_type); if (projection != nullptr && !projection->types.empty()) { projection->types[projection_column_index] = return_type; } diff --git a/src/duckdb/src/optimizer/self_join_aggregate.cpp b/src/duckdb/src/optimizer/self_join_aggregate.cpp index d1a5b333a..1ac3903fd 100644 --- a/src/duckdb/src/optimizer/self_join_aggregate.cpp +++ b/src/duckdb/src/optimizer/self_join_aggregate.cpp @@ -498,8 +498,8 @@ class SelfJoinAggregateRewriter { auto scan = std::move(join.children[0]); auto not_null = make_uniq(); for (auto &key : keys) { - auto check = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - check->GetChildrenMutable().push_back( + auto check = make_uniq( + ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, make_uniq(key.type, ColumnBinding(scan_index, key.left))); not_null->expressions.push_back(std::move(check)); } @@ -539,11 +539,10 @@ class SelfJoinAggregateRewriter { unique_ptr replacement; if (key_of[k] != DConstants::INVALID_INDEX) { replacement = make_uniq( - expr->GetReturnType(), ColumnBinding(group_index, ProjectionIndex(key_of[k]))); + expr->GetAlias(), expr->GetReturnType(), ColumnBinding(group_index, ProjectionIndex(key_of[k]))); } else { - replacement = make_uniq(Value(expr->GetReturnType())); + replacement = make_uniq(Value(expr->GetReturnType()), expr->GetAlias()); } - replacement->SetAlias(expr->GetAlias()); expr = std::move(replacement); } // drops the filters, the join and the other scan diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp index d202a699d..59f32c89e 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp @@ -67,7 +67,7 @@ void StatisticsPropagator::SimplifyConstantOrNull(vector> unique_ptr StatisticsPropagator::PropagateExpression(BoundConjunctionExpression &expr, unique_ptr &expr_ptr) { auto is_and = expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND; - for (idx_t expr_idx = 0; expr_idx < expr.GetChildrenMutable().size(); expr_idx++) { + for (idx_t expr_idx = 0; expr_idx < expr.GetChildren().size(); expr_idx++) { auto &child = expr.GetChildrenMutable()[expr_idx]; auto stats = PropagateExpression(child); if (!child->IsFoldable()) { @@ -114,11 +114,11 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundConjun if (is_and) { SimplifyConstantOrNull(expr.GetChildrenMutable()); } - if (expr.GetChildrenMutable().empty()) { + if (expr.GetChildren().empty()) { // if there are no children left, replace the conjunction with TRUE (for AND) or FALSE (for OR) expr_ptr = make_uniq(Value::BOOLEAN(is_and)); return PropagateExpression(expr_ptr); - } else if (expr.GetChildrenMutable().size() == 1) { + } else if (expr.GetChildren().size() == 1) { // if there is one child left, replace the conjunction with that one child expr_ptr = std::move(expr.GetChildrenMutable()[0]); } diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp index 15692156c..8b36f8831 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp @@ -244,7 +244,7 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundFuncti return PropagateComparison(func, expr_ptr); } vector stats; - stats.reserve(func.GetChildrenMutable().size()); + stats.reserve(func.GetChildren().size()); bool has_invalidated_parameter = false; for (auto &child : func.GetChildrenMutable()) { auto stat = PropagateExpression(child); diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp index 6eba5f59c..cb8417a9b 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp @@ -32,7 +32,7 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundOperat unique_ptr &expr_ptr) { bool all_have_stats = true; vector> child_stats; - child_stats.reserve(expr.GetChildrenMutable().size()); + child_stats.reserve(expr.GetChildren().size()); for (auto &child : expr.GetChildrenMutable()) { auto stats = PropagateExpression(child); if (!stats) { @@ -46,12 +46,12 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundOperat switch (expr.GetExpressionType()) { case ExpressionType::OPERATOR_COALESCE: // COALESCE, merge stats of all children - for (idx_t i = 0; i < expr.GetChildrenMutable().size(); i++) { + for (idx_t i = 0; i < expr.GetChildren().size(); i++) { D_ASSERT(child_stats[i]); if (!child_stats[i]->CanHaveNoNull()) { // this child is always NULL, we can remove it from the coalesce // UNLESS there is only one node remaining - if (expr.GetChildrenMutable().size() > 1) { + if (expr.GetChildren().size() > 1) { expr.GetChildrenMutable().erase_at(i); child_stats.erase_at(i); i--; @@ -61,24 +61,24 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundOperat // coalesce child cannot have NULL entries // this is the last coalesce node that influences the result // we can erase any children after this node - if (i + 1 < expr.GetChildrenMutable().size()) { + if (i + 1 < expr.GetChildren().size()) { expr.GetChildrenMutable().erase(expr.GetChildrenMutable().begin() + NumericCast(i + 1), - expr.GetChildrenMutable().end()); + expr.GetChildren().end()); child_stats.erase(child_stats.begin() + NumericCast(i + 1), child_stats.end()); removed_expressions = true; } break; } } - D_ASSERT(!expr.GetChildrenMutable().empty()); - D_ASSERT(expr.GetChildrenMutable().size() == child_stats.size()); - if (expr.GetChildrenMutable().size() == 1) { + D_ASSERT(!expr.GetChildren().empty()); + D_ASSERT(expr.GetChildren().size() == child_stats.size()); + if (expr.GetChildren().size() == 1) { // coalesce of one entry: simply return that entry expr_ptr = Expression::PreserveReturnType(expr.GetReturnType(), std::move(expr.GetChildrenMutable()[0])); } else { // coalesce of multiple entries // merge the stats - for (idx_t i = 1; i < expr.GetChildrenMutable().size(); i++) { + for (idx_t i = 1; i < expr.GetChildren().size(); i++) { child_stats[0]->Merge(*child_stats[i]); } } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp index 41efa1d5e..98e71c566 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/numeric_utils.hpp" +#include "duckdb/common/operator/add.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/types/value.hpp" #include "duckdb/common/unique_ptr.hpp" @@ -314,8 +315,8 @@ void CapGroupedAggregateCardinalityByKeyDomain(LogicalAggregate &aggr, optional_ } // namespace void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_ptr &node_ptr) { - if (!aggr.groups.empty()) { - // not possible with groups + if (!aggr.groups.empty() || aggr.grouping_sets.size() > 1) { + // Direct execution produces one row, so it cannot preserve groups or repeated grouping sets. return; } if (aggr.expressions.empty()) { @@ -475,6 +476,9 @@ void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_p case FilterPropagateResult::FILTER_ALWAYS_FALSE: break; default: + // Bail out early: partial precomputation is disabled due to unstable row-group indices (PR #24962). + return; + need_to_scan = true; scan_partition_indices.push_back(partition_idx); break; @@ -565,8 +569,8 @@ void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_p if (fun_name == "count_star") { // pre_count + count_star_from_scan auto &pre_count_expr = agg_results[i]; - auto add_expr = optimizer.BindScalarFunction("+", pre_count_expr->Copy(), std::move(agg_col_ref)); - add_expr->SetAlias(aggr.expressions[i]->GetAlias()); + auto add_expr = optimizer.BindScalarFunction("+", pre_count_expr->Copy(), std::move(agg_col_ref), + aggr.expressions[i]->GetAlias()); proj_expressions.push_back(std::move(add_expr)); } else if (fun_name == "min" || fun_name == "max") { // For min: COALESCE(least(pre_min, agg_min), pre_min) @@ -575,9 +579,8 @@ void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_p Identifier merge_func((fun_name == "min") ? "least" : "greatest"); auto merged = optimizer.BindScalarFunction(merge_func, pre_val_expr->Copy(), std::move(agg_col_ref)); auto coalesce = - make_uniq(ExpressionType::OPERATOR_COALESCE, aggr_expr.GetReturnType()); - coalesce->GetChildrenMutable().push_back(std::move(merged)); - coalesce->GetChildrenMutable().push_back(pre_val_expr->Copy()); + make_uniq(ExpressionType::OPERATOR_COALESCE, aggr_expr.GetReturnType(), + std::move(merged), pre_val_expr->Copy()); coalesce->SetAlias(aggr.expressions[i]->GetAlias()); proj_expressions.push_back(std::move(coalesce)); } @@ -683,23 +686,34 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalAggr aggr.distinct_validity = distinct_validity; const auto is_ungrouped = aggr.groups.empty(); + const auto grouping_set_count = MaxValue(1, aggr.grouping_sets.size()); // after we propagate statistics - try to directly execute aggregates using statistics TryExecuteAggregates(aggr, node_ptr); if (is_ungrouped) { - // Ungrouped aggregate always returns exactly one row, even over empty input + // Each empty grouping set returns one row, even over empty input. // node_stats holds the input cardinality: do not leak it to the parent operator node_stats.reset(); - return make_uniq(1U, 1U); + return make_uniq(grouping_set_count, grouping_set_count); } - // the max cardinality of an aggregate is the max cardinality of the input (i.e. when every row is a unique - // group) // The join-order optimizer bounds a group key's distinct count by its table's min/max only for keys that are // a direct base-table column reference; a key that is an expression or arrives through another operator falls // back to an input-proportional guess. Now that the propagated group statistics are available, tighten the // estimate by an upper bound on the number of distinct group-key combinations - the same group-key domain the // physical perfect-hash-aggregate path derives from min/max and type. CapGroupedAggregateCardinalityByKeyDomain(aggr, node_stats.get()); + if (node_stats && node_stats->has_max_cardinality && !aggr.grouping_sets.empty()) { + idx_t max_cardinality = 0; + for (const auto &grouping_set : aggr.grouping_sets) { + // Nonempty sets emit at most one group per input row. Empty sets always emit one row. + const auto set_max = grouping_set.empty() ? 1 : node_stats->max_cardinality; + if (!TryAddOperator::Operation(max_cardinality, set_max, max_cardinality)) { + node_stats.reset(); + return nullptr; + } + } + node_stats->max_cardinality = max_cardinality; + } return std::move(node_stats); } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp index 0f152cef5..7cd786e97 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp @@ -1,5 +1,6 @@ #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/scalar/generic_common.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/expression/bound_between_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -323,7 +324,21 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalFilt return make_uniq(0U, 0U); } - // then propagate to each of the expressions + // the filter evaluates its conjuncts in an adaptive order over the input rows, so their verification statistics + // are derived from the input statistics before any conjunct narrows them + const bool verify_stats = Settings::Get(context); + column_binding_map_t> input_statistics; + if (verify_stats) { + for (auto &entry : statistics_map) { + // compressed materialization registers bindings without statistics + if (entry.second) { + input_statistics[entry.first] = entry.second->ToUnique(); + } + } + } + // the conjuncts are propagated against statistics narrowed by the earlier conjuncts: these hold for the filter + // output and the pruning of the later conjuncts, but not for the vectors they are evaluated on + VerificationStatsGuard narrowing_guard(attach_verification_stats); for (idx_t i = 0; i < filter.expressions.size(); i++) { auto &condition = filter.expressions[i]; auto prune_result = HandleFilter(condition); @@ -350,6 +365,15 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalFilt } } SimplifyConstantOrNull(filter.expressions); + if (verify_stats) { + // the remaining conjuncts are final: attach the verification statistics derived from the input statistics + narrowing_guard.Release(); + std::swap(statistics_map, input_statistics); + for (auto &condition : filter.expressions) { + PropagateExpression(condition); + } + std::swap(statistics_map, input_statistics); + } // the max cardinality of a filter is the cardinality of the input (i.e. no tuples get filtered) return std::move(node_stats); } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp index 9df72ffd6..a7c26f245 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp @@ -168,6 +168,8 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalGet unique_ptr &node_ptr) { if (get.function.cardinality) { node_stats = get.function.cardinality(context, get.bind_data.get()); + } else { + node_stats.reset(); } if (!get.function.statistics && !get.function.statistics_extended) { // no column statistics to get diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp index 42bb343a5..d28678277 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp @@ -1,6 +1,9 @@ #include "duckdb/common/types/hugeint.hpp" +#include "duckdb/common/operator/add.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/optimizer/statistics_propagator.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/operator/logical_any_join.hpp" @@ -106,18 +109,29 @@ bool StatisticsPropagator::HandleJoinAlwaysMatches(LogicalJoin &join, unique_ptr } } -//! Suspends attaching verification statistics to propagated expressions for the lifetime of the guard -struct VerificationStatsGuard { - explicit VerificationStatsGuard(bool &attach_p) : attach(attach_p), previous(attach_p) { - attach = false; +//! The column a join-derived filter can target: the side itself or the column under an invertible numeric cast +static optional_ptr GetFilterColumn(ClientContext &context, const Expression &expr) { + optional_ptr column = expr; + if (BoundCastExpression::IsCast(expr)) { + auto &cast = expr.Cast(); + auto source_type = BoundCastExpression::SourceType(cast); + auto &target_type = cast.GetReturnType(); + // Invertible numeric casts also preserve order. + if (BoundCastExpression::IsTryCast(cast) || !source_type.IsNumeric() || !target_type.IsNumeric() || + !BoundCastExpression::CastIsInvertibleForEquality(source_type, target_type)) { + return nullptr; + } + if (!BoundCastExpression::IsDefaultCast(cast) && + CastFunctionSet::Get(context).CanOverrideDefaultCast(source_type, target_type)) { + return nullptr; + } + column = BoundCastExpression::Child(cast); } - ~VerificationStatsGuard() { - attach = previous; + if (column->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return nullptr; } - - bool &attach; - bool previous; -}; + return column; +} void StatisticsPropagator::PropagateStatistics(LogicalComparisonJoin &join, unique_ptr &node_ptr) { // every condition is evaluated over the candidate pairs of the join inputs, so the verification statistics of @@ -238,6 +252,14 @@ void StatisticsPropagator::PropagateStatistics(LogicalComparisonJoin &join, uniq // Update join_stats when is already part of the join condition.SetLeftStats(std::move(updated_stats_left)); condition.SetRightStats(std::move(updated_stats_right)); + } else if (stats_left && stats_right && GetFilterColumn(context, condition.GetLHS()) && + GetFilterColumn(context, condition.GetRHS())) { + // A side is a cast of a column: tighten copies of the side stats instead + auto tightened_left = stats_left->Copy(); + auto tightened_right = stats_right->Copy(); + UpdateFilterStatistics(tightened_left, tightened_right, condition.GetComparisonType()); + CreateFilterFromJoinStats(join.children[0], condition.LeftReference(), *stats_left, tightened_left); + CreateFilterFromJoinStats(join.children[1], condition.RightReference(), *stats_right, tightened_right); } break; } @@ -306,14 +328,43 @@ void StatisticsPropagator::MultiplyCardinalities(unique_ptr &sta unique_ptr StatisticsPropagator::PropagateStatistics(LogicalJoin &join, unique_ptr &node_ptr) { // first propagate through the children of the join - node_stats = PropagateStatistics(join.children[0]); - for (idx_t child_idx = 1; child_idx < join.children.size(); child_idx++) { - auto child_stats = PropagateStatistics(join.children[child_idx]); - if (!child_stats) { - node_stats = nullptr; - } else if (node_stats) { - MultiplyCardinalities(node_stats, *child_stats); + auto left_stats = PropagateStatistics(join.children[0]); + auto right_stats = PropagateStatistics(join.children[1]); + switch (join.join_type) { + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + case JoinType::SINGLE: + node_stats = std::move(left_stats); + break; + case JoinType::RIGHT_SEMI: + case JoinType::RIGHT_ANTI: + node_stats = std::move(right_stats); + break; + default: + if (left_stats && right_stats && left_stats->has_max_cardinality && right_stats->has_max_cardinality) { + idx_t unmatched_rows = 0; + if (join.join_type == JoinType::LEFT) { + right_stats->max_cardinality = MaxValue(right_stats->max_cardinality, 1); + } else if (join.join_type == JoinType::RIGHT) { + left_stats->max_cardinality = MaxValue(left_stats->max_cardinality, 1); + } else if (join.join_type == JoinType::OUTER) { + if (!TryAddOperator::Operation(left_stats->max_cardinality, right_stats->max_cardinality, + unmatched_rows)) { + left_stats.reset(); + } + } + if (left_stats) { + MultiplyCardinalities(left_stats, *right_stats); + if (left_stats) { + left_stats->max_cardinality = MaxValue(left_stats->max_cardinality, unmatched_rows); + } + } + } else { + left_stats.reset(); } + node_stats = std::move(left_stats); + break; } auto join_type = join.join_type; @@ -392,20 +443,21 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalPosi D_ASSERT(join.type == LogicalOperatorType::LOGICAL_POSITIONAL_JOIN); // first propagate through the children of the join - node_stats = PropagateStatistics(join.children[0]); + auto join_stats = PropagateStatistics(join.children[0]); for (idx_t child_idx = 1; child_idx < join.children.size(); child_idx++) { auto child_stats = PropagateStatistics(join.children[child_idx]); if (!child_stats) { - node_stats = nullptr; - } else if (node_stats) { - if (!node_stats->has_estimated_cardinality || !child_stats->has_estimated_cardinality || - !node_stats->has_max_cardinality || !child_stats->has_max_cardinality) { - node_stats = nullptr; + join_stats = nullptr; + } else if (join_stats) { + if (!join_stats->has_estimated_cardinality || !child_stats->has_estimated_cardinality || + !join_stats->has_max_cardinality || !child_stats->has_max_cardinality) { + join_stats = nullptr; } else { - MaxCardinalities(node_stats, *child_stats); + MaxCardinalities(join_stats, *child_stats); } } } + node_stats = std::move(join_stats); // No conditions. @@ -439,9 +491,10 @@ void StatisticsPropagator::CreateFilterFromJoinStats(unique_ptr if (mode != StatisticsPropagationMode::FULL) { return; } - // Only do this for integral colref's that have stats - if (expr->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || !expr->GetReturnType().IsIntegral() || - !NumericStats::HasMinMax(stats_before) || !NumericStats::HasMinMax(stats_after)) { + // Match the numeric types supported by UpdateFilterStatistics. + auto column = GetFilterColumn(context, *expr); + if (!column || !expr->GetReturnType().IsNumeric() || !NumericStats::HasMinMax(stats_before) || + !NumericStats::HasMinMax(stats_after)) { return; } @@ -452,15 +505,19 @@ void StatisticsPropagator::CreateFilterFromJoinStats(unique_ptr auto max_after = NumericStats::Max(stats_after); vector> filter_exprs; + auto add_filter = [&](ExpressionType comparison_type, const Value &bound) { + // Inclusive bounds remain conservative when the reverse numeric cast rounds. + auto column_bound = bound.DefaultTryCastAs(column->GetReturnType()); + if (column_bound) { + filter_exprs.emplace_back(BoundComparisonExpression::Create( + comparison_type, column->Copy(), make_uniq(std::move(*column_bound)))); + } + }; if (min_after > min_before) { - filter_exprs.emplace_back( - BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHANOREQUALTO, expr->Copy(), - make_uniq(std::move(min_after)))); + add_filter(ExpressionType::COMPARE_GREATERTHANOREQUALTO, min_after); } if (max_after < max_before) { - filter_exprs.emplace_back( - BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHANOREQUALTO, expr->Copy(), - make_uniq(std::move(max_after)))); + add_filter(ExpressionType::COMPARE_LESSTHANOREQUALTO, max_after); } if (filter_exprs.empty()) { diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_set_operation.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_set_operation.cpp index 61967fa64..22a2550ed 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_set_operation.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_set_operation.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/operator/add.hpp" #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" @@ -12,18 +13,10 @@ void StatisticsPropagator::AddCardinalities(unique_ptr &stats, N stats = nullptr; return; } - stats->estimated_cardinality += new_stats.estimated_cardinality; - auto new_max = - Hugeint::Add(NumericCast(stats->max_cardinality), NumericCast(new_stats.max_cardinality)); - if (new_max < NumericLimits::Maximum()) { - int64_t result; - if (!Hugeint::TryCast(new_max, result)) { - throw InternalException("Overflow in cast in statistics propagation"); - } - D_ASSERT(result >= 0); - stats->max_cardinality = idx_t(result); - } else { - stats = nullptr; + if (!TryAddOperator::Operation(stats->estimated_cardinality, new_stats.estimated_cardinality, + stats->estimated_cardinality) || + !TryAddOperator::Operation(stats->max_cardinality, new_stats.max_cardinality, stats->max_cardinality)) { + stats.reset(); } } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_unnest.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_unnest.cpp new file mode 100644 index 000000000..87523ae62 --- /dev/null +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_unnest.cpp @@ -0,0 +1,63 @@ +#include "duckdb/optimizer/statistics_propagator.hpp" +#include "duckdb/planner/expression/bound_unnest_expression.hpp" +#include "duckdb/planner/operator/logical_unnest.hpp" +#include "duckdb/storage/statistics/array_stats.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" + +namespace duckdb { + +static unique_ptr GetUnnestElementStats(const BaseStatistics &input_stats, + const LogicalType &element_type) { + optional_ptr element_stats; + switch (input_stats.GetStatsType()) { + case StatisticsType::LIST_STATS: + element_stats = ListStats::GetChildStats(input_stats); + break; + case StatisticsType::ARRAY_STATS: + element_stats = ArrayStats::GetChildStats(input_stats); + break; + default: + return nullptr; + } + if (element_stats->GetType() != element_type) { + return nullptr; + } + return element_stats->ToUnique(); +} + +unique_ptr StatisticsPropagator::PropagateStatistics(LogicalUnnest &unnest, + unique_ptr &node_ptr) { + PropagateStatistics(unnest.children[0]); + if (unnest.children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT) { + ReplaceWithEmptyResult(node_ptr); + return nullptr; + } + // unnest emits its input row once per unnested entry + ResetAdditiveStatistics(unnest.children[0]->GetColumnBindings()); + // several unnests in one operator pad the shorter lists with NULL + const bool can_pad_with_null = unnest.expressions.size() > 1; + for (idx_t expr_idx = 0; expr_idx < unnest.expressions.size(); expr_idx++) { + auto &expr = unnest.expressions[expr_idx]; + if (expr->GetExpressionClass() != ExpressionClass::BOUND_UNNEST) { + PropagateExpression(expr); + continue; + } + auto &unnest_expr = expr->Cast(); + auto input_stats = PropagateExpression(unnest_expr.ChildMutable()); + if (!input_stats) { + continue; + } + auto element_stats = GetUnnestElementStats(*input_stats, expr->GetReturnType()); + if (!element_stats) { + continue; + } + element_stats->ResetAdditiveStatistics(); + if (can_pad_with_null) { + element_stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES); + } + statistics_map[ColumnBinding(unnest.unnest_index, ProjectionIndex(expr_idx))] = std::move(element_stats); + } + return nullptr; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp index e793a2eb0..b4a75889d 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp @@ -64,7 +64,7 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalWind : AggregateType::NON_DISTINCT); aggregate.GetCallbacks().GetStatisticsCallback()(context, synthetic, input); agg_children = std::move(synthetic.GetChildrenMutable()); - aggregate = synthetic.FunctionMutable(); + aggregate = synthetic.Function(); removed_expressions |= agg_children.size() < child_count; } } diff --git a/src/duckdb/src/optimizer/statistics_propagator.cpp b/src/duckdb/src/optimizer/statistics_propagator.cpp index 03095c73b..e7ea8a27e 100644 --- a/src/duckdb/src/optimizer/statistics_propagator.cpp +++ b/src/duckdb/src/optimizer/statistics_propagator.cpp @@ -19,6 +19,7 @@ #include "duckdb/planner/operator/logical_order.hpp" #include "duckdb/planner/operator/logical_positional_join.hpp" #include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_unnest.hpp" #include "duckdb/planner/operator/logical_secure_view.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/operator/logical_window.hpp" @@ -32,6 +33,12 @@ StatisticsPropagator::StatisticsPropagator(Optimizer &optimizer_p, unique_ptrResolveOperatorTypes(); } +unique_ptr StatisticsPropagator::PropagateExpressionStatistics( + unique_ptr &expr, column_binding_map_t> column_statistics) { + statistics_map = std::move(column_statistics); + return PropagateExpression(expr); +} + void StatisticsPropagator::ReplaceWithEmptyResult(unique_ptr &node) { node = make_uniq(std::move(node)); } @@ -120,9 +127,7 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalOper result = PropagateStatistics(node.Cast(), node_ptr); break; case LogicalOperatorType::LOGICAL_UNNEST: - result = PropagateChildren(node, node_ptr); - // unnest emits its input row once per unnested entry - ResetAdditiveStatistics(node.children[0]->GetColumnBindings()); + result = PropagateStatistics(node.Cast(), node_ptr); break; default: result = PropagateChildren(node, node_ptr); diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index 9c4e995e6..eb50d454c 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -20,6 +20,7 @@ #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_unnest.hpp" +#include "duckdb/common/type_visitor.hpp" #include "duckdb/planner/operator/logical_window.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -308,6 +309,7 @@ unique_ptr TopNWindowElimination::OptimizeInternal(unique_ptrCopy(); fun_args[1] = make_uniq(alias); - auto bound_function = function_binder.BindScalarFunction(struct_extract_fun, std::move(fun_args)); - bound_function->SetAlias(alias); + auto bound_function = + function_binder.BindScalarFunction(struct_extract_fun, std::move(fun_args), false, nullptr, alias); exprs.push_back(std::move(bound_function)); } } @@ -708,10 +710,15 @@ vector> TopNWindowElimination::GenerateAggregatePayload(c const auto window_child_bindings = window.children[0]->GetColumnBindings(); auto &window_expr = window.expressions[0]->Cast(); - // Remember order of group columns to recreate that order in new bindings later + // Remember order of group columns to recreate that order in new bindings later. + // A FLOAT or DOUBLE group holds both 0.0 and -0.0, so such a column is carried in the payload instead. column_binding_map_t group_bindings; - for (idx_t i = 0; i < window_expr.PartitionsMutable().size(); i++) { + for (idx_t i = 0; i < window_expr.Partitions().size(); i++) { auto &expr = window_expr.PartitionsMutable()[i]; + const auto &type = expr->GetReturnType(); + if (TypeVisitor::Contains(type, LogicalTypeId::FLOAT) || TypeVisitor::Contains(type, LogicalTypeId::DOUBLE)) { + continue; + } auto column_references = ColumnReferenceExtractor::GetReferences(&expr); group_bindings[column_references.begin()->first] = i; } @@ -953,7 +960,7 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo vector projections(window_expr.Partitions().size() + args.size()); // Build a projection list for an LHS table scan to recreate the column order of an aggregate with struct packing - for (idx_t i = 0; i < window_expr.PartitionsMutable().size(); i++) { + for (idx_t i = 0; i < window_expr.Partitions().size(); i++) { auto &partition = window_expr.PartitionsMutable()[i]; if (!ExtractSingleBinding(&partition, projections[i])) { return false; diff --git a/src/duckdb/src/optimizer/type_pushdown.cpp b/src/duckdb/src/optimizer/type_pushdown.cpp index 491f4402e..009911b16 100644 --- a/src/duckdb/src/optimizer/type_pushdown.cpp +++ b/src/duckdb/src/optimizer/type_pushdown.cpp @@ -247,13 +247,14 @@ unique_ptr CastReplace::VisitReplace(BoundColumnRefExpression &expr, const auto &[analysis, column_index, projection, projection_column_index] = *binding; if (CanPushdownColumn(analysis, column_index)) { const LogicalType return_type = analysis.get.returned_types[analysis.StorageIndex(column_index)]; - expr.SetReturnType(return_type); + auto retyped = expr.WithReturnType(return_type); // LogicalProjection types are resolved by calling // LogicalProjection::ResolveTypes, so we need to check whether types in // projection have been resolved, and updated them only if needed. if (projection != nullptr && !projection->types.empty()) { projection->types[projection_column_index] = return_type; } + return retyped; } return std::move(*ptr); @@ -279,7 +280,7 @@ unique_ptr CastReplace::VisitReplace(BoundFunctionExpression &expr, } const LogicalType return_type = analysis.get.returned_types[analysis.StorageIndex(column_index)]; - bound_col_base->SetReturnType(return_type); + bound_col_base = bound_col.WithReturnType(return_type); // Same as in CastReplace::VisitReplace(BoundColumnRefExpression) if (projection != nullptr && !projection->types.empty()) { projection->types[projection_column_index] = return_type; diff --git a/src/duckdb/src/optimizer/unnest_rewriter.cpp b/src/duckdb/src/optimizer/unnest_rewriter.cpp index cf477c1ef..34b900d1c 100644 --- a/src/duckdb/src/optimizer/unnest_rewriter.cpp +++ b/src/duckdb/src/optimizer/unnest_rewriter.cpp @@ -86,7 +86,7 @@ void UnnestRewriterPlanUpdater::VisitExpression(unique_ptr *expressi auto &bound_column_ref = expr->Cast(); for (idx_t i = 0; i < replace_bindings.size(); i++) { if (bound_column_ref.Binding() == replace_bindings[i].old_binding) { - bound_column_ref.BindingMutable() = replace_bindings[i].new_binding; + expr = bound_column_ref.WithBinding(replace_bindings[i].new_binding); break; } } @@ -222,9 +222,8 @@ void UnnestRewriter::FindCandidates(unique_ptr &root, unique_pt auto unnest_expr = make_uniq(unnest_get->types[i]); unnest_expr->ChildMutable() = BoundCastExpression::AddArrayCastToList(context, proj.expressions[col_bind.column_index]->Copy()); - bind_col.BindingMutable() = ColumnBinding(unnest_get_index, bind_col.Binding().column_index); auto unnest_proj_idx = ColumnBinding::PushExpression(unnest->expressions, std::move(unnest_expr)); - ColumnBinding new_column_ref(bind_col.Binding().table_index, unnest_proj_idx); + ColumnBinding new_column_ref(unnest_get_index, unnest_proj_idx); auto unnest_ref = make_uniq(bind_col.GetAlias(), unnest_get->types[i], new_column_ref, bind_col.Depth()); proj.expressions[col_bind.column_index] = std::move(unnest_ref); @@ -291,9 +290,8 @@ static bool ConvertCTETableInOutUnnest(ClientContext &context, unique_ptr(unnest_get->types[i]); unnest_expr->ChildMutable() = BoundCastExpression::AddArrayCastToList(context, proj.expressions[col_bind.column_index]->Copy()); - bind_col.BindingMutable() = ColumnBinding(unnest_get_index, bind_col.Binding().column_index); auto unnest_proj_idx = ColumnBinding::PushExpression(unnest->expressions, std::move(unnest_expr)); - ColumnBinding new_column_ref(bind_col.Binding().table_index, unnest_proj_idx); + ColumnBinding new_column_ref(unnest_get_index, unnest_proj_idx); auto unnest_ref = make_uniq(bind_col.GetAlias(), unnest_get->types[i], new_column_ref, bind_col.Depth()); proj.expressions[col_bind.column_index] = std::move(unnest_ref); diff --git a/src/duckdb/src/parallel/executor.cpp b/src/duckdb/src/parallel/executor.cpp index 14b94ff23..f2e09af79 100644 --- a/src/duckdb/src/parallel/executor.cpp +++ b/src/duckdb/src/parallel/executor.cpp @@ -484,7 +484,11 @@ QueryResultState Executor::ExecuteTask() { } if (task) { // partially process the task - auto result = task->Execute(TaskExecutionMode::PROCESS_PARTIAL); + TaskExecutionResult result; + { + PipelineTask::PartialChunkBound bound(PartialChunkCount()); + result = task->Execute(TaskExecutionMode::PROCESS_PARTIAL); + } if (result == TaskExecutionResult::TASK_BLOCKED) { task->Deschedule(); task.reset(); @@ -717,6 +721,21 @@ bool Executor::ResultStoreCanPark() { return !buffer || buffer->Lifetime() != ResultLifetime::RETAINED; } +idx_t Executor::PartialChunkCount() { + // A thread that runs tasks here while worker threads produce a streaming result is that result's consumer: the + // producers park as soon as the buffer is full, and only its pop frees them. When a unit nearly fills the buffer, + // one unit fits at a time, so after every pop the consumer reschedules a producer, finds the buffer empty and + // takes a task - often the one it just rescheduled, before the woken worker gets to it. A full slice then stalls + // the whole pipeline for its length while every worker finishes its unit and parks. The consumer therefore runs + // one chunk per slice and returns to its buffer. A thread with no workers to wait for keeps the full slice: + // NumberOfThreads counts the external threads too, so only a count above them means workers exist + auto external_threads = Settings::Get(context); + if (TaskScheduler::GetScheduler(context).NumberOfThreads() > external_threads && ResultStoreCanPark()) { + return 1; + } + return PipelineTask::PARTIAL_CHUNK_COUNT; +} + bool Executor::ResultCollectorIsBlocked() { // A store that cannot park never waits on the consumer, so the retained hot path skips the rest if (!ResultStoreCanPark()) { diff --git a/src/duckdb/src/parallel/pipeline.cpp b/src/duckdb/src/parallel/pipeline.cpp index a0eeef176..1e53c15d6 100644 --- a/src/duckdb/src/parallel/pipeline.cpp +++ b/src/duckdb/src/parallel/pipeline.cpp @@ -28,6 +28,18 @@ static shared_ptr ToSharedSourceState(unique_ptr(std::move(state)); } +//! The chunks per PROCESS_PARTIAL slice on this thread, 0 for PARTIAL_CHUNK_COUNT. Trivially destructible, so no +//! thread_local destructor is registered +static thread_local idx_t partial_chunk_bound = 0; // NOLINT + +PipelineTask::PartialChunkBound::PartialChunkBound(idx_t chunk_count) : previous(partial_chunk_bound) { + partial_chunk_bound = chunk_count; +} + +PipelineTask::PartialChunkBound::~PartialChunkBound() { + partial_chunk_bound = previous; +} + PipelineTask::PipelineTask(Pipeline &pipeline_p, shared_ptr event_p) : ExecutorTask(pipeline_p.executor, std::move(event_p)), pipeline(pipeline_p) { auto sink = pipeline.GetSink(); @@ -45,7 +57,7 @@ TaskExecutionResult PipelineTask::ExecuteTask(TaskExecutionMode mode) { pipeline_executor->SetTaskForInterrupts(shared_from_this()); if (mode == TaskExecutionMode::PROCESS_PARTIAL) { - auto res = pipeline_executor->Execute(PARTIAL_CHUNK_COUNT); + auto res = pipeline_executor->Execute(PartialChunkCount()); switch (res) { case PipelineExecuteResult::NOT_FINISHED: @@ -73,6 +85,16 @@ TaskExecutionResult PipelineTask::ExecuteTask(TaskExecutionMode mode) { return TaskExecutionResult::TASK_FINISHED; } +idx_t PipelineTask::PartialChunkCount() const { + // The bound belongs to the consumer of a streaming result: only the pipeline that feeds its buffer can hand it + // a unit to pop, so only that pipeline returns to it early. The other pipelines keep the full slice + auto sink = pipeline.GetSink(); + if (partial_chunk_bound && sink && sink->type == PhysicalOperatorType::RESULT_COLLECTOR) { + return partial_chunk_bound; + } + return PARTIAL_CHUNK_COUNT; +} + Pipeline::Pipeline(Executor &executor_p) : executor(executor_p), ready(false), initialized(false), source(nullptr), sink(nullptr) { } diff --git a/src/duckdb/src/parallel/runtime_filter_schedule.cpp b/src/duckdb/src/parallel/runtime_filter_schedule.cpp index e13692990..1caa71e1f 100644 --- a/src/duckdb/src/parallel/runtime_filter_schedule.cpp +++ b/src/duckdb/src/parallel/runtime_filter_schedule.cpp @@ -23,6 +23,18 @@ static optional_ptr RuntimeFilterProducer(Pipeline &pipe } } +static bool IsSmallBuild(const PhysicalOperator &op) { + if (op.estimated_cardinality > DEFAULT_STANDARD_VECTOR_SIZE || op.IsSink()) { + return false; + } + for (auto &child : op.children) { + if (!IsSmallBuild(child.get())) { + return false; + } + } + return true; +} + static bool HasJoinSink(Pipeline &pipeline) { auto sink = pipeline.GetSink(); if (!sink) { @@ -128,7 +140,11 @@ static void ScheduleRuntimeFiltersInternal(PipelineSchedule &schedule, bool clea dependency_check = RuntimeFilterDependencyCheck(schedule); join_build_stages = CollectJoinBuildStages(schedule); } - reference_map_t> sources; + struct FilterSource { + idx_t stage_idx; + bool small_build_only; + }; + reference_map_t> sources; for (idx_t stage_idx = 0; add_edges && stage_idx < schedule.stages.size(); stage_idx++) { auto &stage = schedule.stages[stage_idx]; auto &pipeline = *stage.pipeline; @@ -143,12 +159,12 @@ static void ScheduleRuntimeFiltersInternal(PipelineSchedule &schedule, bool clea scan.function.global_initialization == TableFunctionInitialization::INITIALIZE_ON_SCHEDULE) { continue; } - if (!join_build_stages[stage_idx] && (!scan.table_filters || (!scan.table_filters->HasFilters() && - !scan.table_filters->HasMultiColumnFilters()))) { - sources[*scan.dynamic_filters].push_back(stage_idx); - } + const auto small_build_only = + join_build_stages[stage_idx] || + (scan.table_filters && (scan.table_filters->HasFilters() || scan.table_filters->HasMultiColumnFilters())); + sources[*scan.dynamic_filters].push_back({stage_idx, small_build_only}); for (auto &filters : scan.dynamic_filters->GetDisjunctionFilters()) { - sources[filters.get()].push_back(stage_idx); + sources[filters.get()].push_back({stage_idx, false}); } } @@ -157,6 +173,7 @@ static void ScheduleRuntimeFiltersInternal(PipelineSchedule &schedule, bool clea auto &publication = publications[producer]; auto build_estimate = producer.children[1].get().estimated_cardinality; auto probe_estimate = producer.children[0].get().estimated_cardinality; + const auto small_build = add_edges && IsSmallBuild(producer.children[1].get()); for (auto &target : producer.filter_pushdown->probe_info) { if (clear_filters) { // Clear previous executions before any scan can take its filter snapshot. @@ -170,7 +187,12 @@ static void ScheduleRuntimeFiltersInternal(PipelineSchedule &schedule, bool clea build_estimate >= MaxValue(probe_estimate, target.estimated_scan_cardinality)) { continue; } - for (auto execution : source->second) { + for (auto &filter_source : source->second) { + // A small aggregate or join result can still require expensive inputs. + if (filter_source.small_build_only && !small_build) { + continue; + } + auto execution = filter_source.stage_idx; if (dependency_check.TryAddDependency(execution, publication[0])) { schedule.TryAddDependency(execution, publication[0]); } diff --git a/src/duckdb/src/parallel/scan_read_ahead.cpp b/src/duckdb/src/parallel/scan_read_ahead.cpp index edd56bf2a..7fd4750a2 100644 --- a/src/duckdb/src/parallel/scan_read_ahead.cpp +++ b/src/duckdb/src/parallel/scan_read_ahead.cpp @@ -221,6 +221,15 @@ bool ScanReadAhead::HasActiveProducers() const { return active_producers.load() > 0; } +void ScanReadAhead::ReleaseMemoryReservation() { + // a finished scan returns its reservation now, not at query end, so later joins and aggregates can use it + if (!memory_governor) { + return; + } + memory_governor->Release(); + backlog_budget = 0; +} + unique_ptr ScanReadAhead::ClaimJob() { lock_guard guard(lock); if (ready_queue.empty()) { @@ -266,6 +275,7 @@ ScanReadAheadAcquire ScanReadAhead::AcquireJob(ClientContext &context, TableFunc throw InternalException("Read-ahead exhausted with jobs still held back, " "batch indexes must be gapless from 0"); } + ReleaseMemoryReservation(); return ScanReadAheadAcquire::EXHAUSTED; } } diff --git a/src/duckdb/src/parallel/task_scheduler_pool.cpp b/src/duckdb/src/parallel/task_scheduler_pool.cpp index b034ed4cb..ccdf6ccc0 100644 --- a/src/duckdb/src/parallel/task_scheduler_pool.cpp +++ b/src/duckdb/src/parallel/task_scheduler_pool.cpp @@ -34,9 +34,6 @@ struct LightWeightSemaphoreWrapper { struct TaskSchedulerThread { #ifndef DUCKDB_NO_THREADS - explicit TaskSchedulerThread(unique_ptr thread_p) : internal_thread(std::move(thread_p)) { - } - unique_ptr internal_thread; #endif }; @@ -149,45 +146,45 @@ void TaskSchedulerPool::RelaunchThreads(TaskScheduler &scheduler, bool destroy) current_thread_count = threads.size() + (pool_type == TaskSchedulerType::REGULAR ? external_threads : 0); return; } - if (threads.size() != new_thread_count) { - // we are changing the number of threads: clear all threads first - // we do this even when increasing the number of threads to make sure that all threads follow the current - // affinity mask - for (idx_t i = 0; i < threads.size(); i++) { - *markers[i] = false; - } - Signal(threads.size()); - // now join the threads to ensure they are fully stopped before erasing them - for (idx_t i = 0; i < threads.size(); i++) { - threads[i]->internal_thread->join(); - } - // erase the threads/markers - threads.clear(); - markers.clear(); + // allocate what the new workers need before stopping the running ones: if this fails, the old pool and its thread + // count stay as they were + vector available_cpus; + if (new_thread_count > 0) { + available_cpus = GetAvailableCPUsForPinning(pool_type, pin_thread_mode, new_thread_count); + threads.reserve(new_thread_count); + markers.reserve(new_thread_count); } - if (threads.size() < new_thread_count) { - // we are increasing the number of threads: launch them and run tasks on them - idx_t create_new_threads = new_thread_count - threads.size(); - - const auto available_cpus = GetAvailableCPUsForPinning(pool_type, pin_thread_mode, new_thread_count); - for (idx_t i = 0; i < create_new_threads; i++) { + // we are changing the number of threads: clear all threads first + // we do this even when increasing the number of threads to make sure that all threads follow the current + // affinity mask + for (idx_t i = 0; i < threads.size(); i++) { + *markers[i] = false; + } + Signal(threads.size()); + // now join the threads to ensure they are fully stopped before erasing them + for (idx_t i = 0; i < threads.size(); i++) { + threads[i]->internal_thread->join(); + } + // erase the threads/markers + threads.clear(); + markers.clear(); + // launch the new threads and run tasks on them + // destroying a running thread ends the process: the pool owns a thread as soon as it starts, so everything + // that can fail to allocate happens before the thread is created + for (idx_t i = 0; i < new_thread_count; i++) { + try { // launch a thread and assign it a cancellation marker auto marker = unique_ptr>(new atomic(true)); - unique_ptr worker_thread; - try { - const auto cpu = threads.size() < available_cpus.size() ? optional_idx(available_cpus[threads.size()]) - : optional_idx(); - worker_thread = - make_uniq(&TaskScheduler::ExecuteForever, &scheduler, marker.get(), pool_type, cpu); - } catch (std::exception &ex) { - // thread constructor failed - this can happen when the system has too many threads allocated - // in this case we cannot allocate more threads - stop launching them - break; - } - auto thread_wrapper = make_uniq(std::move(worker_thread)); - + auto thread_wrapper = make_uniq(); + const auto cpu = i < available_cpus.size() ? optional_idx(available_cpus[i]) : optional_idx(); + thread_wrapper->internal_thread = + make_uniq(&TaskScheduler::ExecuteForever, &scheduler, marker.get(), pool_type, cpu); threads.push_back(std::move(thread_wrapper)); markers.push_back(std::move(marker)); + } catch (std::exception &ex) { + // thread constructor failed - this can happen when the system has too many threads allocated, or when + // the marker cannot be allocated - in this case we cannot launch more threads - stop launching them + break; } } current_thread_count = threads.size() + (pool_type == TaskSchedulerType::REGULAR ? external_threads : 0); diff --git a/src/duckdb/src/parser/parsed_data/alter_info.cpp b/src/duckdb/src/parser/parsed_data/alter_info.cpp index 38f57252a..4490b593e 100644 --- a/src/duckdb/src/parser/parsed_data/alter_info.cpp +++ b/src/duckdb/src/parser/parsed_data/alter_info.cpp @@ -1,4 +1,5 @@ #include "duckdb/parser/parsed_data/alter_info.hpp" + #include "duckdb/catalog/dependency_list.hpp" #include "duckdb/parser/parsed_data/alter_table_info.hpp" @@ -17,6 +18,17 @@ AlterInfo::AlterInfo(AlterType type) : ParseInfo(TYPE), type(type) { AlterInfo::~AlterInfo() { } +vector> AlterInfo::GetTypesToBind() { + return {}; +} + +vector AlterInfo::GetEntryLookupTypes() const { + return {GetCatalogType()}; +} + +void AlterInfo::SetResolvedEntryType(CatalogType type) { +} + AlterEntryData AlterInfo::GetAlterEntryData() const { return AlterEntryData(GetQualifiedName(), if_not_found); } diff --git a/src/duckdb/src/parser/parsed_data/alter_macro_info.cpp b/src/duckdb/src/parser/parsed_data/alter_macro_info.cpp new file mode 100644 index 000000000..7bdc26c4c --- /dev/null +++ b/src/duckdb/src/parser/parsed_data/alter_macro_info.cpp @@ -0,0 +1,82 @@ +#include "duckdb/parser/parsed_data/alter_macro_info.hpp" + +namespace duckdb { + +//===--------------------------------------------------------------------===// +// AlterMacroInfo +//===--------------------------------------------------------------------===// +AlterMacroInfo::AlterMacroInfo(AlterMacroType alter_macro_type) + : AlterInfo(AlterType::ALTER_MACRO), alter_macro_type(alter_macro_type), + entry_catalog_type(CatalogType::MACRO_ENTRY) { +} + +AlterMacroInfo::AlterMacroInfo(AlterMacroType alter_macro_type, const AlterEntryData &data, + CatalogType entry_catalog_type) + : AlterInfo(AlterType::ALTER_MACRO, data.qualified_name, data.if_not_found), alter_macro_type(alter_macro_type), + entry_catalog_type(entry_catalog_type) { +} + +AlterMacroInfo::~AlterMacroInfo() { +} + +CatalogType AlterMacroInfo::GetCatalogType() const { + return entry_catalog_type; +} + +vector AlterMacroInfo::GetEntryLookupTypes() const { + if (entry_catalog_type == CatalogType::MACRO_ENTRY) { + return {CatalogType::MACRO_ENTRY, CatalogType::TABLE_MACRO_ENTRY}; + } + return {entry_catalog_type}; +} + +void AlterMacroInfo::SetResolvedEntryType(CatalogType type) { + entry_catalog_type = type; +} + +//===--------------------------------------------------------------------===// +// RemoveMacroOverloadInfo +//===--------------------------------------------------------------------===// +RemoveMacroOverloadInfo::RemoveMacroOverloadInfo() : AlterMacroInfo(AlterMacroType::REMOVE_OVERLOAD) { +} + +RemoveMacroOverloadInfo::RemoveMacroOverloadInfo(const AlterEntryData &data, CatalogType entry_catalog_type, + vector signature) + : AlterMacroInfo(AlterMacroType::REMOVE_OVERLOAD, data, entry_catalog_type), signature(std::move(signature)) { +} + +RemoveMacroOverloadInfo::~RemoveMacroOverloadInfo() { +} + +unique_ptr RemoveMacroOverloadInfo::Copy() const { + auto result = make_uniq(GetAlterEntryData(), entry_catalog_type, signature); + result->allow_internal = allow_internal; + return std::move(result); +} + +vector> RemoveMacroOverloadInfo::GetTypesToBind() { + vector> result; + for (auto &type : signature) { + result.push_back(type); + } + return result; +} + +string RemoveMacroOverloadInfo::ToString() const { + // the alter is how a signature drop executes: render the statement that produces it + string result = "DROP " + ParseInfo::TypeToString(entry_catalog_type); + if (if_not_found == OnEntryNotFound::RETURN_NULL) { + result += " IF EXISTS"; + } + result += " " + GetQualifiedName().ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA) + "("; + for (idx_t i = 0; i < signature.size(); i++) { + if (i > 0) { + result += ", "; + } + result += signature[i].ToString(); + } + result += ");"; + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/parser/parsed_data/create_index_info.cpp b/src/duckdb/src/parser/parsed_data/create_index_info.cpp index 82cffa43f..f9d18f9df 100644 --- a/src/duckdb/src/parser/parsed_data/create_index_info.cpp +++ b/src/duckdb/src/parser/parsed_data/create_index_info.cpp @@ -1,7 +1,6 @@ #include "duckdb/parser/parsed_data/create_index_info.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" -#include "duckdb/parser/parsed_expression_iterator.hpp" namespace duckdb { @@ -15,15 +14,16 @@ CreateIndexInfo::CreateIndexInfo(const duckdb::CreateIndexInfo &info) SetQualifiedName(info.GetQualifiedName()); } -static void RemoveTableQualificationRecursive(unique_ptr &root_expr, const Identifier &table_name) { - ParsedExpressionIterator::VisitExpressionMutable( - *root_expr, [&](ColumnRefExpression &col_ref) { - auto &col_names = col_ref.ColumnNamesMutable(); - // the table qualifier is the component directly before the column name - if (col_ref.IsQualified() && col_names[col_names.size() - 2] == table_name) { - col_names.erase(col_names.begin()); - } - }); +// only a top-level column reference is qualified with the table name when the index is created, column references +// inside expressions are stored as written (and may be struct fields of a column named like the table) +static void RemoveTableQualification(ParsedExpression &expr, const Identifier &table_name) { + if (expr.GetExpressionType() != ExpressionType::COLUMN_REF) { + return; + } + auto &col_names = expr.Cast().ColumnNamesMutable(); + if (col_names.size() == 2 && col_names[0] == table_name) { + col_names.erase(col_names.begin()); + } } vector CreateIndexInfo::ExpressionsToList() const { @@ -33,9 +33,8 @@ vector CreateIndexInfo::ExpressionsToList() const { auto &expr = parsed_expressions[i]; auto copy = expr->Copy(); - // Column reference expressions are qualified with the table name. - // We need to remove them to reproduce the original query. - RemoveTableQualificationRecursive(copy, table); + // column references are qualified with the table name, remove it to reproduce the original query + RemoveTableQualification(*copy, table); bool add_parenthesis = true; if (copy->GetExpressionType() == ExpressionType::COLUMN_REF) { auto &column_ref = copy->Cast(); diff --git a/src/duckdb/src/parser/parsed_data/load_info.cpp b/src/duckdb/src/parser/parsed_data/load_info.cpp index 15f198b7f..ca1676f37 100644 --- a/src/duckdb/src/parser/parsed_data/load_info.cpp +++ b/src/duckdb/src/parser/parsed_data/load_info.cpp @@ -63,6 +63,10 @@ static string RepositoryToString(const LoadInfo &info) { result += "IF NOT EXISTS "; } result += SQLIdentifier(info.repository); + if (info.repository_url.empty()) { + // no prefix: the host names it + return result + ";"; + } result += " WITH PREFIX " + SQLString(info.repository_url); if (!info.public_keys.empty()) { result += info.public_keys.size() > 1 ? " USING PUBLIC KEYS " : " USING PUBLIC KEY "; diff --git a/src/duckdb/src/parser/parser.cpp b/src/duckdb/src/parser/parser.cpp index a698e893a..20a5afc49 100644 --- a/src/duckdb/src/parser/parser.cpp +++ b/src/duckdb/src/parser/parser.cpp @@ -287,25 +287,26 @@ void Parser::ParseQuery(const string &query_p) { // PEG parser: tokenize, then peel one TopLevelStatement at a time. On per-statement PEG // failure, hand the rest of the query to parse_function extensions; the extension reports // how many bytes it consumed and we advance the token cursor past them. - auto owned_tokens = make_uniq>(); - ParserTokenizerBehavior behavior(query, *owned_tokens); + ParserTokenizerBehavior behavior(query); auto &tokenizer = GetGrammar().GetTokenizer(); tokenizer.TokenizeInput(behavior); - TokenIterator token_iterator(std::move(owned_tokens)); + TokenIterator token_iterator(behavior); + // A statement's text starts where the previous one ended, so comments and whitespace before its + // first token belong to it; the last statement runs to the end of the input. + idx_t stmt_start = 0; while (token_iterator.Current()) { auto stmt = ParseTopLevelStatement(token_iterator, query); + auto stmt_end = token_iterator.ConsumedEndOffset(); if (stmt) { + stmt->stmt_location = QueryLocation(stmt_start, stmt_end - stmt_start); statements.push_back(std::move(stmt)); } + stmt_start = stmt_end; } if (!statements.empty()) { - for (idx_t i = 0; i + 1 < statements.size(); i++) { - auto start = statements[i]->stmt_location.offset; - statements[i]->stmt_location = QueryLocation(start, statements[i + 1]->stmt_location.offset - start); - } - statements.back()->stmt_location = QueryLocation(statements.back()->stmt_location.offset, - query.size() - statements.back()->stmt_location.offset); + auto &last_location = statements.back()->stmt_location; + last_location = QueryLocation(last_location.offset, query.size() - last_location.offset); for (auto &statement : statements) { statement->query = query.substr(statement->stmt_location.offset, statement->stmt_location.length); statement->stmt_location = QueryLocation(0, statement->query.size()); @@ -427,8 +428,7 @@ bool Parser::IsQueryComplete(const string &query_p) { return true; } auto &grammar = GetGrammar(); - auto owned_tokens = make_uniq>(); - CompletenessTokenizerBehavior behavior(query, *owned_tokens); + CompletenessTokenizerBehavior behavior(query); grammar.GetTokenizer().TokenizeInput(behavior); if (behavior.fatal_token) { // no continuation can repair the input - submit it so the error surfaces @@ -439,7 +439,7 @@ bool Parser::IsQueryComplete(const string &query_p) { } // the final statement must be terminated by a top-level semicolon bool terminated = false; - for (auto &token : *owned_tokens) { + for (auto &token : behavior.tokens) { switch (token.type) { case TokenType::END_OF_INPUT: case TokenType::END_OF_INPUT_AUTOCOMPLETE: @@ -456,7 +456,7 @@ bool Parser::IsQueryComplete(const string &query_p) { if (!terminated) { return false; } - TokenIterator token_iterator(std::move(owned_tokens)); + TokenIterator token_iterator(behavior); while (!token_iterator.AtEnd()) { // match one TopLevelStatement without transforming it - statements that match but cannot be // transformed classify as complete either way, and the transformer can expand matched input @@ -504,10 +504,10 @@ bool Parser::IsQueryComplete(const string &query_p) { vector Parser::Tokenize(const string &query) { auto &keyword_helper = DuckDBKeywordHelper::Instance(); - vector tokens; - HighlightTokenizerBehavior behavior(query, tokens); + HighlightTokenizerBehavior behavior(query); Tokenizer tokenizer(keyword_helper); tokenizer.TokenizeInput(behavior); + auto &tokens = behavior.tokens; vector result; result.reserve(tokens.size()); diff --git a/src/duckdb/src/parser/peg/autocomplete_core.cpp b/src/duckdb/src/parser/peg/autocomplete_core.cpp index 030e47fb9..1cc972105 100644 --- a/src/duckdb/src/parser/peg/autocomplete_core.cpp +++ b/src/duckdb/src/parser/peg/autocomplete_core.cpp @@ -164,9 +164,8 @@ bool ReplaceUnicodeSpaces(const string &query, string &new_query, const vector &tokens, - vector &suggestions_p) - : TokenizerBehavior(sql, tokens), suggestions(suggestions_p) { + AutoCompleteTokenizerBehavior(const string &sql, vector &suggestions_p) + : TokenizerBehavior(sql), suggestions(suggestions_p) { last_pos = 0; } @@ -199,21 +198,20 @@ vector GenerateAutoCompleteSuggestions(AutoCompleteCatal AutoCompleteParameters ¶meters) { // tokenize the input auto compiled_grammar = provider.GetCompiledGrammar(); - vector tokens; vector suggestions; ParseResultAllocator parse_allocator; idx_t max_token_index = 0; vector unicode_spaces; string clean_sql; const string &sql_ref = Parser::StripUnicodeSpaces(sql, clean_sql) ? clean_sql : sql; - AutoCompleteTokenizerBehavior behavior(sql_ref, tokens, suggestions); + AutoCompleteTokenizerBehavior behavior(sql_ref, suggestions); if (!compiled_grammar->GetTokenizer().TokenizeInput(behavior)) { return {}; } if (suggestions.empty()) { // no suggestions found during tokenizing // run the root matcher - TokenIterator token_iterator(tokens); + TokenIterator token_iterator(behavior); ArenaAllocator process_allocator(Allocator::DefaultAllocator()); // memoize match results so backtracking over unbalanced input stays polynomial ArenaAllocator packrat_allocator(Allocator::DefaultAllocator()); diff --git a/src/duckdb/src/parser/peg/matcher_factory.cpp b/src/duckdb/src/parser/peg/matcher_factory.cpp index f4f4af052..eba2aa15c 100644 --- a/src/duckdb/src/parser/peg/matcher_factory.cpp +++ b/src/duckdb/src/parser/peg/matcher_factory.cpp @@ -230,6 +230,7 @@ Matcher &MatcherFactory::CreateRootMatcher(const string &root_rule) { //===--------------------------------------------------------------------===// AddPackratMemoizedRule("Expression"); AddPackratMemoizedRule("TableRef"); + AddPackratMemoizedRule("ParensTableRef"); AddPackratMemoizedRule("Identifier"); AddPackratMemoizedRule("ColId"); AddPackratMemoizedRule("CatalogQualification"); diff --git a/src/duckdb/src/parser/peg/matcher_stack.cpp b/src/duckdb/src/parser/peg/matcher_stack.cpp index 5d63e3a0a..fe246ff16 100644 --- a/src/duckdb/src/parser/peg/matcher_stack.cpp +++ b/src/duckdb/src/parser/peg/matcher_stack.cpp @@ -783,7 +783,8 @@ MatchStep MatchStack::ExecuteInternal(optional_ptr stack, MatchStack break; } } - if (has_child) { + D_ASSERT(!has_child || next); + if (has_child && next) { if (SINGLE_STEP) { return MatchStep::Child(*next); } diff --git a/src/duckdb/src/parser/peg/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index f709da5cb..7707a8543 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -460,11 +460,18 @@ static const char *const PEG_RULE_NAMES[] = { "DescRule", "DetachStatement", "DropStatement", + "DropMemberStatement", + "DropMember", + "DropTableFunctionMember", + "DropFunctionMember", "DropEntries", "DropTrigger", "DropTable", "DropTableFunction", "DropFunction", + "DropFunctionSignature", + "DropSignatureType", + "DropSignatureAnyType", "DropSchema", "DropIndex", "QualifiedIndexName", @@ -842,12 +849,16 @@ static const char *const PEG_RULE_NAMES[] = { "FromSource", "FromSourceIdentifier", "FromSourceString", + "FromSourceName", "VersionNumber", "ExtensionRepositoryStatement", "CreateExtensionRepositoryStmt", "RepositoryPrefix", "RepositoryPublicKey", + "CreateExtensionRepositoryFromHostStmt", "DropExtensionRepositoryStmt", + "ExtensionRepositoryName", + "ExtensionRepositoryHostName", "TableMatchRecognizeClause", "MatchRecognizeBody", "MatchRecognizeClause", @@ -1012,6 +1023,8 @@ static const char *const PEG_RULE_NAMES[] = { "TableAliasColon", "ValuesRef", "ParensTableRef", + "JoinedTableRef", + "JoinedTableRefChain", "JoinOrPivot", "TablePivotClause", "TablePivotClauseBody", diff --git a/src/duckdb/src/parser/peg/sql_formatter.cpp b/src/duckdb/src/parser/peg/sql_formatter.cpp index 4240b6076..163317411 100644 --- a/src/duckdb/src/parser/peg/sql_formatter.cpp +++ b/src/duckdb/src/parser/peg/sql_formatter.cpp @@ -94,10 +94,10 @@ SQLFormatter::SQLFormatter(const FormatterConfig &config) : config(config) { vector SQLFormatter::Tokenize(const string &sql) { auto &keyword_helper = DuckDBKeywordHelper::Instance(); - vector tokens; - HighlightTokenizerBehavior behavior(sql, tokens); + HighlightTokenizerBehavior behavior(sql); Tokenizer tokenizer(keyword_helper); tokenizer.TokenizeInput(behavior); + auto tokens = std::move(behavior.tokens); if (!tokens.empty()) { auto back_type = tokens.back().type; if (back_type == TokenType::END_OF_INPUT || back_type == TokenType::END_OF_INPUT_AUTOCOMPLETE) { diff --git a/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp b/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp index 11f6b5fa8..b867d290f 100644 --- a/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp +++ b/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp @@ -29,7 +29,7 @@ uint8_t ComputeMatcherTokenClass(TokenType type, const string &text) { } } -TokenizerBehavior::TokenizerBehavior(const string &sql, vector &tokens) : sql(sql), tokens(tokens) { +TokenizerBehavior::TokenizerBehavior(const string &sql) : sql(sql) { } Tokenizer::Tokenizer(const PEGKeywordHelper &keyword_helper_p) : keyword_helper(keyword_helper_p) { @@ -441,12 +441,19 @@ bool Tokenizer::TokenizeInputInternal(TokenizerBehavior &behavior) const { last_pos = i + 1; break; } - if (CharacterIsInitialNumber(c)) { - // parse a numeric literal + // '.' 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])))) { 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)) { // Look ahead to see if a quote follows if (i + 1 < sql.size() && sql[i + 1] == '\'') { diff --git a/src/duckdb/src/parser/peg/tokenizer/highlight_tokenizer.cpp b/src/duckdb/src/parser/peg/tokenizer/highlight_tokenizer.cpp index 0dac034d6..19e89e9c7 100644 --- a/src/duckdb/src/parser/peg/tokenizer/highlight_tokenizer.cpp +++ b/src/duckdb/src/parser/peg/tokenizer/highlight_tokenizer.cpp @@ -2,8 +2,7 @@ namespace duckdb { -HighlightTokenizerBehavior::HighlightTokenizerBehavior(const string &sql, vector &tokens) - : TokenizerBehavior(sql, tokens) { +HighlightTokenizerBehavior::HighlightTokenizerBehavior(const string &sql) : TokenizerBehavior(sql) { } void HighlightTokenizerBehavior::PushToken(idx_t start, idx_t end, TokenType type, bool unterminated) { diff --git a/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp b/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp index d6ee3d51b..5904c5e78 100644 --- a/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp +++ b/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp @@ -10,8 +10,7 @@ bool ParserTokenizerBehavior::IsEmptyQuotedIdentifier(const string &sql, idx_t s return (sql[start] == '"' && sql[start + 1] == '"') || (sql[start] == '`' && sql[start + 1] == '`'); } -ParserTokenizerBehavior::ParserTokenizerBehavior(const string &sql, vector &tokens) - : TokenizerBehavior(sql, tokens) { +ParserTokenizerBehavior::ParserTokenizerBehavior(const string &sql) : TokenizerBehavior(sql) { } void ParserTokenizerBehavior::PushToken(idx_t start, idx_t end, TokenType type, bool unterminated) { diff --git a/src/duckdb/src/parser/peg/transformer/transform_drop.cpp b/src/duckdb/src/parser/peg/transformer/transform_drop.cpp index ecc4f4394..9a1cdfea5 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_drop.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_drop.cpp @@ -1,5 +1,7 @@ #include "duckdb/parser/peg/transformer/peg_transformer.hpp" +#include "duckdb/parser/parsed_data/alter_macro_info.hpp" #include "duckdb/parser/parsed_data/extra_drop_info.hpp" +#include "duckdb/parser/statement/alter_statement.hpp" #include "duckdb/parser/tableref/basetableref.hpp" namespace duckdb { @@ -79,6 +81,51 @@ PEGTransformerFactory::TransformDropFunction(PEGTransformer &transformer, const return result; } +unique_ptr PEGTransformerFactory::TransformDropMemberStatement(PEGTransformer &transformer, + unique_ptr drop_member, + const optional &drop_behavior) { + if (drop_behavior && *drop_behavior) { + // removing an overload is an alter: dependents block it, and only dropping the macro can cascade + throw ParserException("Cannot drop an overload of %s with CASCADE: drop the dependent entries first, or " + "drop the whole macro", + drop_member->GetQualifiedName().Name()); + } + auto result = make_uniq(); + result->info = std::move(drop_member); + return std::move(result); +} + +//! A parameter type list on DROP names one overload member: removing it alters the macro entry +static unique_ptr MakeRemoveOverloadInfo(const QualifiedName &name, CatalogType type, + const optional &if_exists, vector signature) { + auto if_not_found = if_exists ? OnEntryNotFound::RETURN_NULL : OnEntryNotFound::THROW_EXCEPTION; + AlterEntryData data(name, if_not_found); + return make_uniq(data, type, std::move(signature)); +} + +unique_ptr PEGTransformerFactory::TransformDropTableFunctionMember( + PEGTransformer &transformer, const CatalogType &comment_macro_table, const optional &if_exists, + const QualifiedName &qualified_table_function, const vector &drop_function_signature) { + return MakeRemoveOverloadInfo(qualified_table_function, comment_macro_table, if_exists, drop_function_signature); +} + +unique_ptr PEGTransformerFactory::TransformDropFunctionMember( + PEGTransformer &transformer, const bool &function_type_macro, const optional &if_exists, + const QualifiedName &function_identifier, const vector &drop_function_signature) { + return MakeRemoveOverloadInfo(function_identifier, CatalogType::MACRO_ENTRY, if_exists, drop_function_signature); +} + +vector PEGTransformerFactory::TransformDropFunctionSignature(PEGTransformer &transformer, + const optional> &type) { + // empty parentheses identify the zero-parameter overload + return type ? *type : vector(); +} + +LogicalType PEGTransformerFactory::TransformDropSignatureAnyType(PEGTransformer &transformer) { + // ANY names an untyped parameter slot of the stored overload + return LogicalType(LogicalTypeId::ANY); +} + unique_ptr PEGTransformerFactory::TransformDropSchema(PEGTransformer &transformer, const optional &if_exists, const vector &qualified_name) { 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 0f4e3fadb..49a218578 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -2445,7 +2445,80 @@ static const TransformChildPlan FRAME_CHILDREN_171[] = {{PEGRuleId::DropBehavior {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::BaseTableName, +static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DropMember, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_186 = {FRAME_CHILDREN_172, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::DropFunctionSignature, + TransformChildKind::REQUIRED, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentMacroTable, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_187 = {FRAME_CHILDREN_173, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::DropFunctionSignature, + TransformChildKind::REQUIRED, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionIdentifier, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionTypeMacro, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_188 = {FRAME_CHILDREN_174, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 4, 2, @@ -2466,8 +2539,8 @@ static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::BaseTableNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_186 = {FRAME_CHILDREN_172, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_189 = {FRAME_CHILDREN_175, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::BaseTableName, TransformChildKind::LIST, 2, 2, @@ -2488,8 +2561,8 @@ static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::BaseTableNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_187 = {FRAME_CHILDREN_173, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::QualifiedTableFunction, +static const TransformFramePlan FRAME_PLAN_190 = {FRAME_CHILDREN_176, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::QualifiedTableFunction, TransformChildKind::LIST, 2, 2, @@ -2510,8 +2583,8 @@ static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::QualifiedTab false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_188 = {FRAME_CHILDREN_174, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::FunctionIdentifier, +static const TransformFramePlan FRAME_PLAN_191 = {FRAME_CHILDREN_177, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::FunctionIdentifier, TransformChildKind::LIST, 2, 2, @@ -2532,8 +2605,16 @@ static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::FunctionIden false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_189 = {FRAME_CHILDREN_175, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::QualifiedName, +static const TransformFramePlan FRAME_PLAN_192 = {FRAME_CHILDREN_178, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_179[] = {{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, TransformChildKind::LIST, 2, 1, @@ -2547,8 +2628,8 @@ static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::QualifiedNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_190 = {FRAME_CHILDREN_176, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::QualifiedIndexName, +static const TransformFramePlan FRAME_PLAN_194 = {FRAME_CHILDREN_180, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::QualifiedIndexName, TransformChildKind::LIST, 2, 1, @@ -2562,8 +2643,8 @@ static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::QualifiedInd false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_191 = {FRAME_CHILDREN_177, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_195 = {FRAME_CHILDREN_181, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::REQUIRED, 1, 1, @@ -2577,8 +2658,8 @@ static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_192 = {FRAME_CHILDREN_178, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_179[] = {{PEGRuleId::QualifiedSequenceName, +static const TransformFramePlan FRAME_PLAN_196 = {FRAME_CHILDREN_182, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::QualifiedSequenceName, TransformChildKind::LIST, 2, 1, @@ -2592,8 +2673,8 @@ static const TransformChildPlan FRAME_CHILDREN_179[] = {{PEGRuleId::QualifiedSeq false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_193 = {FRAME_CHILDREN_179, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_180[] = {{PEGRuleId::CollationName, +static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::CollationName, TransformChildKind::LIST, 2, 1, @@ -2607,8 +2688,8 @@ static const TransformChildPlan FRAME_CHILDREN_180[] = {{PEGRuleId::CollationNam 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::QualifiedTypeName, +static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::QualifiedTypeName, TransformChildKind::LIST, 2, 1, @@ -2622,8 +2703,8 @@ static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::QualifiedTyp 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::DropSecretStorage, +static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::DropSecretStorage, TransformChildKind::OPTIONAL, 4, 3, @@ -2651,8 +2732,8 @@ static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::DropSecretSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_196 = {FRAME_CHILDREN_182, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::TableFunctionArguments, +static const TransformFramePlan FRAME_PLAN_200 = {FRAME_CHILDREN_186, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::TableFunctionArguments, TransformChildKind::OPTIONAL, 2, 1, @@ -2666,8 +2747,8 @@ static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::TableFunctio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::ExplainableStatements, +static const TransformFramePlan FRAME_PLAN_201 = {FRAME_CHILDREN_187, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExplainableStatements, TransformChildKind::REQUIRED, 3, 2, @@ -2688,16 +2769,16 @@ static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::ExplainableS false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::ExplainOption, +static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_188, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::ExplainOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_189, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 1, 1, @@ -2711,9 +2792,9 @@ static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::Expression, 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 TransformFramePlan FRAME_PLAN_204 = {FRAME_CHILDREN_190, 2, 2, false, 0, {}}; static const char *const FRAME_NAMES_8[] = {"FuncNameKeyword", "TypeNameKeyword"}; -static const TransformFramePlan FRAME_PLAN_201 = {nullptr, +static const TransformFramePlan FRAME_PLAN_205 = {nullptr, 0, 1, false, @@ -2722,15 +2803,15 @@ static const TransformFramePlan FRAME_PLAN_201 = {nullptr, ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING), 0, true, false, 2, FRAME_NAMES_8}}; -static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::SelectStatementInternal, +static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_187, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExportOptions, +static const TransformFramePlan FRAME_PLAN_206 = {FRAME_CHILDREN_191, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::ExportOptions, TransformChildKind::OPTIONAL, 4, 1, @@ -2744,8 +2825,8 @@ static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExportOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_188, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::REPEAT, 3, 3, @@ -2773,8 +2854,8 @@ static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_204 = {FRAME_CHILDREN_189, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::ReservedTableQualification, +static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedTableQualification, TransformChildKind::REQUIRED, 2, 2, @@ -2795,8 +2876,8 @@ static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::ReservedTabl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_205 = {FRAME_CHILDREN_190, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::ReservedTableQualification, +static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::ReservedTableQualification, TransformChildKind::REQUIRED, 1, 1, @@ -2810,16 +2891,16 @@ static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::ReservedTabl 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::TableQualification, +static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::TableQualification, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::OverClause, +static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::OverClause, TransformChildKind::OPTIONAL, 5, 4, @@ -2854,16 +2935,16 @@ static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::OverClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::FunctionExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::FunctionExpressionArgumentList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_213 = {FRAME_CHILDREN_198, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -2891,16 +2972,16 @@ static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::FunctionArgument, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -2914,32 +2995,32 @@ static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::OrderByClause, +static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_213 = {FRAME_CHILDREN_198, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::FilterClauseExpression, +static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::FilterClauseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::FilterClauseContents, +static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::FilterClauseContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::CastArguments, +static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::CastArguments, TransformChildKind::REQUIRED, 1, 1, @@ -2953,8 +3034,8 @@ static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::CastArgument false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::Type, +static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::Type, TransformChildKind::REQUIRED, 2, 1, @@ -2968,8 +3049,8 @@ static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::Type, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::RenameList, +static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::RenameList, TransformChildKind::OPTIONAL, 4, 3, @@ -2997,72 +3078,72 @@ static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::RenameList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::ColIdDot, +static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::ColIdDot, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::ExcludeNames, +static const TransformFramePlan FRAME_PLAN_223 = {FRAME_CHILDREN_208, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_209[] = {{PEGRuleId::ExcludeNames, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::ExcludeName, +static const TransformFramePlan FRAME_PLAN_224 = {FRAME_CHILDREN_209, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_210[] = {{PEGRuleId::ExcludeName, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::ExcludeName, +static const TransformFramePlan FRAME_PLAN_225 = {FRAME_CHILDREN_210, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_211[] = {{PEGRuleId::ExcludeName, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::DottedIdentifier, +static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::DottedIdentifier, TransformChildKind::REQUIRED, 0, 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::ReplaceEntries, +static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::ReplaceEntries, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_224 = {FRAME_CHILDREN_209, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_210[] = {{PEGRuleId::ReplaceEntry, +static const TransformFramePlan FRAME_PLAN_228 = {FRAME_CHILDREN_213, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_214[] = {{PEGRuleId::ReplaceEntry, 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::ReplaceEntry, +static const TransformFramePlan FRAME_PLAN_229 = {FRAME_CHILDREN_214, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ReplaceEntry, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::ColumnReference, +static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::ColumnReference, TransformChildKind::REQUIRED, 2, 1, @@ -3076,32 +3157,32 @@ static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::ColumnRefere false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::RenameEntries, +static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::RenameEntries, TransformChildKind::REQUIRED, 1, 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::RenameEntry, +static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::RenameEntry, 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::RenameEntry, +static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::RenameEntry, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 2, 2, @@ -3122,8 +3203,8 @@ static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::CaseElse, +static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::CaseElse, TransformChildKind::OPTIONAL, 3, 2, @@ -3144,8 +3225,8 @@ static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::CaseElse, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::CaseElse, +static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::CaseElse, TransformChildKind::OPTIONAL, 2, 1, @@ -3159,8 +3240,8 @@ static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::CaseElse, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -3174,8 +3255,8 @@ static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_220[] = {{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, @@ -3189,8 +3270,8 @@ static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::Interval, +static const TransformFramePlan FRAME_PLAN_239 = {FRAME_CHILDREN_224, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 1, @@ -3204,8 +3285,8 @@ static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::Interval, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::WindowExcludeClause, +static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::WindowExcludeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3226,16 +3307,16 @@ static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::WindowExclud false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::FrameBound, +static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::FrameBound, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_238 = {FRAME_CHILDREN_223, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::FrameBound, +static const TransformFramePlan FRAME_PLAN_242 = {FRAME_CHILDREN_227, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::FrameBound, TransformChildKind::REQUIRED, 3, 1, @@ -3249,16 +3330,16 @@ static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::FrameBound, 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::PrecedingOrFollowing, +static const TransformFramePlan FRAME_PLAN_243 = {FRAME_CHILDREN_228, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::PrecedingOrFollowing, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::PrecedingOrFollowing, +static const TransformFramePlan FRAME_PLAN_244 = {FRAME_CHILDREN_229, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::PrecedingOrFollowing, TransformChildKind::REQUIRED, 1, 1, @@ -3272,24 +3353,24 @@ static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::PrecedingOrF false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::WindowExcludeElement, +static const TransformFramePlan FRAME_PLAN_245 = {FRAME_CHILDREN_230, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::WindowExcludeElement, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_242 = {FRAME_CHILDREN_227, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::WindowFrameNameContents, +static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowFrameNameContents, TransformChildKind::REQUIRED, 0, 0, false, {1, 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::WindowFrameContents, +static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameContents, TransformChildKind::REQUIRED, 1, 1, @@ -3303,16 +3384,16 @@ static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::WindowFrameC 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::WindowFrameContents, +static const TransformFramePlan FRAME_PLAN_248 = {FRAME_CHILDREN_233, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::WindowFrameContents, TransformChildKind::REQUIRED, 0, 0, false, {1, 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::FrameClause, +static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::FrameClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3333,40 +3414,40 @@ static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::FrameClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_250 = {FRAME_CHILDREN_235, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::BoundedListExpression, +static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::BoundedListExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, 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::Expression, +static const TransformFramePlan FRAME_PLAN_252 = {FRAME_CHILDREN_237, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_238[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::StructField, +static const TransformFramePlan FRAME_PLAN_253 = {FRAME_CHILDREN_238, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_239[] = {{PEGRuleId::StructField, TransformChildKind::OPTIONAL_LIST, 1, 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::Expression, +static const TransformFramePlan FRAME_PLAN_254 = {FRAME_CHILDREN_239, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -3380,24 +3461,24 @@ static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::MapStructExpression, +static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::MapStructExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_252 = {FRAME_CHILDREN_237, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_238[] = {{PEGRuleId::MapStructField, +static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::MapStructField, 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_257 = {FRAME_CHILDREN_242, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -3411,8 +3492,8 @@ 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::Expression, +static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -3426,8 +3507,8 @@ static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::ListComprehensionFilter, +static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::ListComprehensionFilter, TransformChildKind::OPTIONAL, 6, 3, @@ -3455,16 +3536,16 @@ static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::ListComprehe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_257 = {FRAME_CHILDREN_242, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::FunctionExpression, +static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::FunctionExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3478,24 +3559,24 @@ static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::FunctionExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::LogicalOrExpression, +static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::LogicalOrExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::ColDefOrExpr, +static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::ColDefOrExpr, TransformChildKind::REQUIRED, 0, 0, false, {0, 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::LogicalOrExpressionTail, +static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3509,16 +3590,16 @@ static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::LogicalOrExp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::LogicalAndExpression, +static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::LogicalAndExpression, TransformChildKind::REQUIRED, 1, 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::ColDefOrExpressionTail, +static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3532,16 +3613,16 @@ static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::ColDefOrExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::ColDefAndExpr, +static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::ColDefAndExpr, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalAndExpressionTail, +static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::LogicalAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3555,16 +3636,16 @@ static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalAndEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::LogicalNotExpression, +static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::LogicalNotExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefAndExpressionTail, +static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::ColDefAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3578,16 +3659,16 @@ static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefAndExp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::IsDistinctFromExpression, +static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsDistinctFromExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3601,16 +3682,16 @@ static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::NotKeyword, +static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::NotKeyword, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsExpressionContinuation, +static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsExpressionContinuation, TransformChildKind::OPTIONAL, 1, 1, @@ -3624,8 +3705,8 @@ static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsExpressionTail, +static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3639,64 +3720,64 @@ 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, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsTest, +static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::IsTest, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::OtherOperatorTail, 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::CastOperator, +static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::CastOperator, 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::IsLiteralValue, +static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::IsLiteralValue, TransformChildKind::REQUIRED, 2, 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::IsNullOperator, +static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsNullOperator, 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::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3710,8 +3791,8 @@ static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::IsDistinctFr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::ComparisonExpression, +static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3725,8 +3806,8 @@ static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3740,8 +3821,8 @@ static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::ComparisonOperand, +static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::ComparisonOperand, TransformChildKind::REQUIRED, 1, 1, @@ -3755,8 +3836,8 @@ static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::ComparisonOp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3770,8 +3851,8 @@ static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsExpression 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::BetweenLikeOp, +static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::BetweenLikeOp, TransformChildKind::OPTIONAL, 2, 2, @@ -3792,8 +3873,8 @@ static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::BetweenLikeO false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::CastOperator, TransformChildKind::OPTIONAL_REPEAT, 2, 1, @@ -3807,16 +3888,16 @@ static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::CastOperator false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::BetweenLikeOpExpression, +static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::BetweenLikeOpExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::EscapeClause, +static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::EscapeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3837,48 +3918,48 @@ static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::EscapeClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::InExpression, +static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::InExpression, 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::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {1, 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_297 = {FRAME_CHILDREN_282, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 4, 1, @@ -3892,16 +3973,16 @@ static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::InfixOtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::InfixOtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3915,8 +3996,8 @@ static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -3930,8 +4011,8 @@ static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::SubqueryRefe 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::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3945,16 +4026,16 @@ static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::SingleArrowBody, +static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::SingleArrowBody, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::ArrowChainTail, +static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::ArrowChainTail, TransformChildKind::REPEAT, 1, 1, @@ -3968,48 +4049,48 @@ static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::ArrowChainTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::AnyAllOperator, +static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::AnyAllOperator, TransformChildKind::REQUIRED, 0, 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::AnyOrAll, +static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AnyOrAll, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::QualifiedOperatorContents, +static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::QualifiedOperatorContents, TransformChildKind::REQUIRED, 1, 0, false, {1, 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::ColIdDot, +static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::ColIdDot, TransformChildKind::OPTIONAL_REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::BitwiseExpressionTail, +static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::BitwiseExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4023,8 +4104,8 @@ static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4038,8 +4119,8 @@ static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::TildeExpress false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AdditiveExpression, +static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::AdditiveExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4053,8 +4134,8 @@ static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::AdditiveExpressionTail, +static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::AdditiveExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4068,8 +4149,8 @@ static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::AdditiveExpr 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::MultiplicativeExpression, +static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::MultiplicativeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4083,8 +4164,8 @@ static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::Multiplicati 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::MultiplicativeExpressionTail, +static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::MultiplicativeExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4098,8 +4179,8 @@ static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::Multiplicati 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::ExponentiationExpression, +static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::ExponentiationExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4113,8 +4194,8 @@ static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::ExponentiationExpressionTail, +static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::ExponentiationExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4128,8 +4209,8 @@ static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::CollateExpression, +static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::CollateExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4143,8 +4224,8 @@ static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::CollateExpressionTail, +static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::CollateExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4158,16 +4239,16 @@ static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::AtTimeZoneExpression, +static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::AtTimeZoneExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::AtTimeZoneExpressionTail, +static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::AtTimeZoneExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4181,24 +4262,24 @@ static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::AtTimeZoneEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::UnaryExpression, +static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::UnaryExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::TildeExpression, 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::IndirectionList, +static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::IndirectionList, TransformChildKind::OPTIONAL, 1, 1, @@ -4212,24 +4293,24 @@ static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::IndirectionL false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::Indirection, +static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::Indirection, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::MethodExpression, +static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::MethodExpression, 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::MethodExpressionArguments, +static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpressionArguments, TransformChildKind::REQUIRED, 1, 1, @@ -4243,16 +4324,16 @@ static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::MethodExpres 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::MethodExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::MethodExpressionArgumentList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -4280,16 +4361,16 @@ static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::SliceBound, +static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::SliceBound, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::SliceUpperBound, +static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::SliceUpperBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4303,16 +4384,16 @@ static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::SliceUpperBo false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::StepSliceBound, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::StepSliceBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4326,32 +4407,32 @@ static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::StepSliceBou false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 0, false, {1, 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::ExtractArguments, +static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::ExtractArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4365,8 +4446,8 @@ static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -4380,24 +4461,24 @@ static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::NullIfArguments, +static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::NullIfArguments, 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::PositionArguments, +static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::PositionArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4411,32 +4492,32 @@ 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, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::SubstringArguments, +static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::SubstringArguments, 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_343 = {FRAME_CHILDREN_328, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::SubstringFromFor, +static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::SubstringFromFor, TransformChildKind::REQUIRED, 1, 1, @@ -4450,8 +4531,8 @@ static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::SubstringFro false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 1, 1, @@ -4465,24 +4546,24 @@ static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::ForExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::TrimArguments, +static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::TrimArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 2, @@ -4503,24 +4584,24 @@ static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 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::OverlayArguments, +static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::OverlayArguments, 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::ForExpression, +static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 4, 3, @@ -4548,16 +4629,16 @@ static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::ExtractDatePart, +static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::ExtractDatePart, TransformChildKind::REQUIRED, 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::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, 1, @@ -4571,8 +4652,8 @@ static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::ExternalReso false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 5, 1, @@ -4586,16 +4667,16 @@ static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::ColId, +static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::ColId, TransformChildKind::REQUIRED, 2, 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::AttachOptions, +static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 4, 2, @@ -4616,8 +4697,8 @@ static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::AttachOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::AttachOptions, +static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 3, 1, @@ -4631,16 +4712,16 @@ static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::AttachOption 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::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, 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::ReturningClause, +static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 10, 7, @@ -4696,24 +4777,24 @@ static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 8, 8, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::InsertByName, +static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::InsertByName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::InsertByPosition, +static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::InsertByPosition, TransformChildKind::REQUIRED, 1, 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::InsertAlias, +static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::InsertAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -4727,8 +4808,8 @@ static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::InsertAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::OnConflictAction, +static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::OnConflictAction, TransformChildKind::REQUIRED, 3, 1, @@ -4742,8 +4823,8 @@ static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::OnConflictAc false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 1, 1, @@ -4757,16 +4838,16 @@ static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::ConstraintName, +static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::ConstraintName, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 4, 1, @@ -4780,16 +4861,16 @@ static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::WhereClause, 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::TargetList, +static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::ExtensionAlias, +static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::ExtensionAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -4810,8 +4891,8 @@ static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::ExtensionAli false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::VersionNumber, +static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::VersionNumber, TransformChildKind::OPTIONAL, 5, 3, @@ -4839,16 +4920,34 @@ static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::VersionNumbe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::IdentifierOrStringLiteral, +static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::FromSourceName, 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::RepositoryPublicKey, +static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 1, 1, false, 0, {}}; +static const char *const FRAME_NAMES_9[] = {"Identifier"}; +static const TransformFramePlan FRAME_PLAN_372 = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 1, FRAME_NAMES_9}}; +static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_357, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::RepositoryPublicKey, TransformChildKind::OPTIONAL, 7, 4, @@ -4862,7 +4961,7 @@ static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::RepositoryPu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, + {PEGRuleId::ExtensionRepositoryName, TransformChildKind::REQUIRED, 5, 2, @@ -4883,8 +4982,30 @@ static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::RepositoryPu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_374 = {FRAME_CHILDREN_358, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::ExtensionRepositoryName, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrReplace, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_359, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::ExtensionRepositoryName, TransformChildKind::REQUIRED, 4, 1, @@ -4898,8 +5019,23 @@ static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::ColIdOrStrin false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_360, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_361[] = {{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_377 = {FRAME_CHILDREN_361, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -4913,88 +5049,88 @@ static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::MatchRecognizeClause, +static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_362, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::MatchRecognizeClause, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::WindowPartition, +static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_363, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::WindowPartition, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_372 = {FRAME_CHILDREN_357, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::OrderByClause, +static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_364, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_358, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::MeasuresClause, +static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_365, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::MeasuresClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_374 = {FRAME_CHILDREN_359, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::RowsPerMatch, +static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::RowsPerMatch, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_360, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::AfterMatchSkip, +static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::AfterMatchSkip, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_361, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::PatternClause, +static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::PatternClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_362, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::SubsetClause, +static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::SubsetClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_363, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::DefineClause, +static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::DefineClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_364, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::MeasuresElement, +static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_371, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::MeasuresElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_365, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_372, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 1, @@ -5008,48 +5144,48 @@ static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_366, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::AllRowsEmptyMatches, +static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_373, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::AllRowsEmptyMatches, TransformChildKind::OPTIONAL, 4, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::AfterMatchSkipTarget, +static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_374, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::AfterMatchSkipTarget, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_375, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_370[] = {{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, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_371, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::RowPatternAlternative, +static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPatternAlternative, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5063,24 +5199,24 @@ static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::RowPatternAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_372, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::RowPatternTerm, +static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_379, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::RowPatternTerm, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_373, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::RowPatternFactor, +static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_380, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternFactor, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_374, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::RowPatternQuantifier, +static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_381, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPatternQuantifier, TransformChildKind::OPTIONAL, 1, 1, @@ -5094,40 +5230,40 @@ static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::RowPatternQu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_375, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_382, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::RowPattern, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_376, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_383, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_384, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_385, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_379, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::QuantifierReluctant, +static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_386, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::QuantifierReluctant, TransformChildKind::OPTIONAL, 1, 1, @@ -5141,24 +5277,24 @@ static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::QuantifierRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_380, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::QuantifierBounds, +static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_387, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::QuantifierBounds, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_381, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::SubsetElement, +static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_388, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::SubsetElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_382, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_389, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::LIST, 2, 1, @@ -5172,16 +5308,16 @@ static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_383, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::DefineElement, +static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_390, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::DefineElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_384, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_391, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -5195,8 +5331,8 @@ static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_385, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_392, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 7, 5, @@ -5238,16 +5374,16 @@ static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_386, 6, 6, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::TableRef, +static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_393, 6, 6, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::TableRef, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_387, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_394, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 4, 1, @@ -5261,48 +5397,48 @@ static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_388, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::UpdateMatchInfo, +static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_395, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::UpdateMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_389, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::UpdateMatchSetClause, +static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_396, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::UpdateMatchSetClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_390, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_391, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::InsertMatchInfo, +static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_398, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::InsertMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_392, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_399, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_393, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_400, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 1, @@ -5316,16 +5452,16 @@ static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_394, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::UpdateMatchSetInfo, +static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_401, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::UpdateMatchSetInfo, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_395, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_402, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 6, 2, @@ -5346,24 +5482,24 @@ static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_396, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::PivotColumnList, +static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_403, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::PivotColumnList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::PivotColumnEntry, +static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_404, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::PivotColumnEntry, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_398, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_405, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 2, 1, @@ -5377,8 +5513,8 @@ static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::SelectStatem false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_399, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_406, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 4, 1, @@ -5392,48 +5528,48 @@ static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::OptionalPare false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_400, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_407, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_401, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_408, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_402, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::PragmaAssignOrFunction, +static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_409, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::PragmaAssignOrFunction, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_410, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_404, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::PragmaParameters, +static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::PragmaParameters, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_405, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_412, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 4, 2, @@ -5454,11 +5590,11 @@ static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::Statement, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_406, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_407[] = { +static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_413, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_414[] = { {PEGRuleId::Type, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_407, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::SelectSetOpChainTail, +static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_414, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::SelectSetOpChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5472,8 +5608,8 @@ static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::SelectSetOpC false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_408, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::IntersectChain, +static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_415, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::IntersectChain, TransformChildKind::REQUIRED, 1, 1, @@ -5487,8 +5623,8 @@ static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_409, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::IntersectChainTail, +static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_416, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::IntersectChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5502,8 +5638,8 @@ static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_410, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::SelectAtom, +static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_417, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::SelectAtom, TransformChildKind::REQUIRED, 1, 1, @@ -5517,16 +5653,16 @@ static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::SelectAtom, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_411, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_418, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_412, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_419, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 1, @@ -5540,8 +5676,8 @@ static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::DistinctOrAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_413, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::LimitOffset, +static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_420, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::LimitOffset, TransformChildKind::OPTIONAL, 1, 1, @@ -5555,8 +5691,8 @@ static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::LimitOffset, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_414, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::OffsetClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5570,8 +5706,8 @@ static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_415, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::LimitClause, +static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::LimitClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5585,8 +5721,8 @@ static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::LimitClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_416, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 1, 1, @@ -5600,8 +5736,8 @@ static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::FetchClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_424, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::OffsetClause, TransformChildKind::REQUIRED, 1, 1, @@ -5615,32 +5751,32 @@ static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_418, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_425, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_419, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_426, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_420, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::SimpleSelect, +static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_427, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::SimpleSelect, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_421, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::FromClause, +static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_428, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::FromClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5654,8 +5790,8 @@ static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::FromClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::SelectClause, +static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_429, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SelectClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5669,8 +5805,8 @@ static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::SelectClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::CTEBody, +static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_430, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::CTEBody, TransformChildKind::REQUIRED, 5, 4, @@ -5705,24 +5841,24 @@ static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::CTEBody, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_424, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_431, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_425, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_432, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_426, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_433, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TargetList, TransformChildKind::OPTIONAL, 2, 1, @@ -5736,24 +5872,24 @@ static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::TargetList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_427, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::AliasedExpression, +static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_434, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::AliasedExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_428, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::DistinctOnTargets, +static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_435, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::DistinctOnTargets, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_429, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_436, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5788,8 +5924,8 @@ static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_430, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_437, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5824,8 +5960,8 @@ static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_431, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_432[] = {{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, 3, 3, @@ -5853,8 +5989,8 @@ static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_432, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_439, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -5868,7 +6004,7 @@ static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableRef, + {PEGRuleId::JoinedTableRef, TransformChildKind::REQUIRED, 1, 1, @@ -5882,8 +6018,23 @@ static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_433, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_440, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::JoinOrPivot, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InnerTableRef, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_441, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -5897,8 +6048,8 @@ static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_434, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::PivotGroupByList, +static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_442, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::PivotGroupByList, TransformChildKind::OPTIONAL, 3, 2, @@ -5919,16 +6070,16 @@ static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::PivotGroupBy false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_435, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_443, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_436, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_444, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -5949,8 +6100,8 @@ static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::TableAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_437, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::UnpivotValueList, +static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_445, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::UnpivotValueList, TransformChildKind::REPEAT, 2, 1, @@ -5964,16 +6115,16 @@ static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::UnpivotValue false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_438, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::BaseExpression, +static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_446, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::BaseExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_439, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::PivotValueTarget, +static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_447, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::PivotValueTarget, TransformChildKind::REQUIRED, 2, 1, @@ -5987,16 +6138,16 @@ static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::PivotValueTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_440, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::PivotTargetList, +static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_448, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::PivotTargetList, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_441, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::UnpivotTargetList, +static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_449, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::UnpivotTargetList, TransformChildKind::REQUIRED, 2, 1, @@ -6010,16 +6161,16 @@ static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::UnpivotTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_442, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_450, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_443, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_451, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 5, 5, @@ -6061,8 +6212,8 @@ static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_444, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_452, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -6097,8 +6248,8 @@ static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_445, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::SchemaQualification, +static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_453, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::SchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -6112,16 +6263,16 @@ static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::SchemaQualif false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_446, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_454, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::FunctionArgument, TransformChildKind::OPTIONAL_LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_447, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_455, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6135,8 +6286,8 @@ static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_448, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_456, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 2, @@ -6157,8 +6308,8 @@ static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_449, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_457, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 2, 1, @@ -6172,24 +6323,24 @@ static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::ColumnAliase false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_450, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_458, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_451, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::AtSpecifier, +static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_459, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::AtSpecifier, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_452, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_460, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6203,8 +6354,8 @@ static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_453, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_461, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6239,8 +6390,8 @@ static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_454, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_462, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6275,16 +6426,16 @@ static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_455, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::ValuesClause, +static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_463, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::ValuesClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_456, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::WithOrdinality, +static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_464, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::WithOrdinality, TransformChildKind::OPTIONAL, 3, 3, @@ -6312,8 +6463,8 @@ static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::WithOrdinali false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_457, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_465, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -6327,8 +6478,8 @@ static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_458, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_466, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 2, 2, @@ -6349,23 +6500,23 @@ static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_459, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_467, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableRef, + {PEGRuleId::JoinedTableRef, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_460, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::JoinQualifier, +static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_468, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, 3, @@ -6393,8 +6544,8 @@ static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::JoinQualifie false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_461, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_462[] = { +static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_469, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_470[] = { {PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, @@ -6410,8 +6561,8 @@ static const TransformChildPlan FRAME_CHILDREN_462[] = { {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_477 = {FRAME_CHILDREN_462, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::InnerTableRef, +static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_470, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::InnerTableRef, TransformChildKind::REQUIRED, 2, 1, @@ -6425,48 +6576,48 @@ static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::InnerTableRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_463, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::UsingColumnName, +static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_471, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::UsingColumnName, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_464, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::JoinType, +static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_472, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::JoinType, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_465, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::GroupByExpressions, +static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_473, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::GroupByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_466, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleEntry, +static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_474, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::SampleEntry, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_467, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::WindowDefinition, +static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_475, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::WindowDefinition, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_468, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::SampleProperties, +static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_476, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::SampleProperties, TransformChildKind::OPTIONAL, 1, 1, @@ -6480,8 +6631,8 @@ static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::SampleProper false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_469, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::RepeatableSample, +static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_477, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::RepeatableSample, TransformChildKind::OPTIONAL, 2, 2, @@ -6502,8 +6653,8 @@ static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::RepeatableSa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_470, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_471[] = { +static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_478, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_479[] = { {PEGRuleId::SampleSeed, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, 1, 0}}, {PEGRuleId::ColId, TransformChildKind::REQUIRED, @@ -6512,16 +6663,16 @@ static const TransformChildPlan FRAME_CHILDREN_471[] = { false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_471, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::SampleSeed, +static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_479, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::SampleSeed, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_472, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::SampleUnit, +static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_480, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::SampleUnit, TransformChildKind::OPTIONAL, 1, 1, @@ -6535,16 +6686,16 @@ static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::SampleUnit, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_473, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_481, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_474, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_482, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -6558,32 +6709,32 @@ static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_475, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_483, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_476, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::OrderByExpressions, +static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_484, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::OrderByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_477, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::OrderByExpression, +static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_485, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::OrderByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_478, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::NullsFirstOrLast, +static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_486, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::NullsFirstOrLast, TransformChildKind::OPTIONAL, 2, 1, @@ -6597,32 +6748,32 @@ static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::NullsFirstOr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_479, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::LimitValue, +static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_487, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::LimitValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_480, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::OffsetValue, +static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::OffsetValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_481, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::FetchValue, +static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::FetchValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_482, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_490, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6636,56 +6787,56 @@ static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_483, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::ValuesExpressions, +static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_491, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::ValuesExpressions, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_484, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::SetAssignmentOrTimeZone, +static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_492, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::SetAssignmentOrTimeZone, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_485, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_486, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::ResetTarget, +static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::ResetTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_487, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::SettingScope, +static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::SettingScope, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::SetVariableOrSetting, +static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SetVariableOrSetting, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::SetAssignment, +static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_497, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::SetAssignment, TransformChildKind::REQUIRED, 1, 1, @@ -6699,8 +6850,8 @@ static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::SetAssignmen false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_490, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::ZoneValue, +static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_498, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::ZoneValue, TransformChildKind::REQUIRED, 3, 1, @@ -6714,48 +6865,48 @@ static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::ZoneValue, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_491, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::Interval, +static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_499, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_492, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::VariableScope, +static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_500, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::VariableScope, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::ReadOrWrite, +static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::ReadOrWrite, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::ReadOnlyOrReadWrite, +static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_503, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReadOnlyOrReadWrite, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_504, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 6, 5, @@ -6797,8 +6948,8 @@ static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_497, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::UpdateAlias, +static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_505, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::UpdateAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -6812,16 +6963,16 @@ static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::UpdateAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_498, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::UpdateSetClause, +static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_506, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::UpdateSetClause, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_499, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_523 = {FRAME_CHILDREN_507, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6835,32 +6986,32 @@ static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_500, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_524 = {FRAME_CHILDREN_508, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_509[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_501, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::UseTarget, +static const TransformFramePlan FRAME_PLAN_525 = {FRAME_CHILDREN_509, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_510[] = {{PEGRuleId::UseTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_526 = {FRAME_CHILDREN_510, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_503, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::AnalyzeTarget, +static const TransformFramePlan FRAME_PLAN_527 = {FRAME_CHILDREN_511, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::AnalyzeTarget, TransformChildKind::OPTIONAL, 2, 1, @@ -6874,16 +7025,16 @@ static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::AnalyzeTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_504, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::VacuumOption, +static const TransformFramePlan FRAME_PLAN_528 = {FRAME_CHILDREN_512, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::VacuumOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_505, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::OptAnalyze, +static const TransformFramePlan FRAME_PLAN_529 = {FRAME_CHILDREN_513, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::OptAnalyze, TransformChildKind::OPTIONAL, 3, 3, @@ -6911,15 +7062,15 @@ static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::OptAnalyze, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_506, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::AnalyzeKeyword, +static const TransformFramePlan FRAME_PLAN_530 = {FRAME_CHILDREN_514, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_515[] = {{PEGRuleId::AnalyzeKeyword, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_507, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_531 = {FRAME_CHILDREN_515, 1, 1, false, 0, {}}; static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, @@ -7782,20 +7933,34 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { &PEGTransformerFactory::FinalizeDetachStatementTrampoline, &FRAME_PLAN_184}, {"DropStatement", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDropStatementTrampoline, &FRAME_PLAN_185}, + {"DropMemberStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropMemberStatementTrampoline, &FRAME_PLAN_186}, + {"DropMember", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DropTableFunctionMember", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropTableFunctionMemberTrampoline, &FRAME_PLAN_187}, + {"DropFunctionMember", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropFunctionMemberTrampoline, &FRAME_PLAN_188}, {"DropEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DropTrigger", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_186}, + &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_189}, {"DropTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_187}, + &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_190}, {"DropTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_188}, + &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_191}, {"DropFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_189}, + &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_192}, + {"DropFunctionSignature", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropFunctionSignatureTrampoline, &FRAME_PLAN_193}, + {"DropSignatureType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DropSignatureAnyType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropSignatureAnyTypeTrampoline, &FRAME_PLAN_12}, {"DropSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_190}, + &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_194}, {"DropIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_191}, + &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_195}, {"QualifiedIndexName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QualifiedIndexNameString", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7803,15 +7968,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SchemaReservedIndex", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline, &FRAME_PLAN_56}, {"CatalogReservedSchemaIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_192}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_196}, {"DropSequence", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_193}, + &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_197}, {"DropCollation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_194}, + &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_198}, {"DropType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_195}, + &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_199}, {"DropSecret", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_196}, + &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_200}, {"TableOrView", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MaterializedViewEntry", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7833,21 +7998,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DropSecretStorage", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline, &FRAME_PLAN_12}, {"ExecuteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_197}, + &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_201}, {"ExplainStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_198}, + &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_202}, {"ExplainOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_199}, + &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_203}, {"ExplainOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_200}, + &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_204}, {"ExplainOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_201}, + &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_205}, {"ExplainSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_202}, + &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_206}, {"ExplainableStatements", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_203}, + &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_207}, {"ExportSource", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExportSourceTrampoline, &FRAME_PLAN_12}, {"ExportOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -7857,27 +8022,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ColumnReference", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeColumnReferenceTrampoline, &FRAME_PLAN_1}, {"NestedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_204}, + &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_208}, {"CatalogReservedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_205}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_209}, {"SchemaReservedTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_206}, + &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_210}, {"TableReservedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_207}, + &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_211}, {"FunctionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_208}, + &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_212}, {"FunctionExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_209}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_213}, {"FunctionExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_210}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_214}, {"FunctionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_211}, + &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_215}, {"FunctionIdentifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"CatalogReservedSchemaFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_212}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_216}, {"SchemaReservedFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline, &FRAME_PLAN_56}, {"DistinctOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -7887,11 +8052,11 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AllKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAllKeywordTrampoline, &FRAME_PLAN_12}, {"WithinGroupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_213}, + &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_217}, {"FilterClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_214}, + &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_218}, {"FilterClauseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_215}, + &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_219}, {"FilterClauseContents", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline, &FRAME_PLAN_21}, {"IgnoreOrRespectNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -7913,9 +8078,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FalseLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFalseLiteralTrampoline, &FRAME_PLAN_12}, {"CastExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_216}, + &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_220}, {"CastArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_217}, + &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_221}, {"CastOrTryCast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7925,45 +8090,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ColIdDot", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeColIdDotTrampoline, &FRAME_PLAN_83}, {"StarExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_218}, + &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_222}, {"StarQualifierList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_219}, + &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_223}, {"ExcludeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_220}, + &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_224}, {"ExcludeNames", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_221}, + &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_225}, {"ExcludeNameSingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_222}, + &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_226}, {"ExcludeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeDottedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_223}, + &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_227}, {"ExcludeColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline, &FRAME_PLAN_38}, {"ReplaceList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_224}, + &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_228}, {"ReplaceEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReplaceEntrySingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_225}, + &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_229}, {"ReplaceEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_226}, + &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_230}, {"ReplaceEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_227}, + &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_231}, {"RenameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_228}, + &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_232}, {"RenameEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RenameEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_229}, + &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_233}, {"SingleRenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_230}, + &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_234}, {"RenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_222}, + &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_226}, {"SubqueryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_231}, + &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_235}, {"SubqueryNot", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryNotTrampoline, &FRAME_PLAN_12}, {"SubqueryExists", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7971,29 +8136,29 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CaseExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_232}, + &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_236}, {"SearchedCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_233}, + &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_237}, {"SimpleCaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_234}, + &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_238}, {"SimpleCaseWhenOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleCaseWhenEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline, &FRAME_PLAN_31}, {"CaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_235}, + &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_239}, {"CaseElse", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCaseElseTrampoline, &FRAME_PLAN_21}, {"TypeLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTypeLiteralTrampoline, &FRAME_PLAN_162}, {"IntervalLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_236}, + &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_240}, {"IntervalParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IntervalStringParameter", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline, &FRAME_PLAN_12}, {"FrameClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_237}, + &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_241}, {"Framing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeFramingTrampoline, &FRAME_PLAN_19}, {"RowsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8005,15 +8170,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FrameExtent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SingleFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_238}, + &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_242}, {"BetweenFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_239}, + &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_243}, {"FrameBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FrameUnbounded", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_240}, + &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_244}, {"FrameExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_241}, + &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_245}, {"FrameCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline, &FRAME_PLAN_12}, {"PrecedingOrFollowing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8023,7 +8188,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FollowingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFollowingFrameTrampoline, &FRAME_PLAN_12}, {"WindowExcludeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_242}, + &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_246}, {"WindowExcludeElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8045,37 +8210,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WindowFrameDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"WindowFrameNameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_243}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_247}, {"WindowFrameNameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_244}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_248}, {"WindowFrameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_245}, + &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_249}, {"WindowFrameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_246}, + &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_250}, {"BaseWindowName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline, &FRAME_PLAN_12}, {"WindowPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_247}, + &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_251}, {"ListExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ArrayBoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_248}, + &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_252}, {"ArrayParensSelect", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline, &FRAME_PLAN_163}, {"BoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_249}, + &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_253}, {"StructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_250}, + &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_254}, {"StructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_251}, + &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_255}, {"MapExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_252}, + &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_256}, {"MapStructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_253}, + &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_257}, {"MapStructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_254}, + &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_258}, {"GroupingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_255}, + &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_259}, {"GroupingOrGroupingId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupingKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8097,61 +8262,61 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DefaultExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline, &FRAME_PLAN_12}, {"ListComprehensionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_256}, + &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_260}, {"ListComprehensionFilter", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline, &FRAME_PLAN_21}, {"ParensExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_257}, + &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_261}, {"MeasureSemanticsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_258}, + &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_262}, {"SingleExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"Expression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_259}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_263}, {"ColumnDefaultExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_260}, + &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_264}, {"LogicalOrExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_261}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_265}, {"LogicalOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_262}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_266}, {"ColDefOrExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_263}, + &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_267}, {"ColDefOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_264}, + &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_268}, {"LogicalAndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_265}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_269}, {"LogicalAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_266}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_270}, {"ColDefAndExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_267}, + &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_271}, {"ColDefAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_268}, + &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_272}, {"LogicalNotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_269}, + &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_273}, {"NotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_270}, + &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_274}, {"NotKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_12}, {"IsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_271}, + &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_275}, {"IsExpressionContinuation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_272}, + &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_276}, {"IsExpressionTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsTestTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_273}, + &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_277}, {"IsDistinctTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_274}, + &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_278}, {"IsComparisonTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_275}, + &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_279}, {"IsOtherOperatorTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_276}, + &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_280}, {"IsCastTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_277}, + &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_281}, {"IsTest", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_278}, + &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_282}, {"IsLiteralValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UnknownLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8163,23 +8328,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsNull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullTrampoline, - &FRAME_PLAN_279}, + &FRAME_PLAN_283}, {"IsNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsDistinctFromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_280}, + &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_284}, {"IsDistinctFromTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_281}, + &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_285}, {"IsDistinctFromOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_12}, {"ComparisonExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_282}, + &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_286}, {"ComparisonExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_283}, + &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_287}, {"ComparisonOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NotComparisonOperand", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_284}, + &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_288}, {"ComparisonOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OperatorEqual", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8195,17 +8360,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OperatorGreaterThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_12}, {"BetweenInLikeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_285}, + &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_289}, {"InPredicate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_286}, + &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_290}, {"BetweenLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_287}, + &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_291}, {"BetweenLikeOpExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LikeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_288}, + &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_292}, {"EscapeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_289}, + &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_293}, {"LikeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, &FRAME_PLAN_19}, {"LikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8229,43 +8394,43 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotSimilarToOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_12}, {"InClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_290}, + &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_294}, {"InExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InContainsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_291}, + &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_295}, {"InExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_296}, {"InSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_297}, {"BetweenClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_298}, {"OtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_299}, {"InfixOtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_300}, {"OtherOperatorTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllSubqueryTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_301}, {"OtherOperatorExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_302}, {"SingleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_299}, + &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_303}, {"SingleArrowBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ArrowChainBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_300}, + &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_304}, {"ArrowChainTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DoubleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_301}, + &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_305}, {"ArrowFullBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_259}, + &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_263}, {"OtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllParsedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_302}, + &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_306}, {"NamedOtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, &FRAME_PLAN_54}, {"OperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8273,7 +8438,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AnyOperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_12}, {"AnyAllOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_303}, + &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_307}, {"AnyOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubqueryAny", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8281,49 +8446,49 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SubqueryAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_12}, {"QualifiedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_304}, + &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_308}, {"QualifiedOperatorContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_305}, + &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_309}, {"BitwiseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_306}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_310}, {"BitwiseExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_307}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_311}, {"BitOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_12}, {"TildeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_308}, + &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_312}, {"AdditiveExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_309}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_313}, {"AdditiveExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_310}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_314}, {"Term", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTermTrampoline, &FRAME_PLAN_12}, {"MultiplicativeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_311}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_315}, {"MultiplicativeExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_312}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_316}, {"Factor", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFactorTrampoline, &FRAME_PLAN_12}, {"ExponentiationExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_313}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_317}, {"ExponentiationExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_314}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_318}, {"ExponentOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_12}, {"CollateExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_315}, + &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_319}, {"CollateExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_316}, + &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_320}, {"AtTimeZoneExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_317}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_321}, {"AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_318}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_322}, {"UnaryExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_319}, + &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_323}, {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_19}, {"MinusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8333,9 +8498,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TildePrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_12}, {"BaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_320}, + &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_324}, {"IndirectionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_321}, + &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_325}, {"Indirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8343,27 +8508,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DotOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DotMethodOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_322}, + &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_326}, {"DotColumnOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_147}, {"MethodExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_323}, + &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_327}, {"MethodExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_324}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_328}, {"MethodExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_325}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_329}, {"MethodFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_211}, + &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_215}, {"SliceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_326}, + &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_330}, {"SliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_327}, + &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_331}, {"SliceUpperBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MinusStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_328}, + &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_332}, {"EndStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_329}, + &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_333}, {"EndSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_66}, {"StepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8373,47 +8538,47 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SpecialFunctionExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CoalesceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_330}, + &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_334}, {"UnpackExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_134}, {"TryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_134}, {"ColumnsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_331}, + &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_335}, {"ExtractExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_332}, + &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_336}, {"ExtractArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_333}, + &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_337}, {"LambdaExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_334}, + &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_338}, {"NullIfExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_335}, + &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_339}, {"NullIfArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_254}, + &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_258}, {"PositionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_336}, + &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_340}, {"PositionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_337}, + &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_341}, {"RowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_338}, + &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_342}, {"SubstringExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_343}, {"SubstringArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_344}, {"SubstringParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_341}, + &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_345}, {"SubstringFromFor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringFromOptionalFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_342}, + &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_346}, {"SubstringFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_347}, {"TrimExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_348}, {"TrimArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_349}, {"TrimDirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, &FRAME_PLAN_19}, {"TrimBoth", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8423,23 +8588,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TrimTrailing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_12}, {"TrimSource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_346}, + &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_350}, {"OverlayExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_347}, + &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_351}, {"OverlayArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OverlayParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_348}, + &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_352}, {"FromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_21}, {"ForExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_21}, {"OverlayExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_344}, {"ExtractArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExtractDatePartArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_349}, + &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_353}, {"ExtractIdentifierArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_12}, {"ExtractStringArgument", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8449,25 +8614,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ExternalResourceStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_350}, + &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_354}, {"RegisterExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_351}, + &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_355}, {"DestroyExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_352}, + &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_356}, {"ExternalResourceCreationOptions", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_33}, {"AttachToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_353}, + &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_357}, {"ConnectToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_354}, + &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_358}, {"ExternalResourceSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExternalResourceCreateClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_355}, + &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_359}, {"ExternalResourceReferenceClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_32}, {"InsertStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_356}, + &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_360}, {"OrAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertOrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8477,15 +8642,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ByNameOrPosition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertByNameOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_357}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_361}, {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_358}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_362}, {"InsertByName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_12}, {"InsertByPosition", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_12}, {"InsertTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_359}, + &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_363}, {"InsertAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_12}, {"ColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8495,31 +8660,31 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"InsertValues", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectInsertValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_202}, + &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_206}, {"DefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_12}, {"OnConflictClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_360}, + &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_364}, {"OnConflictTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictExpressionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_361}, + &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_365}, {"OnConflictIndexTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_362}, + &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_366}, {"OnConflictAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_363}, + &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_367}, {"OnConflictNothing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_12}, {"ReturningClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_364}, + &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_368}, {"LoadStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_365}, + &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_369}, {"ExtensionAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_12}, {"InstallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_366}, + &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_370}, {"InstallAndLoad", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_12}, {"UpdateExtensionsStatement", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8527,49 +8692,57 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FromSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FromSourceIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_371}, {"FromSourceString", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_12}, + {"FromSourceName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_372}, {"VersionNumber", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_367}, + &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_373}, {"ExtensionRepositoryStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_368}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_374}, {"RepositoryPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_12}, {"RepositoryPublicKey", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_12}, + {"CreateExtensionRepositoryFromHostStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, &FRAME_PLAN_375}, {"DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_369}, + &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_376}, + {"ExtensionRepositoryName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline, &FRAME_PLAN_149}, + {"ExtensionRepositoryHostName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtensionRepositoryHostNameTrampoline, &FRAME_PLAN_377}, {"TableMatchRecognizeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_370}, + &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_378}, {"MatchRecognizeBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_371}, + &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_379}, {"MatchRecognizeClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MRPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_372}, + &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_380}, {"MROrderBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_373}, + &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_381}, {"MRMeasures", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_374}, + &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_382}, {"MRRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRRowsTrampoline, - &FRAME_PLAN_375}, + &FRAME_PLAN_383}, {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, - &FRAME_PLAN_376}, + &FRAME_PLAN_384}, {"MRPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_377}, + &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_385}, {"MRSubset", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_378}, + &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_386}, {"MRDefineAuto", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_12}, {"MRDefine", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_379}, + &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_387}, {"MeasuresClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_380}, + &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_388}, {"MeasuresElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_381}, + &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_389}, {"MeasureSemantics", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RunningSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8581,7 +8754,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OneRowPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_12}, {"AllRowsPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_382}, + &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_390}, {"AllRowsEmptyMatches", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ShowEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8591,7 +8764,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WithUnmatchedRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_12}, {"AfterMatchSkip", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_383}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_391}, {"AfterMatchSkipTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SkipToNextRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8599,25 +8772,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SkipPastLastRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_12}, {"SkipToFirstVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_384}, + &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_392}, {"SkipToLastVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_384}, + &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_392}, {"SkipToVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_385}, + &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_393}, {"PatternClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_386}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_394}, {"RowPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_387}, + &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_395}, {"RowPatternAlternative", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_388}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_396}, {"RowPatternTerm", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_389}, + &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_397}, {"RowPatternFactor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_390}, + &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_398}, {"RowPatternPrimary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RowPatternPermute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_391}, + &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_399}, {"RowPatternAnchor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PatternStart", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8625,15 +8798,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PatternEnd", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_12}, {"RowPatternGroup", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_392}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_400}, {"RowPatternEmpty", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_12}, {"RowPatternExclusion", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_393}, + &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_401}, {"RowPatternLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_394}, + &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_402}, {"RowPatternQuantifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_395}, + &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_403}, {"RowPatternQuantifierKind", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierReluctant", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8645,7 +8818,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierOptional", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_12}, {"QuantifierRange", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_396}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_404}, {"QuantifierBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8657,55 +8830,55 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierExact", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_12}, {"SubsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_397}, + &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_405}, {"SubsetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_398}, + &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_406}, {"DefineClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_399}, + &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_407}, {"DefineElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_400}, + &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_408}, {"MergeIntoStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_401}, + &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_409}, {"MergeIntoUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_402}, + &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_410}, {"MergeMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_403}, + &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_411}, {"MatchedClauseAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_404}, + &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_412}, {"UpdateMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchSetAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_405}, + &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_413}, {"UpdateByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_406}, + &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_414}, {"DeleteMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_12}, {"InsertMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_407}, + &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_415}, {"InsertMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertDefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_12}, {"InsertByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_408}, + &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_416}, {"InsertValuesList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_409}, + &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_417}, {"DoNothingMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_12}, {"ErrorMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_66}, {"UpdateMatchSetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_410}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_418}, {"UpdateMatchSetInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_80}, {"AndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_21}, {"NotMatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_411}, + &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_419}, {"BySourceOrTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BySource", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8715,27 +8888,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PivotStatement", &PEGTransformerFactory::InitializePivotStatementTrampoline, &PEGTransformerFactory::FinalizePivotStatementTrampoline, nullptr}, {"PivotOn", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotOnTrampoline, - &FRAME_PLAN_412}, + &FRAME_PLAN_420}, {"PivotUsing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_364}, + &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_368}, {"PivotColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_413}, + &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_421}, {"PivotColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotColumnExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_31}, {"PivotColumnSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_414}, + &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_422}, {"UnpivotStatement", &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline, nullptr}, {"IntoNameValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_423}, {"OptionalParensNameList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ParenthesizedNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_424}, {"BareNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_417}, + &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_425}, {"IncludeOrExcludeNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IncludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8747,41 +8920,41 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"UnpivotHeaderSingle", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_38}, {"UnpivotHeaderList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_424}, {"PragmaStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_418}, + &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_426}, {"PragmaAssignOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PragmaAssign", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_419}, + &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_427}, {"PragmaFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_420}, + &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_428}, {"PragmaParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_296}, {"PrepareStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_421}, + &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_429}, {"TypeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_422}, + &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_430}, {"SelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_202}, + &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_206}, {"SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline, nullptr}, {"SelectSetOpChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_431}, {"SelectSetOpChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_432}, {"IntersectChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_433}, {"IntersectChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_426}, + &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_434}, {"SetIntersectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_427}, + &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_435}, {"SelectAtom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_297}, {"SetopClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_428}, + &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_436}, {"SetopType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetopUnion", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8791,103 +8964,107 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SelectStatementType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResultModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_429}, + &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_437}, {"LimitOffset", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LimitOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_430}, + &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_438}, {"OffsetLimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_431}, + &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_439}, {"OffsetFetchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_432}, + &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_440}, {"FetchOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_433}, + &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_441}, {"FetchOnlyClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_434}, + &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_442}, {"TableStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_435}, + &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_443}, {"OptionalParensSimpleSelect", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleSelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_436}, + &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_444}, {"SimpleSelect", &PEGTransformerFactory::InitializeSimpleSelectTrampoline, &PEGTransformerFactory::FinalizeSimpleSelectTrampoline, nullptr}, {"SelectFrom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectFromClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_437}, + &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_445}, {"FromSelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_438}, + &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_446}, {"WithStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_439}, + &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_447}, {"CTEBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CTESelectBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_297}, {"CTEDMLBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_440}, + &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_448}, {"UsingKey", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_441}, + &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_449}, {"Materialized", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_12}, {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, &PEGTransformerFactory::FinalizeWithClauseTrampoline, nullptr}, {"SelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_442}, + &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_450}, {"TargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_443}, + &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_451}, {"ColumnAliases", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_424}, {"DistinctClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DistinctAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_12}, {"DistinctOn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_444}, + &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_452}, {"DistinctOnTargets", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_330}, + &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_334}, {"InnerTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, &PEGTransformerFactory::FinalizeTableRefTrampoline, nullptr}, {"TableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_445}, + &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_453}, {"BaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_446}, + &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_454}, {"TableAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_38}, {"ValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_447}, + &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_455}, {"ParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_448}, + &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_456}, + {"JoinedTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"JoinedTableRefChain", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_457}, {"JoinOrPivot", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TablePivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_449}, + &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_458}, {"TablePivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_450}, + &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_459}, {"PivotGroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_451}, + &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_460}, {"TableUnpivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_452}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_461}, {"TableUnpivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_453}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_462}, {"PivotHeader", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_454}, + &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_463}, {"PivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_455}, + &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_464}, {"PivotValueTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotEnumTarget", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_12}, {"PivotListTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_456}, + &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_465}, {"UnpivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_457}, + &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_466}, {"PivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_458}, + &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_467}, {"UnpivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_458}, + &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_467}, {"Lateral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeLateralTrampoline, &FRAME_PLAN_12}, {"BaseTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8903,37 +9080,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableFunctionLateralOpt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_459}, + &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_468}, {"TableFunctionAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_460}, + &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_469}, {"WithOrdinality", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_12}, {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CatalogReservedSchemaTableFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_461}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_470}, {"TableFunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"TableFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_462}, + &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_471}, {"FunctionArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NamedFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_463}, + &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_472}, {"PositionalFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_31}, {"NamedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_464}, + &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_473}, {"TableAlias", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableAliasAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_465}, + &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_474}, {"TableAliasWithoutAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_466}, + &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_475}, {"AtClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_467}, + &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_476}, {"AtSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_468}, + &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_477}, {"AtUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_19}, {"VersionAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8945,21 +9122,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestJoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestJoinAliased", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_469}, + &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_478}, {"NearestJoinBare", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_470}, + &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_479}, {"NearestBareTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_471}, + &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_480}, {"NearestTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_472}, + &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_481}, {"NearestTableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_473}, + &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_482}, {"NearestBaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_474}, + &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_483}, {"NearestParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_475}, + &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_484}, {"ApproxOrExact", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestApprox", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8973,19 +9150,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestSimilarity", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_12}, {"RegularJoinClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_476}, + &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_485}, {"JoinByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_477}, + &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_486}, {"Asof", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAsofTrampoline, &FRAME_PLAN_12}, {"JoinWithoutOnClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_478}, + &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_487}, {"JoinQualifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_21}, {"UsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_479}, + &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_488}, {"UsingColumnName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, &FRAME_PLAN_149}, {"JoinType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8995,7 +9172,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CrossJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_12}, {"NaturalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_480}, + &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_489}, {"PositionalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_12}, {"FullJoin", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9015,35 +9192,35 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WhereClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_21}, {"GroupByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_481}, + &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_490}, {"HavingClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_21}, {"QualifyClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_21}, {"SampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_482}, + &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_491}, {"SelectSampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_482}, + &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_491}, {"WindowClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_483}, + &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_492}, {"WindowDefinition", &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline, nullptr}, {"SampleEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleEntryCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_484}, + &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_493}, {"SampleEntryFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_485}, + &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_494}, {"SampleFunction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_83}, {"SampleProperties", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_486}, + &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_495}, {"RepeatableSample", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_487}, + &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_496}, {"SampleSeed", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_12}, {"SampleCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_488}, + &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_497}, {"SampleValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9057,7 +9234,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GroupByAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_12}, {"GroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_489}, + &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_498}, {"GroupByExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupByBaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9065,7 +9242,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"EmptyGroupingItem", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_12}, {"CubeOrRollupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_490}, + &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_499}, {"CubeOrRollup", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, &FRAME_PLAN_19}, {"CubeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9073,9 +9250,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"RollupKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_12}, {"GroupingSetsClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_491}, + &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_500}, {"SubqueryReference", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_297}, {"OrderByExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_98}, {"DescOrAsc", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9091,17 +9268,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NullsLast", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_12}, {"OrderByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_492}, + &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_501}, {"OrderByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OrderByExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_493}, + &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_502}, {"OrderByAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_494}, + &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_503}, {"LimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_495}, + &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_504}, {"OffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_496}, + &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_505}, {"OffsetValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_31}, {"LimitValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9117,45 +9294,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FetchClauseWithoutValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_12}, {"FetchClauseWithValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_497}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_506}, {"FetchValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_31}, {"AliasedExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ColIdExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_498}, + &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_507}, {"ExpressionAsCollabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_381}, + &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_389}, {"ExpressionOptIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_31}, {"ValuesClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_499}, + &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_508}, {"ValuesExpressions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_296}, {"SetStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetKeywordStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_500}, + &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_509}, {"VariableAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_501}, + &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_510}, {"SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_511}, {"ResetTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_512}, {"ResetVariableOrSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_504}, + &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_513}, {"SetSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_512}, {"StandardAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_505}, + &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_514}, {"SetVariableOrSetting", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_506}, + &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_515}, {"ZoneValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ZoneLocal", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9167,13 +9344,13 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ZoneIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_12}, {"ZoneIntervalWithInterval", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_507}, + &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_516}, {"ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_12}, {"SetSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_512}, {"SetVariable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_508}, + &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_517}, {"VariableScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_12}, {"SettingScope", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9185,19 +9362,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GlobalScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_12}, {"SetAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_509}, + &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_518}, {"VariableList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_344}, {"TransactionStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BeginTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_510}, + &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_519}, {"RollbackTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_12}, {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_12}, {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_520}, {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReadOnly", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9205,27 +9382,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ReadWrite", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_12}, {"UpdateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_521}, {"UpdateTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BaseTableSet", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_182}, {"BaseTableAliasSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_522}, {"UpdateAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_32}, {"UpdateSetClauseList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_514}, + &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_523}, {"UpdateSetClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateSetTuple", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_17}, {"UpdateSetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_515}, + &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_524}, {"UpdateSetColumnTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_516}, + &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_525}, {"UseStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_517}, + &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_526}, {"UseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SchemaNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9233,21 +9410,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CatalogNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, &FRAME_PLAN_54}, {"UseTargetCatalogSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_518}, + &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_527}, {"DotIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_12}, {"VacuumStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_519}, + &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_528}, {"VacuumOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"VacuumParensOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_520}, + &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_529}, {"VacuumLegacyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_521}, + &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_530}, {"VacuumOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, &FRAME_PLAN_19}, {"OptAnalyze", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_522}, + &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_531}, {"OptFull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptFullTrampoline, &FRAME_PLAN_12}, {"OptFreeze", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9255,7 +9432,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OptVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_12}, {"NameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_424}, }; static case_insensitive_map_t BuildGeneratedTransformFrameOps() { @@ -13054,6 +13231,48 @@ PEGTransformerFactory::FinalizeDropStatementTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeDropMemberStatementTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto drop_member = process.TakeResult>(0); + optional drop_behavior {}; + if (process.child_results[1]) { + drop_behavior = process.TakeResult(1); + } + auto result = TransformDropMemberStatement(transformer, std::move(drop_member), drop_behavior); + return transformer.MakeResult>(std::move(result)); +} + +arena_ptr +PEGTransformerFactory::FinalizeDropTableFunctionMemberTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto comment_macro_table = process.TakeResult(0); + optional if_exists {}; + if (process.child_results[1]) { + if_exists = process.TakeResult(1); + } + auto qualified_table_function = process.TakeResult(2); + auto drop_function_signature = process.TakeResult>(3); + auto result = TransformDropTableFunctionMember(transformer, comment_macro_table, if_exists, + qualified_table_function, drop_function_signature); + return transformer.MakeResult>(std::move(result)); +} + +arena_ptr +PEGTransformerFactory::FinalizeDropFunctionMemberTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto function_type_macro = process.TakeResult(0); + optional if_exists {}; + if (process.child_results[1]) { + if_exists = process.TakeResult(1); + } + auto function_identifier = process.TakeResult(2); + auto drop_function_signature = process.TakeResult>(3); + auto result = TransformDropFunctionMember(transformer, function_type_macro, if_exists, function_identifier, + drop_function_signature); + return transformer.MakeResult>(std::move(result)); +} + arena_ptr PEGTransformerFactory::FinalizeDropTriggerTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional if_exists {}; @@ -13121,6 +13340,36 @@ PEGTransformerFactory::FinalizeDropFunctionTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeDropFunctionSignatureTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + idx_t dynamic_child_count = 0; + auto &dynamic_list_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); + if (dynamic_list_opt.HasResult()) { + dynamic_child_count = CountParseResultsFromList(dynamic_list_opt.GetResult()); + } + optional> drop_signature_type {}; + auto &drop_signature_type_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); + if (drop_signature_type_opt.HasResult()) { + vector drop_signature_type_value; + drop_signature_type_value.reserve(dynamic_child_count); + for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { + drop_signature_type_value.push_back(process.TakeResult(i)); + } + drop_signature_type = std::move(drop_signature_type_value); + } + auto result = TransformDropFunctionSignature(transformer, drop_signature_type); + return transformer.MakeResult>(result); +} + +arena_ptr +PEGTransformerFactory::FinalizeDropSignatureAnyTypeTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto result = TransformDropSignatureAnyType(transformer); + return transformer.MakeResult(result); +} + arena_ptr PEGTransformerFactory::FinalizeDropSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -16570,9 +16819,8 @@ PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline(PEGTransforme arena_ptr PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto identifier = list_pr.GetChild(1).Cast().identifier; - auto result = TransformFromSourceIdentifier(transformer, identifier); + auto from_source_name = process.TakeResult(0); + auto result = TransformFromSourceIdentifier(transformer, from_source_name); return transformer.MakeResult(result); } @@ -16585,6 +16833,28 @@ PEGTransformerFactory::FinalizeFromSourceStringTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } +arena_ptr +PEGTransformerFactory::FinalizeFromSourceNameTrampoline(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::FinalizeVersionNumberTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16604,14 +16874,14 @@ PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline(PEGTransf if (process.child_results[1]) { if_not_exists = process.TakeResult(1); } - auto col_id_or_string = process.TakeResult(2); + auto extension_repository_name = process.TakeResult(2); auto repository_prefix = process.TakeResult(3); optional> repository_public_key {}; if (process.child_results[4]) { repository_public_key = process.TakeResult>(4); } - auto result = TransformCreateExtensionRepositoryStmt(transformer, or_replace, if_not_exists, col_id_or_string, - repository_prefix, repository_public_key); + auto result = TransformCreateExtensionRepositoryStmt( + transformer, or_replace, if_not_exists, extension_repository_name, repository_prefix, repository_public_key); return transformer.MakeResult>(std::move(result)); } @@ -16645,6 +16915,23 @@ PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline(PEGTransformer &tra return transformer.MakeResult>(result); } +arena_ptr +PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + optional or_replace {}; + if (process.child_results[0]) { + or_replace = process.TakeResult(0); + } + optional if_not_exists {}; + if (process.child_results[1]) { + if_not_exists = process.TakeResult(1); + } + auto extension_repository_name = process.TakeResult(2); + auto result = TransformCreateExtensionRepositoryFromHostStmt(transformer, or_replace, if_not_exists, + extension_repository_name); + return transformer.MakeResult>(std::move(result)); +} + arena_ptr PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16652,11 +16939,50 @@ PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline(PEGTransfor if (process.child_results[0]) { if_exists = process.TakeResult(0); } - auto col_id_or_string = process.TakeResult(1); - auto result = TransformDropExtensionRepositoryStmt(transformer, if_exists, col_id_or_string); + auto extension_repository_name = process.TakeResult(1); + auto result = TransformDropExtensionRepositoryStmt(transformer, if_exists, extension_repository_name); return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline(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::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) { @@ -17911,7 +18237,7 @@ PEGTransformerFactory::FinalizeParensTableRefTrampoline(PEGTransformer &transfor if (process.child_results[0]) { table_alias_colon = process.TakeResult(0); } - auto table_ref = process.TakeResult>(1); + auto joined_table_ref = process.TakeResult>(1); optional table_alias {}; if (process.child_results[2]) { table_alias = process.TakeResult(2); @@ -17920,11 +18246,28 @@ PEGTransformerFactory::FinalizeParensTableRefTrampoline(PEGTransformer &transfor if (process.child_results[3]) { sample_clause = process.TakeResult>(3); } - auto result = TransformParensTableRef(transformer, table_alias_colon, std::move(table_ref), table_alias, + auto result = TransformParensTableRef(transformer, table_alias_colon, std::move(joined_table_ref), table_alias, std::move(sample_clause)); return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline(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 inner_table_ref = process.TakeResult>(0); + vector> join_or_pivot; + join_or_pivot.reserve(dynamic_child_count); + for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { + join_or_pivot.push_back(process.TakeResult>(i)); + } + auto result = TransformJoinedTableRefChain(transformer, std::move(inner_table_ref), std::move(join_or_pivot)); + return transformer.MakeResult>(std::move(result)); +} + arena_ptr PEGTransformerFactory::FinalizeTablePivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18430,12 +18773,12 @@ PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline(PEGTransformer &tra arena_ptr PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto table_ref = process.TakeResult>(0); + auto joined_table_ref = process.TakeResult>(0); optional> sample_clause {}; if (process.child_results[1]) { sample_clause = process.TakeResult>(1); } - auto result = TransformNearestParensTableRef(transformer, std::move(table_ref), std::move(sample_clause)); + auto result = TransformNearestParensTableRef(transformer, std::move(joined_table_ref), std::move(sample_clause)); return transformer.MakeResult>(std::move(result)); } diff --git a/src/duckdb/src/parser/peg/transformer/transform_load.cpp b/src/duckdb/src/parser/peg/transformer/transform_load.cpp index 1cc8f063a..6698aa27e 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_load.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_load.cpp @@ -115,8 +115,34 @@ unique_ptr PEGTransformerFactory::TransformCreateExtensionReposito return std::move(result); } +// 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, + const Identifier &extension_repository_name) { + return TransformCreateExtensionRepositoryStmt(transformer, or_replace, if_not_exists, extension_repository_name, + string(), optional>()); +} + string PEGTransformerFactory::TransformRepositoryPrefix(PEGTransformer &transformer, const bool &has_result, const string &string_literal) { + // an empty prefix is not "no prefix": the form without one resolves the repository from its host, and must not be + // reachable with keys of the caller's choosing attached + if (string_literal.empty()) { + throw ParserException( + "CREATE EXTENSION REPOSITORY: the prefix cannot be empty. Leave WITH PREFIX out to resolve " + "the repository from its host"); + } return string_literal; } diff --git a/src/duckdb/src/parser/peg/transformer/transform_pragma.cpp b/src/duckdb/src/parser/peg/transformer/transform_pragma.cpp index 3aeb2e5b6..bb67c464d 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_pragma.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_pragma.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/parser/statement/pragma_statement.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" diff --git a/src/duckdb/src/parser/peg/transformer/transform_select.cpp b/src/duckdb/src/parser/peg/transformer/transform_select.cpp index 2148d0865..b12cea5fc 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_select.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_select.cpp @@ -130,11 +130,15 @@ unique_ptr PEGTransformerFactory::TransformSelectSetOpChain( if (!select_set_op_chain_tail) { return select; } + // the chain only extends the N-ary nodes it builds itself: an operand that already is a set operation was written + // in parentheses and resolves its own result type before the outer operation unifies over it + bool chain_node = false; for (auto &tail : *select_set_op_chain_tail) { auto setop_result = std::move(tail.first); auto right_select = std::move(tail.second); - if (select->node->type == QueryNodeType::SET_OPERATION_NODE && select->node->modifiers.empty() && - select->node->cte_map.map.empty()) { + if (chain_node) { + // modifiers and CTEs are attached by SelectStatementInternal, after the chain has been built + D_ASSERT(select->node->modifiers.empty() && select->node->cte_map.map.empty()); auto &existing = select->node->Cast(); if (existing.setop_type == setop_result->setop_type && existing.setop_all == setop_result->setop_all && (existing.setop_type == SetOperationType::UNION || @@ -146,6 +150,7 @@ unique_ptr PEGTransformerFactory::TransformSelectSetOpChain( setop_result->children.push_back(std::move(select->node)); setop_result->children.push_back(std::move(right_select->node)); select->node = std::move(setop_result); + chain_node = true; } return select; } @@ -382,6 +387,20 @@ QualifiedName PEGTransformerFactory::TransformSchemaReservedIdentifierOrStringLi return result; } +static unique_ptr ApplyJoinOrPivot(unique_ptr source, unique_ptr join_or_pivot) { + if (join_or_pivot->type == TableReferenceType::JOIN) { + join_or_pivot->Cast().left = std::move(source); + } else if (join_or_pivot->type == TableReferenceType::PIVOT) { + join_or_pivot->Cast().source = std::move(source); + } else if (join_or_pivot->type == TableReferenceType::MATCH_RECOGNIZE) { + join_or_pivot->Cast().input = std::move(source); + } else { + throw NotImplementedException("Unsupported TableRef type encountered: %s", + EnumUtil::ToString(join_or_pivot->type)); + } + return join_or_pivot; +} + void PEGTransformerFactory::InitializeTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -412,27 +431,20 @@ arena_ptr PEGTransformerFactory::FinalizeTableRefTrampolin auto &repeat_join_or_pivot = join_or_pivot_opt.GetResult().Cast(); auto repeat_children = repeat_join_or_pivot.GetChildren(); for (idx_t i = 0; i < repeat_children.size(); i++) { - auto transform_join_or_pivot = process.TakeResult>(1 + i); - if (transform_join_or_pivot->type == TableReferenceType::JOIN) { - auto &join_ref = transform_join_or_pivot->Cast(); - join_ref.left = std::move(inner_table_ref); - inner_table_ref = std::move(transform_join_or_pivot); - } else if (transform_join_or_pivot->type == TableReferenceType::PIVOT) { - auto &pivot_ref = transform_join_or_pivot->Cast(); - pivot_ref.source = std::move(inner_table_ref); - inner_table_ref = std::move(transform_join_or_pivot); - } else if (transform_join_or_pivot->type == TableReferenceType::MATCH_RECOGNIZE) { - auto &match_recognize_ref = transform_join_or_pivot->Cast(); - match_recognize_ref.input = std::move(inner_table_ref); - inner_table_ref = std::move(transform_join_or_pivot); - } else { - throw NotImplementedException("Unsupported TableRef type encountered: %s", - EnumUtil::ToString(transform_join_or_pivot->type)); - } + inner_table_ref = ApplyJoinOrPivot(std::move(inner_table_ref), process.TakeResult>(1 + i)); } return transformer.MakeResult>(std::move(inner_table_ref)); } +unique_ptr PEGTransformerFactory::TransformJoinedTableRefChain(PEGTransformer &transformer, + unique_ptr inner_table_ref, + vector> join_or_pivot) { + for (auto &entry : join_or_pivot) { + inner_table_ref = ApplyJoinOrPivot(std::move(inner_table_ref), std::move(entry)); + } + return inner_table_ref; +} + unique_ptr PEGTransformerFactory::TransformTableUnpivotClauseBody(PEGTransformer &transformer, const vector &unpivot_header, vector unpivot_value_list) { diff --git a/src/duckdb/src/parser/token_iterator.cpp b/src/duckdb/src/parser/token_iterator.cpp index 027226fed..1130d9e89 100644 --- a/src/duckdb/src/parser/token_iterator.cpp +++ b/src/duckdb/src/parser/token_iterator.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/parser/parser_extension.hpp" +#include "duckdb/parser/peg/tokenizer/tokenizer.hpp" namespace duckdb { @@ -15,6 +16,11 @@ TokenIterator::TokenIterator(unique_ptr> owned_tokens_p) } } +TokenIterator::TokenIterator(TokenizerBehavior &behavior) + : TokenIterator(make_uniq>(std::move(behavior.tokens))) { + source = &behavior.sql; +} + TokenIterator::TokenIterator(vector &tokens_p) : tokens(tokens_p) { // A new root can receive tokens edited since an earlier match. for (auto &token : tokens) { @@ -23,7 +29,8 @@ TokenIterator::TokenIterator(vector &tokens_p) : tokens(tokens_p) } TokenIterator::TokenIterator(TokenIterator &&other) noexcept - : owned_tokens(std::move(other.owned_tokens)), tokens(other.tokens), position(other.position) { + : owned_tokens(std::move(other.owned_tokens)), tokens(other.tokens), source(other.source), + position(other.position) { } bool TokenIterator::HasMoreStatements() const { @@ -47,6 +54,14 @@ idx_t TokenIterator::EndOffset() const { return last_token.offset + last_token.length; } +idx_t TokenIterator::ConsumedEndOffset() const { + if (position == 0) { + return 0; + } + auto &last_token = Previous(); + return last_token.offset + last_token.length; +} + const MatcherToken &TokenIterator::Previous() const { if (position == 0) { throw InternalException("TokenIterator has no previous token"); diff --git a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp index 3f0ff3b0f..f0b54378d 100644 --- a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp @@ -108,9 +108,10 @@ static void NegatePercentileFractions(ClientContext &context, unique_ptr(Value::LIST(values)); + bound = make_uniq(Value::LIST(values), bound->GetAlias(), bound->GetQueryLocation()); } else { - bound = make_uniq(NegatePercentileValue(value, desc)); + bound = make_uniq(NegatePercentileValue(value, desc), bound->GetAlias(), + bound->GetQueryLocation()); } } @@ -185,7 +186,8 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu vector> bound_arguments; for (idx_t i = 0; i < aggr.GetArguments().size(); ++i) { auto &child = aggr.GetArgumentsMutable()[i]; - bound_arguments.push_back(BindChild(child.GetExpressionMutable(), 0, error)); + // arguments are aliased by their name, if any (see BindFunction for the rationale) + bound_arguments.push_back(BindChild(child.GetExpressionMutable(), 0, error, child.GetName())); // We have to negate the fractions for PERCENTILE_XXXX DESC if (!error.HasError() && ordered_set_agg && i == aggr.GetArguments().size() - 1) { NegatePercentileFractions(context, bound_arguments.back(), negate_fractions); @@ -249,11 +251,6 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu for (idx_t arg_idx = 0; arg_idx < aggr.GetArgumentsMutable().size(); arg_idx++) { auto &arg = aggr.GetArgumentsMutable()[arg_idx]; auto bound_arg = std::move(bound_arguments[arg_idx]); - // legacy function calls cannot have named arguments, so we ignore the names of the arguments during binding - // and pass them all positionally, aliasing them by their name (see BindFunction for the rationale) - if (!arg.GetName().empty()) { - bound_arg->SetAlias(arg.GetName()); - } if (aggr.IsLegacyFunctionCall()) { arguments.emplace_back(string(), std::move(bound_arg)); } else { diff --git a/src/duckdb/src/planner/binder/expression/bind_conjunction_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_conjunction_expression.cpp index cf2d7ba60..e73db61db 100644 --- a/src/duckdb/src/planner/binder/expression/bind_conjunction_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_conjunction_expression.cpp @@ -9,7 +9,7 @@ BindResult ExpressionBinder::BindExpression(ConjunctionExpression &expr, idx_t d // first try to bind the children of the case expression ErrorData error; vector> children; - for (idx_t i = 0; i < expr.GetChildrenMutable().size(); i++) { + for (idx_t i = 0; i < expr.GetChildren().size(); i++) { children.push_back(BindChild(expr.GetChildrenMutable()[i], depth, error)); } if (error.HasError()) { diff --git a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp index 7cbade868..ba0354dea 100644 --- a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp @@ -383,13 +383,30 @@ BindResult ExpressionBinder::BindAggregateInEnclosingScope(FunctionExpression &a } BindResult ExpressionBinder::BindFunction(FunctionExpression &function, ScalarFunctionCatalogEntry &func, idx_t depth) { + // a bound subquery cannot be copied, so keep the parsed arguments to bind them again for the named fallback + vector named_fallback; + if (function.IsLegacyFunctionCall()) { + for (auto &arg : function.GetArguments()) { + if (!arg.GetName().empty()) { + for (auto &fallback_arg : function.GetArguments()) { + named_fallback.push_back(fallback_arg.Copy()); + } + break; + } + } + } + // bind the children of the function expression ErrorData error; // bind each child vector> bound_children; for (idx_t i = 0; i < function.GetArguments().size(); i++) { - bound_children.push_back(BindChild(function.GetArgumentsMutable()[i].GetExpressionMutable(), depth, error)); + // legacy function calls cannot have named arguments, so we ignore the names of the arguments during binding + // and pass them all positionally. We do alias them by their name though, so that alias-capturing functions + // (e.g. struct_pack) still work and so that re-serializing to the old format can match arguments by name. + auto &arg = function.GetArgumentsMutable()[i]; + bound_children.push_back(BindChild(arg.GetExpressionMutable(), depth, error, arg.GetName())); } if (error.HasError()) { @@ -404,29 +421,11 @@ BindResult ExpressionBinder::BindFunction(FunctionExpression &function, ScalarFu // The positional/named split (and, for capturing functions, the alias capture) is resolved later per candidate // overload. vector>> arguments; - // for legacy calls with names: fallback arguments that keep the names, used if binding positionally fails - vector>> named_arguments; arguments.reserve(function.GetArguments().size()); for (idx_t i = 0; i < function.GetArgumentsMutable().size(); i++) { auto &arg = function.GetArgumentsMutable()[i]; auto bound_arg = std::move(bound_children[i]); - - // legacy function calls cannot have named arguments, so we ignore the names of the arguments during binding - // and pass them all positionally. We do alias them by their name though, so that alias-capturing functions - // (e.g. struct_pack) still work and so that re-serializing to the old format can match arguments by name. - // Only override the alias when the argument actually carries a name, otherwise we would clobber the - // display alias the binding assigned (e.g. clearing a column reference's name to its raw binding). - if (!arg.GetName().empty()) { - bound_arg->SetAlias(arg.GetName()); - } if (function.IsLegacyFunctionCall()) { - if (!named_arguments.empty() || !arg.GetName().empty()) { - // first named argument: copy the unnamed arguments bound so far - for (idx_t prev = named_arguments.size(); prev < arguments.size(); prev++) { - named_arguments.emplace_back(Identifier(), arguments[prev].second->Copy()); - } - named_arguments.emplace_back(arg.GetName(), bound_arg->Copy()); - } arguments.emplace_back(string(), std::move(bound_arg)); } else { arguments.emplace_back(arg.GetName(), std::move(bound_arg)); @@ -435,11 +434,21 @@ BindResult ExpressionBinder::BindFunction(FunctionExpression &function, ScalarFu FunctionBinder function_binder(binder); auto result = function_binder.BindScalarFunction(func, std::move(arguments), error, function.IsOperator(), &binder); - if (!result && !named_arguments.empty()) { + if (!result && !named_fallback.empty()) { // a legacy call that does not bind positionally may use names the function declares (e.g. **kwargs) ErrorData named_error; - result = function_binder.BindScalarFunction(func, std::move(named_arguments), named_error, - function.IsOperator(), &binder); + vector>> named_arguments; + for (auto &arg : named_fallback) { + auto bound_arg = BindChild(arg.GetExpressionMutable(), depth, named_error, arg.GetName()); + if (named_error.HasError()) { + break; + } + named_arguments.emplace_back(arg.GetName(), std::move(bound_arg)); + } + if (!named_error.HasError()) { + result = function_binder.BindScalarFunction(func, std::move(named_arguments), named_error, + function.IsOperator(), &binder); + } } if (!result) { error.AddQueryLocation(function); diff --git a/src/duckdb/src/planner/binder/expression/bind_lambda.cpp b/src/duckdb/src/planner/binder/expression/bind_lambda.cpp index 8d1f991c4..ecef0d79f 100644 --- a/src/duckdb/src/planner/binder/expression/bind_lambda.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_lambda.cpp @@ -83,7 +83,7 @@ BindResult ExpressionBinder::BindExpression(LambdaExpression &expr, idx_t depth, // The arrow_expr now might contain bound nodes. // Restore the original expression. if (bind_result.HasError()) { - D_ASSERT(arrow_expr.GetChildrenMutable().size() == 2); + D_ASSERT(arrow_expr.GetChildren().size() == 2); expr.LeftMutable() = std::move(arrow_expr.GetChildrenMutable()[0]); expr.RightMutable() = std::move(arrow_expr.GetChildrenMutable()[1]); } @@ -182,7 +182,7 @@ void ExpressionBinder::TransformCapturedLambdaColumn(unique_ptr &ori offset += GetLambdaParamCount(*lambda_bindings); } offset += bound_lambda_expr.ParameterCount(); - offset += bound_lambda_expr.CapturesMutable().size(); + offset += bound_lambda_expr.Captures().size(); replacement = make_uniq(original->GetAlias(), original->GetReturnType(), offset); bound_lambda_expr.CapturesMutable().push_back(std::move(original)); 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 6e5748885..833e3b58f 100644 --- a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp @@ -166,7 +166,7 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) // by all of its arguments if (!binder.GetEnclosingScopes().empty()) { vector> children; - for (auto &child : op.GetChildrenMutable()) { + for (auto &child : op.GetChildren()) { children.push_back(*child); } auto owner = ResolveOuterGroup(children, 0); @@ -182,7 +182,7 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) ErrorData error; vector> children; if (operator_type == ExpressionType::OPERATOR_TRY) { - D_ASSERT(op.GetChildrenMutable().size() == 1); + D_ASSERT(op.GetChildren().size() == 1); auto &try_child = op.GetChildrenMutable()[0]; if (try_child->GetExpressionClass() == ExpressionClass::SUBQUERY && try_child->Cast().GetSubqueryType() == SubqueryType::SCALAR) { @@ -191,13 +191,13 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) } } if (operator_type == ExpressionType::OPERATOR_TRY || operator_type == ExpressionType::OPERATOR_HAS_ERROR) { - D_ASSERT(op.GetChildrenMutable().size() == 1); + D_ASSERT(op.GetChildren().size() == 1); const auto was_inside_try = inside_try; inside_try = true; children.push_back(BindChild(op.GetChildrenMutable()[0], depth, error)); inside_try = was_inside_try; } else { - for (idx_t i = 0; i < op.GetChildrenMutable().size(); i++) { + for (idx_t i = 0; i < op.GetChildren().size(); i++) { children.push_back(BindChild(op.GetChildrenMutable()[i], depth, error)); } } @@ -227,12 +227,11 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (uinteger_value) { // Array extraction: if the cast fails it's definitely out-of-bounds for a JSON array auto index = UIntegerValue::Get(*uinteger_value); - const_exp.SetValue(StringUtil::Format("$[%lld]", index)); - const_exp.SetReturnType(LogicalType::VARCHAR); + children[1] = const_exp.WithValue(Value(StringUtil::Format("$[%lld]", index))); } else if (const_exp.GetReturnType().id() == LogicalType::VARCHAR) { // Field extraction - const_exp.SetValue(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString())); - const_exp.SetReturnType(LogicalType::VARCHAR); + children[1] = + const_exp.WithValue(Value(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString()))); } } } else if (b_exp_type.id() == LogicalTypeId::VARIANT && children.size() == 2) { @@ -241,8 +240,8 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (i_exp.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { auto &const_exp = i_exp.Cast(); if (!const_exp.GetValue().IsNull() && const_exp.GetReturnType().IsIntegral()) { - const_exp.SetValue(const_exp.GetValue().CastAs(context, LogicalType::UINTEGER, true)); - const_exp.SetReturnType(LogicalType::UINTEGER); + children[1] = + const_exp.WithValue(const_exp.GetValue().CastAs(context, LogicalType::UINTEGER, true)); } } } else { @@ -279,8 +278,7 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (i_exp.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { auto &const_exp = i_exp.Cast(); if (!const_exp.GetValue().IsNull()) { - const_exp.SetValue(StringUtil::Format("%s", const_exp.GetValue().ToString())); - const_exp.SetReturnType(LogicalType::VARCHAR); + children[1] = const_exp.WithValue(Value(StringUtil::Format("%s", const_exp.GetValue().ToString()))); } } } else if (extract_expr_type.IsJSONType()) { @@ -289,8 +287,8 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (name_exp.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { auto &const_exp = name_exp.Cast(); if (!const_exp.GetValue().IsNull()) { - const_exp.SetValue(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString())); - const_exp.SetReturnType(LogicalType::VARCHAR); + children[1] = + const_exp.WithValue(Value(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString()))); } } } else if (extract_expr_type.id() == LogicalTypeId::GEOMETRY) { diff --git a/src/duckdb/src/planner/binder/expression/bind_parameter_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_parameter_expression.cpp index 01ba2a795..a70760f65 100644 --- a/src/duckdb/src/planner/binder/expression/bind_parameter_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_parameter_expression.cpp @@ -23,8 +23,7 @@ BindResult ExpressionBinder::BindExpression(ParameterExpression &expr, idx_t dep auto return_type = parameters->GetReturnType(parameter_id); bool is_literal = return_type.id() == LogicalTypeId::INTEGER_LITERAL || return_type.id() == LogicalTypeId::STRING_LITERAL; - auto constant = make_uniq(data.GetValue()); - constant->SetAlias(expr.GetAlias()); + auto constant = make_uniq(data.GetValue(), expr.GetAlias()); if (is_literal) { return BindResult(std::move(constant)); } @@ -37,8 +36,7 @@ BindResult ExpressionBinder::BindExpression(ParameterExpression &expr, idx_t dep PreparedStatement::AllowsUserVariableFallback(parameter_id)) { Value variable_value; if (ClientConfig::GetConfig(context).GetUserVariable(parameter_id, variable_value)) { - auto constant = make_uniq(variable_value); - constant->SetAlias(expr.GetAlias()); + auto constant = make_uniq(variable_value, expr.GetAlias()); return BindResult(std::move(constant)); } } diff --git a/src/duckdb/src/planner/binder/expression/bind_subquery_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_subquery_expression.cpp index cf4547b70..422b288c2 100644 --- a/src/duckdb/src/planner/binder/expression/bind_subquery_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_subquery_expression.cpp @@ -36,7 +36,7 @@ static void ExtractSubqueryChildren(unique_ptr &child, vector WrapInTry(unique_ptr child) { - auto result = make_uniq(ExpressionType::OPERATOR_TRY, child->GetReturnType()); - result->GetChildrenMutable().push_back(std::move(child)); + auto result = + make_uniq(ExpressionType::OPERATOR_TRY, child->GetReturnType(), std::move(child)); return std::move(result); } @@ -150,8 +150,8 @@ bool ExpressionBinder::GateTryAggregates(const ParsedExpression &location, Logic for (auto position : aggregate_positions) { auto &aggr_expr = aggregate.expressions[position]->Cast(); for (auto &child : aggr_expr.GetChildrenMutable()) { - auto probe = make_uniq(ExpressionType::OPERATOR_HAS_ERROR, LogicalType::BOOLEAN); - probe->GetChildrenMutable().push_back(child->Copy()); + auto probe = make_uniq(ExpressionType::OPERATOR_HAS_ERROR, LogicalType::BOOLEAN, + child->Copy()); gate = OrErrorFlags(std::move(gate), std::move(probe)); child = WrapInTry(std::move(child)); } @@ -352,8 +352,8 @@ optional ExpressionBinder::LowerTrySubquery(const ParsedExpression return optional(); } if (expose_error_flag) { - auto probe = make_uniq(ExpressionType::OPERATOR_HAS_ERROR, LogicalType::BOOLEAN); - probe->GetChildrenMutable().push_back(expr->Copy()); + auto probe = make_uniq(ExpressionType::OPERATOR_HAS_ERROR, LogicalType::BOOLEAN, + expr->Copy()); error_flag = std::move(probe); } expr = WrapInTry(std::move(expr)); @@ -430,7 +430,7 @@ static void PushTryIntoBareSubqueryItem(SubqueryExpression &subquery_expr) { //! flattened subplan and referenced as a column, so the TRY input and its HAS_ERROR probe observe one //! consistent value. BindResult ExpressionBinder::BindTrySubquery(OperatorExpression &op, idx_t depth) { - D_ASSERT(op.GetChildrenMutable().size() == 1); + D_ASSERT(op.GetChildren().size() == 1); auto &subquery_expr = op.GetChildrenMutable()[0]->Cast(); D_ASSERT(subquery_expr.GetSubqueryType() == SubqueryType::SCALAR); CheckTrySubqueryNode(subquery_expr, op); @@ -447,12 +447,12 @@ BindResult ExpressionBinder::BindTrySubquery(OperatorExpression &op, idx_t depth return result; } auto &bound_subquery = result.expression->Cast(); - if (bound_subquery.SubqueryMutable().plan) { + if (bound_subquery.Subquery().plan) { auto &indexes = bound_subquery.GetBinder()->GetTrySubqueryPlanIndexes(); if (!indexes.recorded) { throw InternalException("TRY subquery: no plan indexes were recorded for the top select node"); } - LowerTrySubquery(op, indexes, *bound_subquery.SubqueryMutable().plan, false, false); + LowerTrySubquery(op, indexes, *bound_subquery.Subquery().plan, false, false); } return result; } diff --git a/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp index 87a1b0d36..22d7a9415 100644 --- a/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp @@ -110,8 +110,8 @@ BindResult ExpressionBinder::BindExpression(TypeExpression &type_expr, idx_t dep type_entry.constructors.Bind(context, type_entry.user_type, bound_parameters, type_expr.GetQueryLocation()); // Return the resulting type! - auto result_expr = make_uniq(Value::TYPE(result_type)); - result_expr->SetQueryLocation(type_expr.GetQueryLocation()); + auto result_expr = + make_uniq(Value::TYPE(result_type), Identifier(), type_expr.GetQueryLocation()); return BindResult(std::move(result_expr)); } 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 ff5dba816..43c761e17 100644 --- a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp @@ -20,11 +20,12 @@ namespace duckdb { -static unique_ptr CastWindowExpression(unique_ptr bound, const LogicalType &type) { +static unique_ptr CastWindowExpression(ClientContext &context, unique_ptr bound, + const LogicalType &type) { if (!bound) { return nullptr; } - return BoundCastExpression::AddDefaultCastToType(std::move(bound), type); + return BoundCastExpression::AddCastToType(context, std::move(bound), type); } static bool IsRangeType(const LogicalType &type) { @@ -173,7 +174,8 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ ErrorData error; vector> bound_args; for (auto &child : window.GetArgumentsMutable()) { - bound_args.push_back(BindChild(child.GetExpressionMutable(), depth, error)); + // arguments are aliased by their name, if any (see BindFunction for the rationale) + bound_args.push_back(BindChild(child.GetExpressionMutable(), depth, error, child.GetName())); } vector> bound_partitions; for (auto &child : window.PartitionsMutable()) { @@ -238,15 +240,6 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ auto &arg = window.GetArgumentsMutable()[arg_idx]; auto bound_arg = std::move(bound_args[arg_idx]); - // legacy function calls cannot have named arguments, so we ignore the names of the arguments during binding - // and pass them all positionally. We do alias them by their name though, so that alias-capturing functions - // (e.g. struct_pack) still work and so that re-serializing to the old format can match arguments by name. - // Only override the alias when the argument actually carries a name, otherwise we would clobber the - // display alias the binding assigned (e.g. clearing a column reference's name to its raw binding). - if (!arg.GetName().empty()) { - bound_arg->SetAlias(arg.GetName()); - } - if (window.IsLegacyFunctionCall()) { arguments.emplace_back(Identifier(), std::move(bound_arg)); } else { @@ -440,11 +433,11 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ result->ArgOrdersMutable().emplace_back(type, null_order, std::move(bound_arg_orders[order_idx])); } - result->FilterMutable() = CastWindowExpression(std::move(bound_filter), LogicalType::BOOLEAN); + result->FilterMutable() = CastWindowExpression(context, std::move(bound_filter), LogicalType::BOOLEAN); optional_ptr original_start = bound_start.get(); optional_ptr original_end = bound_end.get(); - result->StartExprMutable() = CastWindowExpression(std::move(bound_start), start_type); - result->EndExprMutable() = CastWindowExpression(std::move(bound_end), end_type); + result->StartExprMutable() = CastWindowExpression(context, std::move(bound_start), start_type); + result->EndExprMutable() = CastWindowExpression(context, std::move(bound_end), end_type); if (result->SQLRangeStartBoundary() && !WindowRangeCast::Capture(*result->StartExpr(), *original_start, result->SQLRangeStartBoundaryMutable()->result_casts)) { diff --git a/src/duckdb/src/planner/binder/query_node/bind_cte_node.cpp b/src/duckdb/src/planner/binder/query_node/bind_cte_node.cpp index 7ff9f8868..251c6bb2d 100644 --- a/src/duckdb/src/planner/binder/query_node/bind_cte_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/bind_cte_node.cpp @@ -136,8 +136,10 @@ void CTEBindState::Bind(CTEBinding &binding) { // add this CTE to the query binder on the RHS with "CANNOT_BE_REFERENCED" to detect recursive references to // ourselves + auto self_type = cte_def.type == QueryNodeType::RECURSIVE_CTE_NODE ? CTEType::CANNOT_BE_REFERENCED_RECURSIVE + : CTEType::CANNOT_BE_REFERENCED; query_binder->bind_context.AddCTEBinding(binding.GetIndex(), binding.GetBindingAlias(), vector(), - vector(), CTEType::CANNOT_BE_REFERENCED); + vector(), self_type); // bind the actual CTE query = query_binder->Bind(cte_def); diff --git a/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp b/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp index 00921259f..7c4432514 100644 --- a/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp @@ -207,7 +207,7 @@ void Binder::PrepareModifiers(OrderBinder &order_binder, QueryNode &statement, B } } } - if (config.options.debug_order_verification == DebugOrderVerification::CREATE_SORT_KEY) { + if (Settings::Get(context) == DebugOrderVerification::CREATE_SORT_KEY) { // When this verification is enabled, replace ORDER BY x, y with ORDER BY create_sort_key(x, y) // note that we don't enable this during actual verification since it doesn't always work // e.g. it breaks EXPLAIN output on queries @@ -339,7 +339,7 @@ static void AssignReturnType(unique_ptr &expr, TableIndex table_inde return; } auto &bound_colref = expr->Cast(); - bound_colref.SetReturnType(sql_types[bound_colref.Binding().column_index]); + expr = bound_colref.WithReturnType(sql_types[bound_colref.Binding().column_index]); } void Binder::BindModifiers(BoundQueryNode &result, TableIndex table_index, const vector &names, @@ -394,18 +394,19 @@ void Binder::BindModifiers(BoundQueryNode &result, TableIndex table_index, const auto null_order = order.orders[0].null_order; order.orders.clear(); for (idx_t i = 0; i < sql_types.size(); i++) { - auto expr = make_uniq(sql_types[i], - ColumnBinding(table_index, ProjectionIndex(i))); + Identifier alias; if (i < names.size()) { - expr->SetAlias(names[i]); + alias = names[i]; } + auto expr = make_uniq(std::move(alias), sql_types[i], + ColumnBinding(table_index, ProjectionIndex(i))); order.orders.emplace_back(order_type, null_order, std::move(expr)); } } - auto &config = DBConfig::GetConfig(context); + auto order_verification = Settings::Get(context); for (auto &order_node : order.orders) { auto &expr = order_node.expression; - if (config.options.debug_order_verification == DebugOrderVerification::VARIANT && + if (order_verification == DebugOrderVerification::VARIANT && expr->GetReturnType().id() != LogicalTypeId::VARIANT) { // when this verification is enabled, cast every ORDER BY expression to VARIANT (the // PushCollation below then routes ordering through the VARIANT comparator) to verify it diff --git a/src/duckdb/src/planner/binder/query_node/bind_trigger_expansion.cpp b/src/duckdb/src/planner/binder/query_node/bind_trigger_expansion.cpp index a8434f65b..e648fb62e 100644 --- a/src/duckdb/src/planner/binder/query_node/bind_trigger_expansion.cpp +++ b/src/duckdb/src/planner/binder/query_node/bind_trigger_expansion.cpp @@ -513,16 +513,17 @@ BoundStatement Binder::ExpandTriggers(QueryNode &node, TableCatalogEntry &table, remap[injected_virtuals[k].first] = logical_count + k; } for (auto &expr : proj_exprs) { - ExpressionIterator::VisitExpressionMutable( - expr, [&](BoundColumnRefExpression &colref, unique_ptr &) { - auto &binding = colref.BindingMutable(); + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) -> unique_ptr { + auto &binding = colref.Binding(); if (binding.table_index != base_index) { - return; + return nullptr; } auto it = remap.find(binding.column_index.GetIndexUnsafe()); - if (it != remap.end()) { - binding.column_index = ProjectionIndex(it->second); + if (it == remap.end()) { + return nullptr; } + return colref.WithBinding(ColumnBinding(binding.table_index, ProjectionIndex(it->second))); }); } } 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 417afb060..7ca298240 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp @@ -6,6 +6,7 @@ #include "duckdb/function/scalar/generic_functions.hpp" #include "duckdb/main/client_config.hpp" #include "duckdb/planner/binder.hpp" +#include "duckdb/function/cast/cast_function_set.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" @@ -61,15 +62,19 @@ static bool PlanReturnsExactlyOneRow(const LogicalOperator &op) { } } -static bool IsExtremumRewriteValid(const BoundSubqueryExpression &expr) { +static bool IsExtremumRewriteValid(Binder &binder, const BoundSubqueryExpression &expr) { // TODO/FIXME: Generalize this rewrite to multi-column subqueries if (expr.GetChildren().size() != 1 || expr.GetChildTypes().size() != 1 || expr.GetChildTargets().size() != 1) { return false; } auto cmp_type = expr.ComparisonType(); - return cmp_type == ExpressionType::COMPARE_GREATERTHAN || - cmp_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO || cmp_type == ExpressionType::COMPARE_LESSTHAN || - cmp_type == ExpressionType::COMPARE_LESSTHANOREQUALTO; + if (cmp_type != ExpressionType::COMPARE_GREATERTHAN && cmp_type != ExpressionType::COMPARE_GREATERTHANOREQUALTO && + cmp_type != ExpressionType::COMPARE_LESSTHAN && cmp_type != ExpressionType::COMPARE_LESSTHANOREQUALTO) { + return false; + } + // the extremum is cast after aggregating, which requires an order-preserving cast - a registered one need not be + return !CastFunctionSet::Get(binder.context) + .CanOverrideDefaultCast(expr.GetChildTypes()[0], expr.GetChildTargets()[0]); } static unique_ptr PlanExtremumRewrite(Binder &binder, BoundSubqueryExpression &expr, @@ -151,8 +156,8 @@ static unique_ptr PlanExtremumRewrite(Binder &binder, BoundSubqueryE make_uniq(std::move(count_star_gt_count_child), null_val->Copy(), std::move(current_else)); // 3. WHEN X > MIN(Y) THEN TRUE - auto x_cast = BoundCastExpression::AddDefaultCastToType(x_expr.Copy(), compare_type); - auto extremum_cast = BoundCastExpression::AddDefaultCastToType(std::move(extremum_ref), compare_type); + auto x_cast = BoundCastExpression::AddCastToType(binder.context, x_expr.Copy(), compare_type); + auto extremum_cast = BoundCastExpression::AddCastToType(binder.context, std::move(extremum_ref), compare_type); unique_ptr x_op_min = BoundComparisonExpression::Create(cmp_type, std::move(x_cast), std::move(extremum_cast)); @@ -350,7 +355,7 @@ static unique_ptr PlanUncorrelatedSubquery(Binder &binder, BoundSubq } default: { D_ASSERT(expr.GetSubqueryType() == SubqueryType::ANY); - if (IsExtremumRewriteValid(expr)) { + if (IsExtremumRewriteValid(binder, expr)) { auto result = PlanExtremumRewrite(binder, expr, plan); root = LogicalCrossProduct::Create(std::move(root), std::move(plan)); return result; @@ -380,8 +385,8 @@ static unique_ptr PlanUncorrelatedSubquery(Binder &binder, BoundSubq for (idx_t i = 0; i < expr.GetChildTypes().size(); i++) { auto &child_type = expr.GetChildTypes()[i]; auto &compare_type = expr.GetChildTargets()[i]; - auto colref = BoundCastExpression::AddDefaultCastToType( - make_uniq(child_type, plan_columns[i]), compare_type); + auto colref = BoundCastExpression::AddCastToType( + binder.context, make_uniq(child_type, plan_columns[i]), compare_type); struct_children.push_back(std::move(colref)); } @@ -401,8 +406,9 @@ static unique_ptr PlanUncorrelatedSubquery(Binder &binder, BoundSubq for (idx_t child_idx = 0; child_idx < expr.GetChildren().size(); child_idx++) { auto &child_type = expr.GetChildTypes()[child_idx]; auto &compare_type = expr.GetChildTargets()[child_idx]; - auto right_expr = BoundCastExpression::AddDefaultCastToType( - make_uniq(child_type, plan_columns[child_idx]), compare_type); + auto right_expr = BoundCastExpression::AddCastToType( + binder.context, make_uniq(child_type, plan_columns[child_idx]), + compare_type); JoinCondition cond(std::move(expr.GetChildrenMutable()[child_idx]), std::move(right_expr), expr.ComparisonType()); @@ -571,7 +577,7 @@ static unique_ptr PlanCorrelatedSubquery(Binder &binder, BoundSubque default: { D_ASSERT(expr.GetSubqueryType() == SubqueryType::ANY); - if (IsExtremumRewriteValid(expr)) { + if (IsExtremumRewriteValid(binder, expr)) { auto result = PlanExtremumRewrite(binder, expr, plan); // For the extremum rewrite, we treat the correlated subquery just like a SCALAR query. // It produces a single aggregated result per RHS execution. @@ -612,8 +618,8 @@ static unique_ptr PlanCorrelatedSubquery(Binder &binder, BoundSubque auto left_expr = std::move(expr.GetChildrenMutable()[0]); auto &child_type = expr.GetChildTypes()[0]; auto &compare_type = expr.GetChildTargets()[0]; - auto right_expr = BoundCastExpression::AddDefaultCastToType( - make_uniq(child_type, plan_columns[0]), compare_type); + auto right_expr = BoundCastExpression::AddCastToType( + binder.context, make_uniq(child_type, plan_columns[0]), compare_type); ExpressionBinder::PushCollation(binder.context, left_expr, compare_type); ExpressionBinder::PushCollation(binder.context, right_expr, compare_type); delim_join->condition = diff --git a/src/duckdb/src/planner/binder/statement/bind_alter.cpp b/src/duckdb/src/planner/binder/statement/bind_alter.cpp index cad100d96..cd3ce2f99 100644 --- a/src/duckdb/src/planner/binder/statement/bind_alter.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_alter.cpp @@ -106,6 +106,9 @@ static void BindAlterTypes(Binder &binder, AlterStatement &stmt) { break; } } + for (auto &type : stmt.info->GetTypesToBind()) { + binder.BindLogicalType(type.get()); + } } BoundStatement Binder::Bind(AlterStatement &stmt) { @@ -148,9 +151,27 @@ BoundStatement Binder::Bind(AlterStatement &stmt) { view.BindView(context); } } else { - // For any other ALTER, we retrieve the catalog entry directly. - EntryLookupInfo lookup_info(stmt.info->GetCatalogType(), stmt.info->GetQualifiedName()); - entry = entry_retriever.GetEntry(lookup_info, stmt.info->if_not_found); + // For any other ALTER, we retrieve the catalog entry directly, trying each type the alter accepts + auto lookup_types = stmt.info->GetEntryLookupTypes(); + EntryLookupInfo lookup_info(lookup_types[0], stmt.info->GetQualifiedName()); + if (lookup_types.size() == 1) { + entry = entry_retriever.GetEntry(lookup_info, stmt.info->if_not_found); + } else { + for (auto &lookup_type : lookup_types) { + EntryLookupInfo type_lookup(lookup_type, stmt.info->GetQualifiedName()); + entry = entry_retriever.GetEntry(type_lookup, OnEntryNotFound::RETURN_NULL); + if (entry) { + break; + } + } + if (!entry) { + // a missing entry is reported for the first type + entry = entry_retriever.GetEntry(lookup_info, stmt.info->if_not_found); + } + } + if (entry) { + stmt.info->SetResolvedEntryType(entry->type); + } } auto &properties = GetStatementProperties(); diff --git a/src/duckdb/src/planner/binder/statement/bind_attach.cpp b/src/duckdb/src/planner/binder/statement/bind_attach.cpp index 81718c46e..61f0bce5d 100644 --- a/src/duckdb/src/planner/binder/statement/bind_attach.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_attach.cpp @@ -5,10 +5,17 @@ #include "duckdb/planner/operator/logical_attach.hpp" #include "duckdb/planner/expression_binder/table_function_binder.hpp" #include "duckdb/execution/expression_executor.hpp" +#include "duckdb/main/settings.hpp" namespace duckdb { void Binder::BindExternalResource(ExternalResourceOptions &external_resource) { + // Provisioning or borrowing a resource runs the resource type's callbacks and attaches to the endpoint they + // hand back, both of which reach outside the database - refused up front, before anything is resolved. + if (!Settings::Get(context)) { + throw PermissionException("External resources are disabled through configuration"); + } + // Reference form (`EXTERNAL RESOURCE `): the resource already exists — the physical operator // looks it up in the manager at execution. Nothing to resolve here. if (!external_resource.reference_name.empty()) { diff --git a/src/duckdb/src/planner/binder/statement/bind_copy.cpp b/src/duckdb/src/planner/binder/statement/bind_copy.cpp index 43d413ba5..440bb1b18 100644 --- a/src/duckdb/src/planner/binder/statement/bind_copy.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_copy.cpp @@ -60,7 +60,9 @@ void IsFormatExtensionKnown(const string &format) { identifier_map_t Binder::GetFullCopyOptionsList(const CopyFunction &function, CopyOptionMode mode) { identifier_map_t copy_options; CopyOptionsInput input(copy_options); - function.copy_options(context, input); + if (function.copy_options) { + function.copy_options(context, input); + } // first erase all options that don't match this type if (mode != CopyOptionMode::READ_WRITE) { @@ -805,10 +807,8 @@ void Binder::BindCopyFormat(CopyInfo &info) { } void Binder::BindCopyOptions(CopyInfo &info, const CopyFunction &function) { - identifier_map_t copy_options; - if (function.copy_options) { - copy_options = GetFullCopyOptionsList(function, CopyOptionMode::READ_WRITE); - } + // formats without their own option list still take the generic ones, such as PARTITION_BY + auto copy_options = GetFullCopyOptionsList(function, CopyOptionMode::READ_WRITE); unique_ptr partition_path; for (auto &[option_name, option_expr] : info.parsed_options) { if (option_name == "partition_path") { diff --git a/src/duckdb/src/planner/binder/statement/bind_create.cpp b/src/duckdb/src/planner/binder/statement/bind_create.cpp index 52a6d163d..b4e40acc1 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create.cpp @@ -18,6 +18,7 @@ #include "duckdb/parser/constraints/list.hpp" #include "duckdb/parser/constraints/unique_constraint.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/parser/expression/subquery_expression.hpp" @@ -873,6 +874,20 @@ unique_ptr DuckCatalog::BindCreateIndex(Binder &binder, CreateS return index_binder.BindCreateIndex(binder.context, std::move(create_index_info), table, std::move(plan), nullptr); } +//! The literal of a CREATE SECRET type or provider without evaluating it, empty when it is not a plain literal +static string SecretLiteral(const unique_ptr &expr) { + if (!expr) { + return string(); + } + if (expr->GetExpressionType() == ExpressionType::VALUE_CONSTANT) { + return StringUtil::Lower(expr->Cast().GetLiteral().ToValue().ToString()); + } + if (expr->GetExpressionType() == ExpressionType::COLUMN_REF) { + return StringUtil::Lower(expr->Cast().GetName().GetIdentifierName()); + } + return string(); +} + BoundStatement Binder::Bind(CreateStatement &stmt) { BoundStatement result; result.names = {"Count"}; @@ -1047,6 +1062,11 @@ BoundStatement Binder::Bind(CreateStatement &stmt) { auto &info = stmt.info->Cast(); + // Refuse before any option expression runs, so a refused statement has no side effects + SecretManager::ThrowIfSecretCreationDisabled(DatabaseInstance::GetDatabase(context), + Identifier(SecretLiteral(info.type)), + Identifier(SecretLiteral(info.provider))); + // We need to execute all expressions in the CreateSecretInfo to construct a CreateSecretInput ConstantBinder default_binder(*this, context, "Secret Parameter"); diff --git a/src/duckdb/src/planner/binder/statement/bind_execute.cpp b/src/duckdb/src/planner/binder/statement/bind_execute.cpp index b73daaace..45577c651 100644 --- a/src/duckdb/src/planner/binder/statement/bind_execute.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_execute.cpp @@ -1,8 +1,8 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/main/prepared_statement.hpp" +#include "duckdb/main/prepared_statement_data.hpp" #include "duckdb/parser/statement/execute_statement.hpp" #include "duckdb/planner/planner.hpp" -#include "duckdb/planner/operator/logical_execute.hpp" #include "duckdb/planner/expression_binder/constant_binder.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/execution/expression_executor.hpp" @@ -13,7 +13,7 @@ namespace duckdb { -BoundStatement Binder::Bind(ExecuteStatement &stmt) { +PreparedExecution Binder::ResolveExecute(ExecuteStatement &stmt) { auto parameter_count = stmt.named_param_map.size(); // bind the prepared statement @@ -58,7 +58,7 @@ BoundStatement Binder::Bind(ExecuteStatement &stmt) { } else { return_type = constant.GetValue().type(); } - parameter_data = BoundParameterData(constant.TakeValue(), std::move(return_type)); + parameter_data = BoundParameterData(constant.GetValue(), std::move(return_type)); } else { auto value = ExpressionExecutor::EvaluateScalar(context, *bound_expr, true); auto value_type = value.type(); @@ -67,8 +67,6 @@ BoundStatement Binder::Bind(ExecuteStatement &stmt) { bind_values[pair.first] = std::move(parameter_data); } prepared->PopulateMissingParameterValues(context, bind_values); - unique_ptr rebound_plan; - RebindQueryInfo rebind = RebindQueryInfo::DO_NOT_REBIND; if (prepared->RequireRebind(context, bind_values)) { rebind = RebindQueryInfo::ATTEMPT_TO_REBIND; @@ -80,33 +78,39 @@ BoundStatement Binder::Bind(ExecuteStatement &stmt) { rebind = RebindQueryInfo::ATTEMPT_TO_REBIND; } } - if (rebind == RebindQueryInfo::ATTEMPT_TO_REBIND) { - // catalog was modified or statement does not have clear types: rebind the statement before running the execute - Planner prepared_planner(context); - prepared_planner.parameter_data = bind_values; - prepared = prepared_planner.PrepareSQLStatement(entry->second->unbound_statement->Copy()); - rebound_plan = std::move(prepared_planner.plan); - D_ASSERT(prepared->properties.bound_all_parameters); - global_binder_state->bound_tables = prepared_planner.binder->global_binder_state->bound_tables; - } + PreparedExecution result; + result.prepared = std::move(prepared); + result.bind_values = std::move(bind_values); + result.rebind = rebind == RebindQueryInfo::ATTEMPT_TO_REBIND; + result.parameter_count = parameter_count; + return result; +} + +BoundStatement Binder::BindExecute(PreparedExecution &execution) { + // plan the prepared statement again with the supplied parameter values + Planner prepared_planner(context); + prepared_planner.parameter_data = execution.bind_values; + auto prepared = prepared_planner.PrepareSQLStatement(execution.prepared->unbound_statement->Copy()); + D_ASSERT(prepared->properties.bound_all_parameters); + global_binder_state->bound_tables = prepared_planner.binder->global_binder_state->bound_tables; + // copy the properties of the prepared statement into the planner auto &properties = GetStatementProperties(); properties = prepared->properties; - properties.parameter_count = parameter_count; + properties.parameter_count = execution.parameter_count; + + prepared->Bind(context, execution.bind_values); BoundStatement result; result.names = prepared->names; result.types = prepared->types; - - prepared->Bind(context, bind_values); - if (rebound_plan) { - auto execute_plan = make_uniq(std::move(prepared)); - execute_plan->children.push_back(std::move(rebound_plan)); - result.plan = std::move(execute_plan); - } else { - result.plan = make_uniq(std::move(prepared)); - } + result.plan = std::move(prepared_planner.plan); return result; } +BoundStatement Binder::Bind(ExecuteStatement &stmt) { + auto execution = ResolveExecute(stmt); + return BindExecute(execution); +} + } // namespace duckdb diff --git a/src/duckdb/src/planner/binder/statement/bind_external_resource.cpp b/src/duckdb/src/planner/binder/statement/bind_external_resource.cpp index 13660130c..f33afc160 100644 --- a/src/duckdb/src/planner/binder/statement/bind_external_resource.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_external_resource.cpp @@ -3,6 +3,7 @@ #include "duckdb/parser/statement/external_resource_statement.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression_binder/table_function_binder.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/planner/operator/logical_external_resource.hpp" namespace duckdb { @@ -25,6 +26,12 @@ BoundStatement Binder::Bind(ExternalResourceStatement &stmt) { result.types = {LogicalType::BOOLEAN}; result.names = {"Success"}; + // Every verb runs the resource type's callbacks (create/status, resolve, destroy), which reach outside the + // database - refused up front, before the statement is looked at any further. + if (!Settings::Get(context)) { + throw PermissionException("External resources are disabled through configuration"); + } + BoundExternalResource data; data.operation = stmt.operation; data.name = stmt.name.GetIdentifierName(); diff --git a/src/duckdb/src/planner/binder/statement/bind_merge_into.cpp b/src/duckdb/src/planner/binder/statement/bind_merge_into.cpp index 90d5992b9..12b8b21b4 100644 --- a/src/duckdb/src/planner/binder/statement/bind_merge_into.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_merge_into.cpp @@ -379,8 +379,7 @@ BoundStatement Binder::BindNode(MergeQueryNode &node) { auto proj = LogicalProjection::CreateIdentity(new_proj_index, std::move(source)); // insert the source marker - auto marker = make_uniq(Value::INTEGER(42)); - marker->SetAlias("source_marker"); + auto marker = make_uniq(Value::INTEGER(42), "source_marker"); ColumnBinding source_marker; auto source_marker_idx = ColumnBinding::PushExpression(proj->expressions, std::move(marker)); source_marker = ColumnBinding(new_proj_index, source_marker_idx); @@ -399,8 +398,7 @@ BoundStatement Binder::BindNode(MergeQueryNode &node) { // push a reference merge_into->source_marker = projection_expressions.size(); - auto marker_ref = make_uniq(LogicalType::INTEGER, source_marker); - marker_ref->SetAlias("source_marker"); + auto marker_ref = make_uniq("source_marker", LogicalType::INTEGER, source_marker); projection_expressions.push_back(std::move(marker_ref)); } diff --git a/src/duckdb/src/planner/binder/statement/bind_update.cpp b/src/duckdb/src/planner/binder/statement/bind_update.cpp index 716dbbce1..85c2f7406 100644 --- a/src/duckdb/src/planner/binder/statement/bind_update.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_update.cpp @@ -117,9 +117,9 @@ void Binder::BindRowIdColumns(TableCatalogEntry &table, LogicalGet &get, vector< break; } } - auto row_id_expr = make_uniq( - row_id_entry->second.type, ColumnBinding(get.table_index, ProjectionIndex(column_idx))); - row_id_expr->SetAlias(row_id_entry->second.name); + auto row_id_expr = + make_uniq(row_id_entry->second.name, row_id_entry->second.type, + ColumnBinding(get.table_index, ProjectionIndex(column_idx))); expressions.push_back(std::move(row_id_expr)); if (column_idx == column_ids.size()) { get.AddColumnId(row_id_column); @@ -202,9 +202,6 @@ BoundStatement Binder::BindNode(UpdateQueryNode &node) { update->return_chunk = true; } update->capture_old_rows = capture_old_rows; - // UPDATE ... FROM can match a target row via multiple source rows, so deduplicate keeping the first match; - // a plain UPDATE cannot produce duplicate row-ids, so it keeps the lock-free path. - update->row_id_handling = node.from_table ? RowIdHandling::KEEP_FIRST : RowIdHandling::ASSUME_UNIQUE; // bind the default values auto &catalog_name = table.ParentCatalog().GetName(); BindDefaultValues(table.GetColumns(), update->bound_defaults, catalog_name.GetIdentifierName(), diff --git a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp index de3d0d9af..d6d1bc0b8 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp @@ -240,9 +240,14 @@ BoundStatement Binder::Bind(BaseTableRef &ref) { // if we found a CTE that cannot be referenced that means that there is a circular reference if (ctebinding) { D_ASSERT(!ctebinding->CanBeReferenced()); + if (ctebinding->IsRecursiveSelfReference()) { + throw BinderException(error_context, + "Recursive reference to CTE %s must not appear in its non-recursive term", + ref.Table()); + } throw BinderException(error_context, - "Circular reference to CTE %s, use WITH RECURSIVE to " - "use recursive CTEs.", + "Circular reference to CTE %s, recursive CTEs must use WITH RECURSIVE and have the " + "form UNION [ALL] ", ref.Table()); } // could not find an alternative: bind again to get the error diff --git a/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp b/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp index 4bd8d8543..47809656a 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp @@ -388,9 +388,8 @@ BoundStatement Binder::Bind(JoinRef &ref) { // AND the USING/NATURAL conditions onto the condition written in the query, in that order for (auto &condition : extra_conditions) { if (result->condition) { - auto conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); - conjunction->GetChildrenMutable().push_back(std::move(result->condition)); - conjunction->GetChildrenMutable().push_back(std::move(condition)); + auto conjunction = make_uniq( + ExpressionType::CONJUNCTION_AND, std::move(result->condition), std::move(condition)); result->condition = std::move(conjunction); } else { result->condition = std::move(condition); diff --git a/src/duckdb/src/planner/bound_parameter_map.cpp b/src/duckdb/src/planner/bound_parameter_map.cpp index 650bf968e..e1580db7c 100644 --- a/src/duckdb/src/planner/bound_parameter_map.cpp +++ b/src/duckdb/src/planner/bound_parameter_map.cpp @@ -50,10 +50,9 @@ unique_ptr BoundParameterMap::BindParameterExpression( // We return a shared pointer to an object that will get populated with a Value later // When the BoundParameterExpression gets executed, this will be used to get the corresponding value auto param_data = CreateOrGetData(identifier); - auto bound_expr = make_uniq(identifier); + auto bound_expr = make_uniq(identifier, expr.GetAlias()); bound_expr->ParameterDataMutable() = param_data; - bound_expr->SetAlias(expr.GetAlias()); auto param_type = param_data->return_type; auto identifier_type = GetReturnType(identifier); diff --git a/src/duckdb/src/planner/collation_binding.cpp b/src/duckdb/src/planner/collation_binding.cpp index 3f5a3e09b..3accfb4c7 100644 --- a/src/duckdb/src/planner/collation_binding.cpp +++ b/src/duckdb/src/planner/collation_binding.cpp @@ -116,10 +116,8 @@ static unique_ptr ApplyCollationFunction(ClientContext &context, con vector> children; children.push_back(std::move(source)); FunctionBinder function_binder(context); - auto function = - function_binder.BindScalarFunction(Identifier::DefaultSchema(), Identifier(function_name), std::move(children)); - function->SetAlias(source_alias); - return function; + return function_binder.BindScalarFunction(Identifier::DefaultSchema(), Identifier(function_name), + std::move(children), false, nullptr, std::move(source_alias)); } //! Pushes collations into STRUCT/TUPLE fields using invoke with a lambda that rebuilds the value and preserves NULLs. @@ -169,8 +167,8 @@ static bool PushStructCollation(ClientContext &context, unique_ptr & auto result = function_binder.BindScalarFunction(Identifier::DefaultSchema(), Identifier(is_tuple ? "row" : "struct_pack"), std::move(fields)); // A NULL struct must remain distinct from a struct containing only NULL fields. - auto is_null = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - is_null->GetChildrenMutable().push_back(lambda_parameter_expr->Copy()); + auto is_null = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, + lambda_parameter_expr->Copy()); auto null_result = make_uniq(Value(result->GetReturnType())); auto body = make_uniq(std::move(is_null), std::move(null_result), std::move(result)); auto lambda = @@ -182,8 +180,8 @@ static bool PushStructCollation(ClientContext &context, unique_ptr & vector> arguments; arguments.push_back(std::move(lambda)); arguments.push_back(std::move(source)); - source = function_binder.BindScalarFunction(Identifier::DefaultSchema(), "invoke", std::move(arguments)); - source->SetAlias(source_alias); + source = function_binder.BindScalarFunction(Identifier::DefaultSchema(), "invoke", std::move(arguments), false, + nullptr, std::move(source_alias)); return true; } diff --git a/src/duckdb/src/planner/expression/bound_cast_expression.cpp b/src/duckdb/src/planner/expression/bound_cast_expression.cpp index 7afbd4bae..4aa164f74 100644 --- a/src/duckdb/src/planner/expression/bound_cast_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_cast_expression.cpp @@ -3,16 +3,16 @@ #include "duckdb/planner/expression/bound_parameter_expression.hpp" #include "duckdb/function/cast/bound_cast_data.hpp" #include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/common/limits.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/planner/expression_binder.hpp" namespace duckdb { -enum class CastBindSource : uint8_t { CONTEXT, DEFAULT }; - static unique_ptr AddCastExpressionInternal(unique_ptr expr, const LogicalType &target_type, - BoundCastInfo bound_cast, bool try_cast, - CastBindSource bind_source) { + BoundCastInfo bound_cast, bool try_cast) { if (ExpressionBinder::GetExpressionReturnType(*expr) == target_type) { return expr; } @@ -24,15 +24,12 @@ static unique_ptr AddCastExpressionInternal(unique_ptr e return expr; } } - if (bind_source == CastBindSource::DEFAULT) { - return BoundCastExpression::CreateDefault(std::move(expr), target_type, std::move(bound_cast), try_cast); - } return BoundCastExpression::Create(std::move(expr), target_type, std::move(bound_cast), try_cast); } static unique_ptr AddCastToTypeInternal(unique_ptr expr, const LogicalType &target_type, CastFunctionSet &cast_functions, GetCastFunctionInput &get_input, - bool try_cast, CastBindSource bind_source) { + bool try_cast) { D_ASSERT(expr); if (expr->GetExpressionClass() == ExpressionClass::BOUND_PARAMETER) { auto ¶meter = expr->Cast(); @@ -64,8 +61,7 @@ static unique_ptr AddCastToTypeInternal(unique_ptr expr, // Add a regular cast on top instead of invalidating. if (parameter.GetReturnType() == parameter.ParameterData()->return_type) { auto cast_function = cast_functions.GetCastFunction(parameter.GetReturnType(), target_type, get_input); - return AddCastExpressionInternal(std::move(expr), target_type, std::move(cast_function), try_cast, - bind_source); + return AddCastExpressionInternal(std::move(expr), target_type, std::move(cast_function), try_cast); } // invalidate the type parameter.ParameterData()->return_type = LogicalType::INVALID; @@ -73,33 +69,27 @@ static unique_ptr AddCastToTypeInternal(unique_ptr expr, return expr; } else if (expr->GetExpressionClass() == ExpressionClass::BOUND_DEFAULT) { D_ASSERT(target_type.IsValid()); - auto &def = expr->Cast(); - def.SetReturnType(target_type); + expr = make_uniq(target_type, expr->GetAlias(), expr->GetQueryLocation()); } if (!target_type.IsValid()) { return expr; } auto cast_function = cast_functions.GetCastFunction(expr->GetReturnType(), target_type, get_input); - return AddCastExpressionInternal(std::move(expr), target_type, std::move(cast_function), try_cast, bind_source); + return AddCastExpressionInternal(std::move(expr), target_type, std::move(cast_function), try_cast); } -unique_ptr BoundCastExpression::AddDefaultCastToType(unique_ptr expr, - const LogicalType &target_type, bool try_cast) { - CastFunctionSet default_set; - GetCastFunctionInput get_input; +unique_ptr BoundCastExpression::AddCastToType(Context &context, unique_ptr expr, + const LogicalType &target_type, bool try_cast) { + auto &cast_functions = CastFunctionSet::Get(context.GetDatabase()); + GetCastFunctionInput get_input(context); get_input.query_location = expr->GetQueryLocation(); - return AddCastToTypeInternal(std::move(expr), target_type, default_set, get_input, try_cast, - CastBindSource::DEFAULT); + return AddCastToTypeInternal(std::move(expr), target_type, cast_functions, get_input, try_cast); } unique_ptr BoundCastExpression::AddCastToType(ClientContext &context, unique_ptr expr, const LogicalType &target_type, bool try_cast) { - auto &cast_functions = DBConfig::GetConfig(context).GetCastFunctions(); - GetCastFunctionInput get_input(context); - get_input.query_location = expr->GetQueryLocation(); - return AddCastToTypeInternal(std::move(expr), target_type, cast_functions, get_input, try_cast, - CastBindSource::CONTEXT); + return AddCastToType(context.GetContext(), std::move(expr), target_type, try_cast); } unique_ptr BoundCastExpression::AddArrayCastToList(ClientContext &context, unique_ptr expr) { @@ -280,47 +270,75 @@ bool BoundCastExpression::CastIsInvertible(const LogicalType &source_type, const return true; } +static bool IsExactNumeric(const LogicalType &type) { + return type.IsIntegral() || type.id() == LogicalTypeId::DECIMAL; +} + +//! Whether an integral or DECIMAL source fits in the digits10 of the floating target, so that distinct source values +//! stay distinct floating values +static bool IsLosslessExactNumericToFloatingCast(const LogicalType &source_type, const LogicalType &target_type) { + uint32_t width, scale; + if (!IsExactNumeric(source_type) || !source_type.GetDecimalProperties(width, scale)) { + return false; + } + switch (target_type.id()) { + case LogicalTypeId::DOUBLE: + return width <= std::numeric_limits::digits10; + case LogicalTypeId::FLOAT: + return width <= std::numeric_limits::digits10; + default: + return false; + } +} + bool BoundCastExpression::IsLosslessIntegralToFloatingCast(const LogicalType &source_type, const LogicalType &target_type) { - if (target_type.id() == LogicalTypeId::DOUBLE) { - switch (source_type.id()) { - case LogicalTypeId::TINYINT: - case LogicalTypeId::SMALLINT: - case LogicalTypeId::INTEGER: - case LogicalTypeId::UTINYINT: - case LogicalTypeId::USMALLINT: - case LogicalTypeId::UINTEGER: - return true; - default: - return false; - } + return source_type.IsIntegral() && IsLosslessExactNumericToFloatingCast(source_type, target_type); +} + +//! Whether every value of the type has a unique VARCHAR representation that casts back to the same value +static bool HasCanonicalVarcharRepresentation(const LogicalType &type) { + if (type.IsIntegral()) { + return true; } - if (target_type.id() == LogicalTypeId::FLOAT) { - switch (source_type.id()) { - case LogicalTypeId::TINYINT: - case LogicalTypeId::SMALLINT: - case LogicalTypeId::UTINYINT: - case LogicalTypeId::USMALLINT: - return true; - default: - return false; - } + // unlike CastIsInvertible, TZ types are excluded: equal TIME_TZ values with different offsets render differently, + // and the rendering of TIMESTAMP_TZ depends on the TimeZone setting + switch (type.id()) { + case LogicalTypeId::BOOLEAN: + case LogicalTypeId::DECIMAL: + case LogicalTypeId::UUID: + case LogicalTypeId::DATE: + case LogicalTypeId::TIME: + case LogicalTypeId::TIME_NS: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_NS: + return true; + default: + return false; } - return false; } bool BoundCastExpression::CastIsInvertibleForEquality(const LogicalType &source_type, const LogicalType &target_type) { - if (source_type.IsIntegral()) { - if (target_type.id() == LogicalTypeId::VARCHAR) { - // a collation can make distinct strings equal - return StringType::GetCollation(target_type).empty(); - } - if (IsLosslessIntegralToFloatingCast(source_type, target_type)) { - return true; - } - return target_type.IsIntegral() && CastIsInvertible(source_type, target_type); + if (target_type.id() == LogicalTypeId::VARCHAR) { + // 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)) { + 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::FLOAT && target_type.id() == LogicalTypeId::DOUBLE; } optional BoundCastExpression::TryInvertConstant(ClientContext &context, const BoundFunctionExpression &cast_expr, diff --git a/src/duckdb/src/planner/expression/bound_columnref_expression.cpp b/src/duckdb/src/planner/expression/bound_columnref_expression.cpp index 081cba658..fe501cedb 100644 --- a/src/duckdb/src/planner/expression/bound_columnref_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_columnref_expression.cpp @@ -6,16 +6,37 @@ namespace duckdb { BoundColumnRefExpression::BoundColumnRefExpression(Identifier alias_p, LogicalType type, ColumnBinding binding, - idx_t depth) + idx_t depth, QueryLocation location) : Expression(ExpressionType::BOUND_COLUMN_REF, ExpressionClass::BOUND_COLUMN_REF, std::move(type)), binding(binding), depth(depth) { this->alias = std::move(alias_p); + query_location = location; } BoundColumnRefExpression::BoundColumnRefExpression(LogicalType type, ColumnBinding binding, idx_t depth) : BoundColumnRefExpression(Identifier(), std::move(type), binding, depth) { } +unique_ptr BoundColumnRefExpression::WithBinding(ColumnBinding new_binding) const { + return WithBinding(new_binding, depth); +} + +unique_ptr BoundColumnRefExpression::WithBinding(ColumnBinding new_binding, idx_t new_depth) const { + return make_uniq(alias, return_type, new_binding, new_depth, query_location); +} + +unique_ptr BoundColumnRefExpression::WithBinding(ColumnBinding new_binding, LogicalType new_type) const { + return make_uniq(alias, std::move(new_type), new_binding, depth, query_location); +} + +unique_ptr BoundColumnRefExpression::WithReturnType(LogicalType new_type) const { + return WithBinding(binding, std::move(new_type)); +} + +unique_ptr BoundColumnRefExpression::WithDepth(idx_t new_depth) const { + return WithBinding(binding, new_depth); +} + unique_ptr BoundColumnRefExpression::Copy() const { return make_uniq(alias, return_type, binding, depth); } diff --git a/src/duckdb/src/planner/expression/bound_constant_expression.cpp b/src/duckdb/src/planner/expression/bound_constant_expression.cpp index 5e558567c..4fb7d8ed4 100644 --- a/src/duckdb/src/planner/expression/bound_constant_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_constant_expression.cpp @@ -11,13 +11,14 @@ BoundConstantExpression::BoundConstantExpression(Value value_p) value(std::move(value_p)) { } -void BoundConstantExpression::SetValue(Value value_p) { - return_type = value_p.type(); - value = std::move(value_p); +BoundConstantExpression::BoundConstantExpression(Value value_p, Identifier alias_p, QueryLocation location) + : BoundConstantExpression(std::move(value_p)) { + alias = std::move(alias_p); + query_location = location; } -Value BoundConstantExpression::TakeValue() { - return std::move(value); +unique_ptr BoundConstantExpression::WithValue(Value new_value) const { + return make_uniq(std::move(new_value), alias, query_location); } void BoundConstantExpression::SetReturnType(LogicalType type) { diff --git a/src/duckdb/src/planner/expression/bound_function_expression.cpp b/src/duckdb/src/planner/expression/bound_function_expression.cpp index 0e4e9cdcc..5586ad6d1 100644 --- a/src/duckdb/src/planner/expression/bound_function_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_function_expression.cpp @@ -21,12 +21,15 @@ static optional_ptr GetLambdaExpression(const BoundFunctionExp BoundFunctionExpression::BoundFunctionExpression(BoundScalarFunction bound_function, vector> arguments, - unique_ptr bind_info_p, bool is_operator) + unique_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()), function(std::move(bound_function)), children(std::move(arguments)), bind_info(std::move(bind_info_p)), is_operator(is_operator) { D_ASSERT(!function.GetName().empty()); + alias = std::move(alias_p); + query_location = location; } ExpressionType BoundFunctionExpression::GetFunctionExpressionType(const BoundScalarFunction &bound_function, diff --git a/src/duckdb/src/planner/expression/bound_operator_expression.cpp b/src/duckdb/src/planner/expression/bound_operator_expression.cpp index 0955ca5bf..ee93f79c7 100644 --- a/src/duckdb/src/planner/expression/bound_operator_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_operator_expression.cpp @@ -8,6 +8,25 @@ BoundOperatorExpression::BoundOperatorExpression(ExpressionType type, LogicalTyp : Expression(type, ExpressionClass::BOUND_OPERATOR, std::move(return_type)) { } +BoundOperatorExpression::BoundOperatorExpression(ExpressionType type, LogicalType return_type, + unique_ptr child) + : BoundOperatorExpression(type, std::move(return_type)) { + children.push_back(std::move(child)); +} + +BoundOperatorExpression::BoundOperatorExpression(ExpressionType type, LogicalType return_type, + unique_ptr left, unique_ptr right) + : BoundOperatorExpression(type, std::move(return_type)) { + children.push_back(std::move(left)); + children.push_back(std::move(right)); +} + +BoundOperatorExpression::BoundOperatorExpression(ExpressionType type, LogicalType return_type, + vector> children_p) + : BoundOperatorExpression(type, std::move(return_type)) { + children = std::move(children_p); +} + string BoundOperatorExpression::ToString() const { return OperatorExpression::ToString(*this); } diff --git a/src/duckdb/src/planner/expression/bound_parameter_expression.cpp b/src/duckdb/src/planner/expression/bound_parameter_expression.cpp index ab6ec7b47..76b2ff1fe 100644 --- a/src/duckdb/src/planner/expression/bound_parameter_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_parameter_expression.cpp @@ -5,10 +5,11 @@ namespace duckdb { -BoundParameterExpression::BoundParameterExpression(const duckdb::Identifier &identifier) +BoundParameterExpression::BoundParameterExpression(const duckdb::Identifier &identifier, duckdb::Identifier alias_p) : Expression(ExpressionType::VALUE_PARAMETER, ExpressionClass::BOUND_PARAMETER, LogicalType(LogicalTypeId::UNKNOWN)), identifier(identifier) { + alias = std::move(alias_p); } BoundParameterExpression::BoundParameterExpression(bound_parameter_map_t &global_parameter_set, diff --git a/src/duckdb/src/planner/expression/bound_reference_expression.cpp b/src/duckdb/src/planner/expression/bound_reference_expression.cpp index 24d8eb398..56b0a652c 100644 --- a/src/duckdb/src/planner/expression/bound_reference_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_reference_expression.cpp @@ -38,6 +38,12 @@ hash_t BoundReferenceExpression::Hash() const { return CombineHash(Expression::Hash(), duckdb::Hash(index)); } +unique_ptr BoundReferenceExpression::WithIndex(idx_t new_index) const { + auto result = make_uniq(alias, return_type, new_index); + result->query_location = query_location; + return std::move(result); +} + unique_ptr BoundReferenceExpression::Copy() const { return make_uniq(alias, return_type, index); } diff --git a/src/duckdb/src/planner/expression_binder.cpp b/src/duckdb/src/planner/expression_binder.cpp index a60b2d1a9..6fe7df28c 100644 --- a/src/duckdb/src/planner/expression_binder.cpp +++ b/src/duckdb/src/planner/expression_binder.cpp @@ -173,11 +173,12 @@ BindResult ExpressionBinder::BindInEnclosingScope(ColumnRefExpression &col_ref, return BindResult(std::move(bind_error)); } -unique_ptr ExpressionBinder::BindChild(unique_ptr &expr, idx_t depth, ErrorData &error) { +unique_ptr ExpressionBinder::BindChild(unique_ptr &expr, idx_t depth, ErrorData &error, + const Identifier &alias) { if (!expr) { return nullptr; } - auto result = Bind(expr, depth); + auto result = Bind(expr, depth, false, alias); if (result.HasError()) { if (!error.HasError()) { error = std::move(result.error); @@ -304,9 +305,10 @@ unique_ptr ExpressionBinder::Bind(unique_ptr &expr return result; } -BindResult ExpressionBinder::Bind(unique_ptr &expr, idx_t depth, bool root_expression) { +BindResult ExpressionBinder::Bind(unique_ptr &expr, idx_t depth, bool root_expression, + const Identifier &alias_p) { auto query_location = expr->GetQueryLocation(); - auto alias = expr->GetAlias(); + auto alias = alias_p.empty() ? expr->GetAlias() : alias_p; BindResult result = BindExpression(expr, depth, root_expression); if (result.HasError()) { return result; diff --git a/src/duckdb/src/planner/expression_binder/base_select_binder.cpp b/src/duckdb/src/planner/expression_binder/base_select_binder.cpp index 577283bb1..333080b6d 100644 --- a/src/duckdb/src/planner/expression_binder/base_select_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/base_select_binder.cpp @@ -163,8 +163,8 @@ BindResult BaseSelectBinder::BindGroup(ParsedExpression &expr, idx_t depth, Proj Identifier(expr.GetName()), group->GetReturnType(), ColumnBinding(node.group_index, group_index), depth); auto sql_null = make_uniq(Value(return_type)); - auto when_expr = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - when_expr->GetChildrenMutable().push_back(std::move(collated_group_expression)); + auto when_expr = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, + std::move(collated_group_expression)); auto then_expr = make_uniq(Value(return_type)); auto else_expr = std::move(uncollated_first_expression); auto case_expr = diff --git a/src/duckdb/src/planner/expression_binder/index_binder.cpp b/src/duckdb/src/planner/expression_binder/index_binder.cpp index abb3a9d7f..1526dd6c4 100644 --- a/src/duckdb/src/planner/expression_binder/index_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/index_binder.cpp @@ -1,5 +1,6 @@ #include "duckdb/planner/expression_binder/index_binder.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/common/error_data.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/parser/parsed_data/create_index_info.hpp" @@ -25,6 +26,44 @@ IndexBinder::IndexBinder(Binder &binder, ClientContext &context, optional_ptr FindLambdaFunction(const Expression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + auto &function = expr.Cast(); + if (function.Function().HasBindLambdaCallback()) { + return &function; + } + } + optional_ptr result; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + if (!result) { + result = FindLambdaFunction(child); + } + }); + return result; +} + +static bool IsValidIndexExpression(Binder &binder, const Expression &expr, ErrorData &error) { + // casts are bound without the binder, so a cast that reads settings such as TimeZone is found in the key + if (binder.GetStatementProperties().always_require_rebind || expr.RequiresRebind()) { + error = BinderException("Index keys cannot contain expressions with side effects. They also cannot depend on " + "settings such as TimeZone."); + return false; + } + // Lambda functions require a ClientContext, but the index's expression executor has none, so reject. + auto lambda_function = FindLambdaFunction(expr); + if (lambda_function) { + error = BinderException(*lambda_function, "Index keys cannot contain lambda functions such as %s.", + lambda_function->Function().GetName()); + return false; + } + if (!expr.IsConsistent()) { + error = BinderException("Index keys cannot contain expressions with side effects."); + return false; + } + return true; +} + unique_ptr IndexBinder::BindIndex(const UnboundIndex &unbound_index) { auto &index_type_name = unbound_index.GetIndexType(); // Do we know the type of this index now? @@ -40,12 +79,21 @@ unique_ptr IndexBinder::BindIndex(const UnboundIndex &unbound_index) auto &parsed_expressions = unbound_index.GetParsedExpressions(); // bind the parsed expressions to create unbound expressions + auto &properties = binder.GetStatementProperties(); + const auto statement_requires_rebind = properties.always_require_rebind; vector> unbound_expressions; unbound_expressions.reserve(parsed_expressions.size()); for (auto &expr : parsed_expressions) { auto copy = expr->Copy(); + properties.always_require_rebind = false; unbound_expressions.push_back(Bind(copy)); + // Stored keys must satisfy the same requirements as newly created keys. + ErrorData error; + if (!IsValidIndexExpression(binder, *unbound_expressions.back(), error)) { + throw DataCorruptionException("Invalid index %s: %s", create_info.GetIndexName(), error.RawMessage()); + } } + properties.always_require_rebind = statement_requires_rebind; CreateIndexInput input(context, unbound_index.table_io_manager, unbound_index.db, create_info.constraint_type, create_info.GetIndexName(), create_info.column_ids, unbound_expressions, storage_info, @@ -77,23 +125,6 @@ void IndexBinder::InitCreateIndexInfo(LogicalGet &get, CreateIndexInfo &info) { get.AddColumnId(COLUMN_IDENTIFIER_ROW_ID); } -//! Returns a lambda function of the key, if any -static optional_ptr FindLambdaFunction(const Expression &expr) { - if (expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { - auto &function = expr.Cast(); - if (function.Function().HasBindLambdaCallback()) { - return &function; - } - } - optional_ptr result; - ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { - if (!result) { - result = FindLambdaFunction(child); - } - }); - return result; -} - unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, unique_ptr create_index_info, TableCatalogEntry &table_entry, @@ -125,16 +156,9 @@ unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, for (auto &expr : create_index_info->expressions) { properties.always_require_rebind = false; expressions.push_back(Bind(expr)); - // casts are bound without the binder, so a cast that reads settings such as TimeZone is found in the key - if (properties.always_require_rebind || expressions.back()->RequiresRebind()) { - throw BinderException("Index keys cannot contain expressions with side effects. They also cannot depend on " - "settings such as TimeZone."); - } - // lambda functions need a ClientContext to execute, which appends and deletes do not have - auto lambda_function = FindLambdaFunction(*expressions.back()); - if (lambda_function) { - throw BinderException(*lambda_function, "Index keys cannot contain lambda functions such as %s.", - lambda_function->Function().GetName()); + ErrorData error; + if (!IsValidIndexExpression(binder, *expressions.back(), error)) { + error.Throw(); } } properties.always_require_rebind = statement_requires_rebind; diff --git a/src/duckdb/src/planner/expression_binder/lateral_binder.cpp b/src/duckdb/src/planner/expression_binder/lateral_binder.cpp index cdce470f8..80351e9ca 100644 --- a/src/duckdb/src/planner/expression_binder/lateral_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/lateral_binder.cpp @@ -55,18 +55,19 @@ string LateralBinder::UnsupportedAggregateMessage() { return "LATERAL join cannot contain aggregates!"; } -static void ReduceColumnRefDepth(BoundColumnRefExpression &expr, const CorrelatedColumns &correlated_columns) { - // don't need to reduce this +//! Returns the column reference with a reduced depth, or nullptr if the depth does not need to be reduced +static unique_ptr ReduceColumnRefDepth(const BoundColumnRefExpression &expr, + const CorrelatedColumns &correlated_columns) { if (expr.Depth() == 0) { - return; + return nullptr; } for (auto &correlated : correlated_columns) { if (correlated.binding == expr.Binding()) { D_ASSERT(expr.Depth() > 1); - expr.DepthMutable()--; - break; + return expr.WithDepth(expr.Depth() - 1); } } + return nullptr; } static void ReduceColumnDepth(CorrelatedColumns &columns, const CorrelatedColumns &affected_columns) { @@ -88,7 +89,10 @@ class ExpressionDepthReducerRecursive : public LogicalOperatorVisitor { void VisitExpression(unique_ptr *expression) override { auto &expr = **expression; if (expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - ReduceColumnRefDepth(expr.Cast(), correlated_columns); + auto reduced = ReduceColumnRefDepth(expr.Cast(), correlated_columns); + if (reduced) { + *expression = std::move(reduced); + } } else if (expr.GetExpressionType() == ExpressionType::SUBQUERY) { ReduceExpressionSubquery(expr.Cast(), correlated_columns); } @@ -107,9 +111,9 @@ class ExpressionDepthReducerRecursive : public LogicalOperatorVisitor { static void ReduceExpressionSubquery(BoundSubqueryExpression &expr, const CorrelatedColumns &correlated_columns) { ReduceColumnDepth(expr.GetBinder()->correlated_columns, correlated_columns); - if (expr.SubqueryMutable().plan) { + if (expr.Subquery().plan) { ExpressionDepthReducerRecursive recursive(correlated_columns); - recursive.VisitOperator(*expr.SubqueryMutable().plan); + recursive.VisitOperator(*expr.Subquery().plan); } } @@ -124,8 +128,7 @@ class ExpressionDepthReducer : public LogicalOperatorVisitor { protected: unique_ptr VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) override { - ReduceColumnRefDepth(expr, correlated_columns); - return nullptr; + return ReduceColumnRefDepth(expr, correlated_columns); } unique_ptr VisitReplace(BoundSubqueryExpression &expr, unique_ptr *expr_ptr) override { @@ -179,17 +182,17 @@ class LateralScopeInserter : public LogicalOperatorVisitor { if (!NeedsRebase(expr.Binding(), expr.Depth(), scope_depth)) { return nullptr; } - expr.DepthMutable()++; - AddCorrelation(correlated_columns, CorrelatedColumnInfo(expr)); - return nullptr; + auto rebased = expr.WithDepth(expr.Depth() + 1); + AddCorrelation(correlated_columns, CorrelatedColumnInfo(rebased->Cast())); + return rebased; } unique_ptr VisitReplace(BoundSubqueryExpression &expr, unique_ptr *expr_ptr) override { AdjustCorrelatedColumns(expr.GetBinder()->correlated_columns, scope_depth + 1); - if (expr.SubqueryMutable().plan) { - CollectLocalBindings(*expr.SubqueryMutable().plan); + if (expr.Subquery().plan) { + CollectLocalBindings(*expr.Subquery().plan); scope_depth++; - VisitOperator(*expr.SubqueryMutable().plan); + VisitOperator(*expr.Subquery().plan); scope_depth--; } return nullptr; diff --git a/src/duckdb/src/planner/expression_binder/order_binder.cpp b/src/duckdb/src/planner/expression_binder/order_binder.cpp index 96a91d42b..3d55e978b 100644 --- a/src/duckdb/src/planner/expression_binder/order_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/order_binder.cpp @@ -35,9 +35,7 @@ unique_ptr OrderBinder::CreateProjectionReference(ParsedExpression & alias = expr.GetAlias(); } } - auto result = make_uniq(Value::UBIGINT(index)); - result->SetAlias(std::move(alias)); - result->SetQueryLocation(expr.GetQueryLocation()); + auto result = make_uniq(Value::UBIGINT(index), std::move(alias), expr.GetQueryLocation()); return std::move(result); } @@ -131,9 +129,8 @@ unique_ptr OrderBinder::BindConstant(ParsedExpression &expr) { } child_list_t values; values.emplace_back(make_pair("index", Value::UBIGINT(index.GetIndex()))); - auto result = make_uniq(Value::STRUCT(std::move(values))); - result->SetAlias(expr.GetAlias()); - result->SetQueryLocation(expr.GetQueryLocation()); + auto result = + make_uniq(Value::STRUCT(std::move(values)), expr.GetAlias(), expr.GetQueryLocation()); return std::move(result); } diff --git a/src/duckdb/src/planner/expression_binder/projection_binder.cpp b/src/duckdb/src/planner/expression_binder/projection_binder.cpp index b0d349322..ff7ff44be 100644 --- a/src/duckdb/src/planner/expression_binder/projection_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/projection_binder.cpp @@ -26,8 +26,8 @@ BindResult ProjectionBinder::BindColumnRef(unique_ptr &expr_pt auto return_type = result.expression->GetReturnType(); auto alias = result.expression->GetName(); auto proj_col_idx = ColumnBinding::PushExpression(proj_expressions, std::move(result.expression)); - auto proj_ref = make_uniq(return_type, ColumnBinding(proj_index, proj_col_idx)); - proj_ref->SetAlias(std::move(alias)); + auto proj_ref = + make_uniq(std::move(alias), return_type, ColumnBinding(proj_index, proj_col_idx)); return BindResult(std::move(proj_ref)); } diff --git a/src/duckdb/src/planner/expression_iterator.cpp b/src/duckdb/src/planner/expression_iterator.cpp index 923c2980c..90da6f5ea 100644 --- a/src/duckdb/src/planner/expression_iterator.cpp +++ b/src/duckdb/src/planner/expression_iterator.cpp @@ -158,6 +158,29 @@ void ExpressionIterator::VisitExpressionClassMutable( *expr, [&](unique_ptr &child) { VisitExpressionClassMutable(child, expr_class, callback); }); } +unique_ptr ExpressionIterator::PreorderReplace(unique_ptr expr, + const ReplaceFunction &callback) { + auto replacement = callback(*expr); + if (replacement) { + return replacement; + } + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { child = PreorderReplace(std::move(child), callback); }); + return expr; +} + +unique_ptr ExpressionIterator::PreorderReplaceClass(unique_ptr expr, ExpressionClass expr_class, + const ReplaceFunction &callback) { + if (expr->GetExpressionClass() == expr_class) { + auto replacement = callback(*expr); + return replacement ? std::move(replacement) : std::move(expr); + } + ExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { + child = PreorderReplaceClass(std::move(child), expr_class, callback); + }); + return expr; +} + static void ReplaceExpressionInPlace(unique_ptr &expr, const Expression &target, const Expression &replacement) { if (expr->Equals(target)) { diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 6f6c1ac06..58557981b 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -60,8 +60,8 @@ ExpressionFilter &ExpressionFilter::GetExpressionFilter(TableFilter &filter, con } unique_ptr ExpressionFilter::CreateInExpression(unique_ptr column, vector values) { - auto result = make_uniq(ExpressionType::COMPARE_IN, LogicalType::BOOLEAN); - result->GetChildrenMutable().push_back(std::move(column)); + auto result = + make_uniq(ExpressionType::COMPARE_IN, LogicalType::BOOLEAN, std::move(column)); for (auto &value : values) { result->GetChildrenMutable().push_back(make_uniq(std::move(value))); } @@ -72,8 +72,7 @@ unique_ptr ExpressionFilter::CreateNullCheckExpression(unique_ptr(expression_type, LogicalType::BOOLEAN); - result->GetChildrenMutable().push_back(std::move(column)); + auto result = make_uniq(expression_type, LogicalType::BOOLEAN, std::move(column)); return std::move(result); } 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 4806e9393..2971c621e 100644 --- a/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp @@ -28,18 +28,20 @@ namespace duckdb { static constexpr idx_t MAX_NUM_SECTORS = (1ULL << 26); static constexpr idx_t MIN_NUM_BITS_PER_KEY = 12; static constexpr idx_t MIN_NUM_BITS = 512; -static constexpr idx_t LOG_SECTOR_SIZE = 6; // a sector is 64 bits, log2(64) = 6 -static constexpr idx_t SHIFT_MASK = 0x3F3F3F3F3F3F3F3F; // 6 bits for 64 positions -static constexpr idx_t N_BITS = 4; // the number of bits to set per hash +static constexpr idx_t LOG_SECTOR_SIZE = 6; // a sector is 64 bits, log2(64) = 6 +static constexpr idx_t N_BITS = 4; // the number of bits to set per hash static constexpr idx_t BITS_PER_SECTOR = 1ULL << LOG_SECTOR_SIZE; +static constexpr idx_t SECTOR_HASH_SHIFT = 32; //! A sector is one entry of the bit array, so the two have to agree on how wide it is static_assert(BITS_PER_SECTOR == sizeof(uint64_t) * 8, "a bloom filter sector must be exactly one array entry"); +static_assert(MAX_NUM_SECTORS <= (1ULL << SECTOR_HASH_SHIFT) && N_BITS * 8 <= SECTOR_HASH_SHIFT, + "sector and within-sector bits must use separate hash halves"); //! 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) { +void BloomFilter::Initialize(ClientContext &context_p, idx_t number_of_rows, idx_t max_bitmap_bytes) { // a published filter is shared with probe-side consumers and must stay immutable D_ASSERT(!published); BufferManager &buffer_manager = BufferManager::GetBufferManager(context_p); @@ -47,7 +49,7 @@ void BloomFilter::Initialize(ClientContext &context_p, idx_t number_of_rows) { // 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 = buffer_manager.GetMaxMemory() / MAX_MEMORY_FRACTION; + const idx_t budget_bytes = MinValue(buffer_manager.GetMaxMemory() / MAX_MEMORY_FRACTION, max_bitmap_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; @@ -143,14 +145,15 @@ idx_t BloomFilter::GetNumberOfSectors(idx_t number_of_rows) { return MinValue(NextPowerOfTwo(min_bits) >> LOG_SECTOR_SIZE, MAX_NUM_SECTORS); } -inline uint64_t GetMask(const hash_t hash) { - const uint64_t shifts = hash & SHIFT_MASK; - const auto shifts_8 = reinterpret_cast(&shifts); +static inline idx_t GetBloomSectorIndex(const hash_t hash, const uint64_t bitmask) { + // Align sector indexing with the high hash bits used for radix partitioning. + return (hash >> SECTOR_HASH_SHIFT) & bitmask; +} +inline uint64_t GetMask(const hash_t hash) { uint64_t mask = 0; - - for (idx_t bit_idx = 8 - N_BITS; bit_idx < 8; bit_idx++) { - const uint8_t bit_pos = shifts_8[bit_idx]; + for (idx_t bit_idx = 0; bit_idx < N_BITS; bit_idx++) { + const auto bit_pos = (hash >> (bit_idx * 8)) & (BITS_PER_SECTOR - 1); mask |= (1ULL << bit_pos); } @@ -192,7 +195,8 @@ idx_t BloomFilter::LookupHashes(const Vector &hashes_v, SelectionVector &result_ result_sel.set_index(found_count, i); found_count += LookupOne(hashes[i]); if (prefetch) { - PrefetchHashTableEntry(i, count, [&](idx_t next_idx) { return &bf[hashes[next_idx] & bitmask]; }); + PrefetchHashTableEntry(i, count, + [&](idx_t next_idx) { return &bf[GetBloomSectorIndex(hashes[next_idx], bitmask)]; }); } } return found_count; @@ -210,8 +214,9 @@ idx_t BloomFilter::LookupHashes(const Vector &hashes_v, const SelectionVector &s result_sel.set_index(found_count, i); found_count += LookupOne(hashes[sel.get_index_unsafe(i)]); if (prefetch) { - PrefetchHashTableEntry( - i, count, [&](idx_t next_idx) { return &bf[hashes[sel.get_index_unsafe(next_idx)] & bitmask]; }); + PrefetchHashTableEntry(i, count, [&](idx_t next_idx) { + return &bf[GetBloomSectorIndex(hashes[sel.get_index_unsafe(next_idx)], bitmask)]; + }); } } return found_count; @@ -220,7 +225,7 @@ idx_t BloomFilter::LookupHashes(const Vector &hashes_v, const SelectionVector &s inline void BloomFilter::InsertOne(const hash_t hash) { D_ASSERT(initialized); D_ASSERT(!sealed); - const uint64_t bf_offset = hash & bitmask; + const auto bf_offset = GetBloomSectorIndex(hash, bitmask); const uint64_t mask = GetMask(hash); atomic &slot = *reinterpret_cast *>(&bf[bf_offset]); @@ -234,7 +239,7 @@ inline void BloomFilter::InsertOne(const hash_t hash) { bool BloomFilter::LookupOne(const uint64_t hash) const { D_ASSERT(initialized); D_ASSERT(sealed); - const uint64_t bf_offset = hash & bitmask; + 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); 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 683345063..ff1d635a1 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 @@ -6,6 +6,7 @@ // //===----------------------------------------------------------------------===// +#include "duckdb/main/context.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/filter/table_filter_function_helpers.hpp" @@ -103,8 +104,8 @@ static unique_ptr SelectivityOptionalFilterDeserialize(Deserialize } struct SelectivityOptionalFilterLocalState : public FunctionLocalState { - SelectivityOptionalFilterLocalState(ClientContext &context, const Expression &child_filter_expr, - idx_t n_vectors_to_check, float selectivity_threshold) + SelectivityOptionalFilterLocalState(Context &context, const Expression &child_filter_expr, idx_t n_vectors_to_check, + float selectivity_threshold) : stats(n_vectors_to_check, selectivity_threshold), executor(context, child_filter_expr) { } diff --git a/src/duckdb/src/planner/joinside.cpp b/src/duckdb/src/planner/joinside.cpp index 85f297803..ab1868852 100644 --- a/src/duckdb/src/planner/joinside.cpp +++ b/src/duckdb/src/planner/joinside.cpp @@ -44,8 +44,8 @@ unique_ptr JoinCondition::CreateExpression(vector con if (!result) { result = std::move(expr); } else { - auto conj = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(expr), - std::move(result)); + auto conj = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(result), + std::move(expr)); result = std::move(conj); } } diff --git a/src/duckdb/src/planner/logical_operator_deep_copy.cpp b/src/duckdb/src/planner/logical_operator_deep_copy.cpp index 1a8aa50b5..01f8a8a34 100644 --- a/src/duckdb/src/planner/logical_operator_deep_copy.cpp +++ b/src/duckdb/src/planner/logical_operator_deep_copy.cpp @@ -10,7 +10,7 @@ LogicalOperatorDeepCopy::LogicalOperatorDeepCopy(Binder &binder, optional_ptr LogicalOperatorDeepCopy::DeepCopy(unique_ptr &op) { +unique_ptr LogicalOperatorDeepCopy::DeepCopy(const unique_ptr &op) { auto copy = op->Copy(binder.context); VisitOperator(*copy); TableBindingReplacer replacer(table_idx_replacements, parameter_data); @@ -281,7 +281,7 @@ void TableBindingReplacer::VisitExpression(unique_ptr *expression) { auto &bound_column_ref = expr->Cast(); auto entry = table_idx_replacements.find(bound_column_ref.Binding().table_index); if (entry != table_idx_replacements.end()) { - bound_column_ref.BindingMutable().table_index = entry->second; + expr = bound_column_ref.WithBinding(ColumnBinding(entry->second, bound_column_ref.Binding().column_index)); } } else if (expr->GetExpressionClass() == ExpressionClass::BOUND_PARAMETER) { // we have to replace the parameter data if it is a bound parameter diff --git a/src/duckdb/src/planner/logical_operator_repeatability.cpp b/src/duckdb/src/planner/logical_operator_repeatability.cpp index 0990ace8e..69e87a337 100644 --- a/src/duckdb/src/planner/logical_operator_repeatability.cpp +++ b/src/duckdb/src/planner/logical_operator_repeatability.cpp @@ -105,7 +105,6 @@ static LogicalOperatorRepeatability ClassifyOperatorType(LogicalOperator &op) { case LogicalOperatorType::LOGICAL_CREATE_TRIGGER: case LogicalOperatorType::LOGICAL_EXPLAIN: case LogicalOperatorType::LOGICAL_PREPARE: - case LogicalOperatorType::LOGICAL_EXECUTE: case LogicalOperatorType::LOGICAL_EXPORT: case LogicalOperatorType::LOGICAL_VACUUM: case LogicalOperatorType::LOGICAL_SET: diff --git a/src/duckdb/src/planner/operator/logical_create_table.cpp b/src/duckdb/src/planner/operator/logical_create_table.cpp index e67c3fa84..b64ef31b1 100644 --- a/src/duckdb/src/planner/operator/logical_create_table.cpp +++ b/src/duckdb/src/planner/operator/logical_create_table.cpp @@ -18,8 +18,18 @@ static SchemaCatalogEntry &ResolveCreateSchema(ClientContext &context, CreateInf LogicalCreateTable::LogicalCreateTable(ClientContext &context, unique_ptr unbound_info) : LogicalOperator(LogicalOperatorType::LOGICAL_CREATE_TABLE), schema(ResolveCreateSchema(context, *unbound_info)) { D_ASSERT(unbound_info->type == CatalogType::TABLE_ENTRY); + // the column types arrive bound, so binding them looks up no user types: keep the dependencies on those types + vector type_dependencies; + for (auto &dependency : unbound_info->dependencies.Set()) { + if (dependency.entry.type == CatalogType::TYPE_ENTRY) { + type_dependencies.push_back(dependency); + } + } auto binder = Binder::CreateBinder(context); info = binder->BindCreateTableInfo(unique_ptr_cast(std::move(unbound_info))); + for (auto &dependency : type_dependencies) { + info->Base().dependencies.AddDependency(dependency); + } } idx_t LogicalCreateTable::EstimateCardinality(ClientContext &context) { diff --git a/src/duckdb/src/planner/operator/logical_filter.cpp b/src/duckdb/src/planner/operator/logical_filter.cpp index cd434ac46..9de502ebb 100644 --- a/src/duckdb/src/planner/operator/logical_filter.cpp +++ b/src/duckdb/src/planner/operator/logical_filter.cpp @@ -29,7 +29,7 @@ bool LogicalFilter::SplitPredicates(vector> &expressions) auto &conjunction = expressions[i]->Cast(); found_conjunction = true; // AND expression, append the other children - for (idx_t k = 1; k < conjunction.GetChildrenMutable().size(); k++) { + for (idx_t k = 1; k < conjunction.GetChildren().size(); k++) { expressions.push_back(std::move(conjunction.GetChildrenMutable()[k])); } // replace this expression with the first child of the conjunction diff --git a/src/duckdb/src/planner/planner.cpp b/src/duckdb/src/planner/planner.cpp index 8ef4878ea..a8fbe9a1d 100644 --- a/src/duckdb/src/planner/planner.cpp +++ b/src/duckdb/src/planner/planner.cpp @@ -18,6 +18,7 @@ #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/main/attached_database.hpp" +#include "duckdb/parser/statement/execute_statement.hpp" #include "duckdb/parser/statement/multi_statement.hpp" #include "duckdb/planner/subquery/flatten_dependent_join.hpp" #include "duckdb/planner/subquery/recursive_dependent_join_planner.hpp" @@ -31,11 +32,12 @@ namespace duckdb { -Planner::Planner(ClientContext &context) : binder(Binder::CreateBinder(context)), context(context) { +Planner::Planner(ClientContext &context, PlanningMode mode) + : binder(Binder::CreateBinder(context)), context(context), mode(mode) { } static void RenderSQLExplain(unique_ptr &op, ClientContext &context, Binder &binder) { - if (op->type == LogicalOperatorType::LOGICAL_PREPARE || op->type == LogicalOperatorType::LOGICAL_EXECUTE) { + if (op->type == LogicalOperatorType::LOGICAL_PREPARE) { for (auto &child : op->children) { RenderSQLExplain(child, context, binder); } @@ -177,6 +179,39 @@ static bool VerifyPlannedExpressions(const LogicalOperator &plan) { } return true; } + +//! What the signature of a planned statement reads from its bind +struct BindSignatureState { + BindSignatureState(Binder &binder, BoundParameterMap ¶meters) + : properties(binder.GetStatementProperties()), rebind(parameters.rebind) { + for (auto &entry : parameters.GetParameters()) { + parameter_types.emplace(entry.first, entry.second->return_type); + } + } + + bool operator==(const BindSignatureState &other) const { + auto &modified = properties.modified_databases; + auto &other_modified = other.properties.modified_databases; + for (auto &entry : modified) { + auto match = other_modified.find(entry.first); + if (match == other_modified.end() || match->second.identity != entry.second.identity || + !match->second.modifications.Contains(entry.second.modifications) || + !entry.second.modifications.Contains(match->second.modifications)) { + return false; + } + } + return modified.size() == other_modified.size() && + properties.read_databases == other.properties.read_databases && + properties.requires_valid_transaction == other.properties.requires_valid_transaction && + properties.return_type == other.properties.return_type && + properties.always_require_rebind == other.properties.always_require_rebind && + parameter_types == other.parameter_types && rebind == other.rebind; + } + + StatementProperties properties; + identifier_map_t parameter_types; + bool rebind; +}; #endif static void RunPreBindExtensions(ClientContext &context, Binder &binder, SQLStatement &statement) { @@ -247,7 +282,11 @@ void Planner::CreatePlan(SQLStatement &statement) { throw; } } - if (this->plan) { + if (this->plan && mode == PlanningMode::FULL) { +#ifdef D_ASSERT_IS_ENABLED + // The bind only mode skips these passes, so they must not change what the signature reads + BindSignatureState bind_state(*binder, bound_parameters); +#endif auto max_tree_depth = Settings::Get(context); CheckTreeDepth(*plan, max_tree_depth); @@ -260,12 +299,15 @@ void Planner::CreatePlan(SQLStatement &statement) { D_ASSERT(!ContainsDependentJoin(*this->plan)); D_ASSERT(VerifyPlannedExpressions(*this->plan)); D_ASSERT(VerifyCanonicalComparisonJoins(*this->plan)); + D_ASSERT(BindSignatureState(*binder, bound_parameters) == bind_state); } this->properties = binder->GetStatementProperties(); this->properties.parameter_count = parameter_count; properties.bound_all_parameters = !bound_parameters.rebind && parameters_resolved; - Planner::VerifyPlan(context, plan, bound_parameters.GetParametersPtr()); + if (mode == PlanningMode::FULL) { + Planner::VerifyPlan(context, plan, bound_parameters.GetParametersPtr()); + } // set up a map of parameter number -> value entries for (auto &kv : bound_parameters.GetParameters()) { @@ -298,6 +340,29 @@ shared_ptr Planner::PrepareSQLStatement(unique_ptrResolveExecute(statement); + if (!execution.rebind && execution.prepared->physical_plan) { + auto &prepared = *execution.prepared; + prepared.Bind(context, execution.bind_values); + names = prepared.names; + types = prepared.types; + properties = prepared.properties; + properties.parameter_count = execution.parameter_count; + reused_statement = std::move(execution.prepared); + return; + } + // plan the prepared statement again + auto bound_statement = binder->BindExecute(execution); + RunPostBindExtensions(context, *binder, bound_statement); + names = std::move(bound_statement.names); + types = std::move(bound_statement.types); + plan = std::move(bound_statement.plan); + properties = binder->GetStatementProperties(); + properties.bound_all_parameters = true; +} + void Planner::CreatePlan(unique_ptr statement) { D_ASSERT(statement); Optimizer optimizer(*binder, context); @@ -323,7 +388,6 @@ void Planner::CreatePlan(unique_ptr statement) { case StatementType::LOAD_STATEMENT: case StatementType::EXTENSION_STATEMENT: case StatementType::PREPARE_STATEMENT: - case StatementType::EXECUTE_STATEMENT: case StatementType::LOGICAL_PLAN_STATEMENT: case StatementType::ATTACH_STATEMENT: case StatementType::DETACH_STATEMENT: @@ -335,6 +399,13 @@ void Planner::CreatePlan(unique_ptr statement) { case StatementType::EXTERNAL_RESOURCE_STATEMENT: CreatePlan(*statement); break; + case StatementType::EXECUTE_STATEMENT: + if (reuse_prepared_plans) { + CreateExecutePlan(statement->Cast()); + } else { + CreatePlan(*statement); + } + break; default: throw NotImplementedException("Cannot plan statement of type %s!", StatementTypeToString(statement->type)); } 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 1004ba711..0b2e7616b 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 @@ -370,11 +370,6 @@ BoundExpressionSQLExportResult BoundExpressionSQLExportState::ExportCast(const B path, "cast_type", "The cast type has no SQL type representation")}); } if (context.discard_optimizer_metadata && CMUtils::GetExpressionType(expression) == CMExpressionType::CAST) { - if (!BoundCastExpression::IsDefaultCast(expression)) { - return BoundExpressionSQLExportResult::Failure({BoundExpressionSQLExportState::UnsupportedFeature( - path, "compressed_materialization_cast", - "The compressed materialization projection contains a non-default cast")}); - } return ExportChild(*expression.GetChildren()[0], path, 0); } if (BoundCastExpression::IsDefaultCast(expression)) { 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 20e1ac134..8db44462d 100644 --- a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp +++ b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp @@ -25,6 +25,7 @@ #include "duckdb/planner/operator/list.hpp" #include +#include namespace duckdb { @@ -365,23 +366,23 @@ static bool RewriteFilterThroughProjections(unique_ptr &expr, const vector> &projections) { for (auto &projection : projections) { bool can_push = true; - ExpressionIterator::VisitExpressionMutable( - expr, [&](BoundColumnRefExpression &colref, unique_ptr &) { + expr = ExpressionIterator::PreorderReplace( + std::move(expr), [&](const BoundColumnRefExpression &colref) -> unique_ptr { if (colref.Depth() != 0) { can_push = false; - return; + return nullptr; } auto &projected = projection.get().GetExpression(colref.Binding()); if (projected.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { can_push = false; - return; + return nullptr; } auto &input = projected.Cast(); if (input.Depth() != 0) { can_push = false; - return; + return nullptr; } - colref.BindingMutable() = input.Binding(); + return colref.WithBinding(input.Binding()); }); if (!can_push) { return false; @@ -733,12 +734,14 @@ static bool NestedDelimJoinUsesAdditionalCorrelation(const LogicalOperator &op, return false; } -struct GeneratedDedupRef { +struct GeneratedDomainRef { optional_ptr cte_ref; + vector source_bindings; vector output_bindings; vector> output_expressions; vector> filters; bool has_projection = false; + bool has_selection = false; }; static bool IsEqualityComparison(ExpressionType comparison_type) { @@ -932,15 +935,6 @@ static bool AddExpressionReplacement(vector &bindings, vector &bindings, - const vector> &expressions) { - if (bindings.empty()) { - return; - } - ExpressionBindingReplacer replacer(bindings, expressions); - replacer.VisitOperator(op); -} - static void ReplaceOperatorBindings(LogicalOperator &op, const vector &bindings, const vector> &expressions, optional_ptr stop_operator) { @@ -951,36 +945,201 @@ static void ReplaceOperatorBindings(LogicalOperator &op, const vector> outputs; + vector> filters; + bool all_equality = true; + + // Each candidate is analyzed once; successful analysis consumes its copied filters. + bool Analyze(const vector &conditions, GeneratedDomainRef &domain, GeneratedDomainAction action) { + vector source_bindings; + vector> source_expressions; + vector covered_bindings; + vector> comparisons; + for (auto &condition : conditions) { + if (!condition.IsComparison()) { + return false; + } + all_equality &= IsEqualityJoinCondition(condition); + auto left_index = FindDomainOutput(condition.GetLHS(), domain); + auto right_index = FindDomainOutput(condition.GetRHS(), domain); + if (left_index.IsValid() == right_index.IsValid()) { + return false; + } + auto domain_index = left_index.IsValid() ? left_index.GetIndex() : right_index.GetIndex(); + 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) || + !bindings.TryAdd(ReplacementBinding(domain.output_bindings[domain_index], base_binding, + domain_expression.GetReturnType()))) { + return false; + } + ColumnBinding source_binding; + if (GetBoundColumnRefBinding(domain_expression, source_binding) && + FindBindingIndex(domain.source_bindings, source_binding).IsValid()) { + if (!AddExpressionReplacement(source_bindings, source_expressions, source_binding, + base_expression.Copy())) { + return false; + } + covered_bindings.push_back(source_binding); + } + comparisons.push_back(BoundComparisonExpression::Create( + condition.GetComparisonType(), condition.GetLHS().Copy(), condition.GetRHS().Copy())); + } + if (!CoversAllBindings(domain.source_bindings, covered_bindings)) { + return false; + } + for (auto &expression : domain.output_expressions) { + auto output = expression->Copy(); + ReplaceExpressionBindings(output, source_bindings, source_expressions); + if (ReferencesDomain(*output, domain) || output->IsVolatile()) { + return false; + } + outputs.push_back(std::move(output)); + } + for (auto &filter : domain.filters) { + ReplaceExpressionBindings(filter, source_bindings, source_expressions); + // Removing the domain evaluates its predicates on previously unrelated base rows. + if (ReferencesDomain(*filter, domain) || + (action == GeneratedDomainAction::REMOVE && (filter->CanThrow() || filter->IsVolatile()))) { + return false; + } + filters.push_back(std::move(filter)); + } + if (!all_equality) { + for (auto &condition : conditions) { + if (condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM || + condition.GetComparisonType() == ExpressionType::COMPARE_DISTINCT_FROM) { + continue; + } + auto &base_expression = + FindDomainOutput(condition.GetLHS(), domain).IsValid() ? condition.GetRHS() : condition.GetLHS(); + auto null_check = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, + LogicalType::BOOLEAN, base_expression.Copy()); + filters.push_back(std::move(null_check)); + } + return !domain.has_projection; + } + for (auto &comparison : comparisons) { + ReplaceExpressionBindings(comparison, domain.output_bindings, outputs); + ReplaceExpressionBindings(comparison, source_bindings, source_expressions); + if (ReferencesDomain(*comparison, domain) || + (action == GeneratedDomainAction::REMOVE && (comparison->CanThrow() || comparison->IsVolatile()))) { + return false; + } + if (IsTautologicalNotDistinctComparison(*comparison)) { + continue; + } + auto &function = comparison->Cast(); + auto &left = BoundComparisonExpression::Left(function); + auto &right = BoundComparisonExpression::Right(function); + if (comparison->GetExpressionType() == ExpressionType::COMPARE_EQUAL && + left.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && !left.GetReturnType().IsNested() && + left.Equals(right)) { + auto null_check = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, + LogicalType::BOOLEAN, left.Copy()); + comparison = std::move(null_check); + } + filters.push_back(std::move(comparison)); + } + return true; + } + + void Apply(Binder &binder, unique_ptr &op, idx_t base_side, const GeneratedDomainRef &domain, + GeneratedDomainAction action, LogicalOperator &root, BindingReplacementGraph &replacements) { + if (!op->HasProjectionMap()) { + ApplyUnprojected(op, base_side, domain, action, root, replacements); + return; + } + D_ASSERT(action == GeneratedDomainAction::REMOVE); + const auto replaces_root = &root == op.get(); + auto old_bindings = op->GetColumnBindings(); + // Preserve the published column order and width while substituting generated output expressions. + op = LogicalProjection::CreateIdentity(binder.GenerateTableIndex(), std::move(op)); + auto boundary_replacements = CreateConstructedBindingReplacements(old_bindings, op->GetColumnBindings()); + auto &join = op->children[0]->Cast(); + join.left_projection_map.clear(); + join.right_projection_map.clear(); + BindingReplacementGraph inner_replacements; + ApplyUnprojected(op->children[0], base_side, domain, action, *op, inner_replacements); + ColumnBindingReplacer replacer; + boundary_replacements.AddTo(replacer); + replacer.BuildIndex(); + replacer.stop_operator = op.get(); + replacer.VisitOperator(replaces_root ? *op : root); + replacements.Merge(boundary_replacements); + } + + void ApplyUnprojected(unique_ptr &op, idx_t base_side, const GeneratedDomainRef &domain, + GeneratedDomainAction action, LogicalOperator &root, BindingReplacementGraph &replacements) { + const auto replaces_root = &root == op.get(); + optional_ptr stop; + if (action == GeneratedDomainAction::REMOVE) { + op = std::move(op->children[base_side]); + for (auto &filter : filters) { + AddFilterToOperator(op, std::move(filter)); + } + } else { + auto &join = op->Cast(); + if (base_side == 1) { + std::swap(join.children[0], join.children[1]); + for (auto &condition : join.conditions) { + condition.Swap(); + } + } + join.join_type = JoinType::SEMI; + join.ResolveOperatorTypes(); + stop = op.get(); + } + ColumnBindingReplacer replacer; + bindings.AddTo(replacer); + replacer.BuildIndex(); + replacer.stop_operator = stop; + auto &replacement_root = replaces_root ? *op : root; + replacer.VisitOperator(replacement_root); + ReplaceOperatorBindings(replacement_root, domain.output_bindings, outputs, stop); + replacements.Merge(bindings); + MergeBindingExpressionReplacements(replacements, domain.output_bindings, outputs); + } +}; + class GeneratedDedupRefEliminator { public: - GeneratedDedupRefEliminator(ClientContext &context, unique_ptr &delim_join_op, - TableIndex dedup_cte_index, idx_t dedup_ref_count, LogicalOperator &rewrite_root, - bool preserve_evidence_side, bool preserve_nested_evidence_side); + GeneratedDedupRefEliminator(Binder &binder, unique_ptr &delim_join_op, TableIndex dedup_cte_index, + idx_t dedup_ref_count, LogicalOperator &rewrite_root, bool preserve_evidence_side, + bool preserve_nested_evidence_side); idx_t Remove(); private: - unique_ptr GetGeneratedDedupRef(LogicalOperator &op, bool collect_filters = false, - bool allow_projection = false) const; - bool ExpressionReferencesGeneratedDedupRef(const Expression &expr, const GeneratedDedupRef &dedup_ref) const; - bool CoversAllDedupColumns(const GeneratedDedupRef &dedup_ref, const vector &bindings) const; - optional_idx FindGeneratedOutputBinding(const Expression &expr, const GeneratedDedupRef &dedup_ref) const; - bool ExpressionReferencesGeneratedSide(const Expression &expr, const GeneratedDedupRef &dedup_ref) const; - bool FilterIsGeneratedDedupCrossProduct(LogicalOperator &op) const; + unique_ptr GetGeneratedDedupRef(LogicalOperator &op, bool collect_filters = false, + bool allow_projection = false) const; bool RewriteSubtree(unique_ptr &op, bool preserve_selected_domain, BindingReplacementGraph &replacements, bool under_aggregate = false, bool under_evidence_side = false); idx_t CountGeneratedDedupRefs(LogicalOperator &op) const; bool RemoveInequalityJoinConditions(LogicalOperator &target_op, const vector &join_conditions, idx_t dedup_idx); - bool PreserveJoinAsSemi(unique_ptr &join, BindingReplacementGraph &replacements); - bool PreserveFilterCrossProductAsSemi(unique_ptr &filter_op, - BindingReplacementGraph &replacements); - bool RemoveJoin(unique_ptr &join, BindingReplacementGraph &replacements); - bool RemoveFilterCrossProduct(unique_ptr &filter_op, BindingReplacementGraph &replacements); + bool RewriteJoin(unique_ptr &join, BindingReplacementGraph &replacements, + GeneratedDomainAction action); private: - ClientContext &context; + Binder &binder; unique_ptr &delim_join_op; LogicalComparisonJoin &delim_join; TableIndex dedup_cte_index; @@ -990,40 +1149,28 @@ class GeneratedDedupRefEliminator { bool preserve_nested_evidence_side; }; -GeneratedDedupRefEliminator::GeneratedDedupRefEliminator(ClientContext &context, - unique_ptr &delim_join_op, +GeneratedDedupRefEliminator::GeneratedDedupRefEliminator(Binder &binder, unique_ptr &delim_join_op, TableIndex dedup_cte_index, idx_t dedup_ref_count, LogicalOperator &rewrite_root, bool preserve_evidence_side, bool preserve_nested_evidence_side) - : context(context), delim_join_op(delim_join_op), delim_join(delim_join_op->Cast()), + : 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) { } -unique_ptr GeneratedDedupRefEliminator::GetGeneratedDedupRef(LogicalOperator &op, - bool collect_filters, - bool allow_projection) const { +static unique_ptr +ReadGeneratedDomainRef(LogicalOperator &op, + const std::function(LogicalCTERef &)> &resolve, + bool collect_filters, bool allow_projection) { if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cteref = op.Cast(); - if (cteref.cte_index == dedup_cte_index) { - auto result = make_uniq(); - result->cte_ref = cteref; - result->output_bindings = cteref.GetColumnBindings(); - result->output_expressions.reserve(result->output_bindings.size()); - for (idx_t col_idx = 0; col_idx < result->output_bindings.size(); col_idx++) { - result->output_expressions.push_back( - make_uniq(cteref.chunk_types[col_idx], result->output_bindings[col_idx])); - } - return result; - } - return nullptr; + return resolve(op.Cast()); } if (op.type == LogicalOperatorType::LOGICAL_FILTER) { auto &filter = op.Cast(); if (filter.HasProjectionMap() || filter.children.size() != 1) { return nullptr; } - auto result = GetGeneratedDedupRef(*filter.children[0], collect_filters, allow_projection); + auto result = ReadGeneratedDomainRef(*filter.children[0], resolve, collect_filters, allow_projection); if (!result) { return nullptr; } @@ -1041,7 +1188,7 @@ unique_ptr GeneratedDedupRefEliminator::GetGeneratedDedupRef( if (projection.children.size() != 1) { return nullptr; } - auto result = GetGeneratedDedupRef(*projection.children[0], collect_filters, allow_projection); + auto result = ReadGeneratedDomainRef(*projection.children[0], resolve, collect_filters, allow_projection); if (!result) { return nullptr; } @@ -1062,75 +1209,31 @@ unique_ptr GeneratedDedupRefEliminator::GetGeneratedDedupRef( return nullptr; } -bool GeneratedDedupRefEliminator::ExpressionReferencesGeneratedDedupRef(const Expression &expr, - const GeneratedDedupRef &dedup_ref) const { - bool found = false; - ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { - if (colref.Depth() == 0 && colref.Binding().table_index == dedup_ref.cte_ref->table_index) { - found = true; - } - }); - return found; -} - -bool GeneratedDedupRefEliminator::CoversAllDedupColumns(const GeneratedDedupRef &dedup_ref, - const vector &bindings) const { - auto cte_bindings = - LogicalOperator::GenerateColumnBindings(dedup_ref.cte_ref->table_index, dedup_ref.cte_ref->chunk_types.size()); - if (bindings.size() != cte_bindings.size()) { - return false; - } - for (auto &cte_binding : cte_bindings) { - idx_t match_count = 0; - for (auto &binding : bindings) { - if (binding == cte_binding) { - match_count++; - } - } - if (match_count != 1) { - return false; - } - } - return true; -} - -optional_idx GeneratedDedupRefEliminator::FindGeneratedOutputBinding(const Expression &expr, - const GeneratedDedupRef &dedup_ref) const { - ColumnBinding binding; - if (!GetBoundColumnRefBinding(expr, binding)) { - return optional_idx(); - } - return FindBindingIndex(dedup_ref.output_bindings, binding); -} - -bool GeneratedDedupRefEliminator::ExpressionReferencesGeneratedSide(const Expression &expr, - const GeneratedDedupRef &dedup_ref) const { - if (ExpressionReferencesGeneratedDedupRef(expr, dedup_ref)) { - return true; - } - bool found = false; - ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { - if (colref.Depth() != 0) { - return; +static unique_ptr GetGeneratedDedupRef(LogicalOperator &op, + const vector &dedup_cte_indexes, + bool collect_filters, bool allow_projection) { + auto resolve = [&](LogicalCTERef &cteref) -> unique_ptr { + if (std::find(dedup_cte_indexes.begin(), dedup_cte_indexes.end(), cteref.cte_index) == + dedup_cte_indexes.end()) { + return nullptr; } - if (FindBindingIndex(dedup_ref.output_bindings, colref.Binding()).IsValid()) { - found = true; + auto result = make_uniq(); + result->cte_ref = cteref; + result->output_bindings = cteref.GetColumnBindings(); + result->source_bindings = result->output_bindings; + for (idx_t column = 0; column < result->output_bindings.size(); column++) { + result->output_expressions.push_back( + make_uniq(cteref.chunk_types[column], result->output_bindings[column])); } - }); - return found; + return result; + }; + return ReadGeneratedDomainRef(op, resolve, collect_filters, allow_projection); } -bool GeneratedDedupRefEliminator::FilterIsGeneratedDedupCrossProduct(LogicalOperator &op) const { - if (op.type != LogicalOperatorType::LOGICAL_FILTER || op.HasProjectionMap()) { - return false; - } - auto &filter = op.Cast(); - if (filter.children.size() != 1 || filter.children[0]->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { - return false; - } - auto &cross_product = *filter.children[0]; - return cross_product.children.size() == 2 && - (GetGeneratedDedupRef(*cross_product.children[0]) || GetGeneratedDedupRef(*cross_product.children[1])); +unique_ptr GeneratedDedupRefEliminator::GetGeneratedDedupRef(LogicalOperator &op, + bool collect_filters, + bool allow_projection) const { + return duckdb::GetGeneratedDedupRef(op, {dedup_cte_index}, collect_filters, allow_projection); } bool GeneratedDedupRefEliminator::RewriteSubtree(unique_ptr &op, bool preserve_selected_domain, @@ -1157,26 +1260,12 @@ bool GeneratedDedupRefEliminator::RewriteSubtree(unique_ptr &op } } - bool filter_cross_product = false; - if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - (GetGeneratedDedupRef(*op->children[0], false, true) || GetGeneratedDedupRef(*op->children[1], false, true))) { - } else if (FilterIsGeneratedDedupCrossProduct(*op)) { - filter_cross_product = true; - } else { - return rewritten; - } - - bool local_rewrite; - BindingReplacementGraph local_replacements; + auto action = GeneratedDomainAction::REMOVE; if (preserve_selected_domain && (under_aggregate || under_evidence_side)) { - // This join is a semijoin reduction for a grouped RHS or an existence-check evidence side. Removing it is - // valid, but can turn a selective correlated subquery into a global aggregate or full evidence scan. - local_rewrite = filter_cross_product ? PreserveFilterCrossProductAsSemi(op, local_replacements) - : PreserveJoinAsSemi(op, local_replacements); - } else { - local_rewrite = filter_cross_product ? RemoveFilterCrossProduct(op, local_replacements) - : RemoveJoin(op, local_replacements); + action = GeneratedDomainAction::PRESERVE; } + BindingReplacementGraph local_replacements; + auto local_rewrite = RewriteJoin(op, local_replacements, action); if (local_rewrite) { replacements.Merge(local_replacements); } @@ -1222,7 +1311,7 @@ bool GeneratedDedupRefEliminator::RemoveInequalityJoinConditions(LogicalOperator return false; } } - NotNullExpressionAnalyzer nullability(context, rewrite_root); + NotNullExpressionAnalyzer nullability(binder.context, rewrite_root); vector traced_bindings; for (const auto &cond : delim_conditions) { @@ -1332,492 +1421,90 @@ bool GeneratedDedupRefEliminator::RemoveInequalityJoinConditions(LogicalOperator return true; } -bool GeneratedDedupRefEliminator::PreserveJoinAsSemi(unique_ptr &join, - BindingReplacementGraph &replacements) { - auto &comparison_join = join->Cast(); - if (comparison_join.join_type != JoinType::INNER && comparison_join.join_type != JoinType::SEMI) { +bool GeneratedDedupRefEliminator::RewriteJoin(unique_ptr &op, BindingReplacementGraph &replacements, + GeneratedDomainAction action) { + optional_ptr filter; + optional_ptr join_op = op.get(); + if (op->type == LogicalOperatorType::LOGICAL_FILTER && !op->HasProjectionMap() && op->children.size() == 1 && + op->children[0]->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + filter = op->Cast(); + join_op = op->children[0].get(); + } else if (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { return false; } - if (comparison_join.HasProjectionMap()) { + if (join_op->children.size() != 2 || (action == GeneratedDomainAction::PRESERVE && join_op->HasProjectionMap())) { return false; } - - auto left_is_generated = GetGeneratedDedupRef(*join->children[0], false, true) != nullptr; - auto right_is_generated = GetGeneratedDedupRef(*join->children[1], false, true) != nullptr; - if (left_is_generated == right_is_generated) { - return false; - } - const idx_t dedup_idx = left_is_generated ? 0 : 1; - if (comparison_join.join_type == JoinType::SEMI && dedup_idx == 0) { + auto left_domain = GetGeneratedDedupRef(*join_op->children[0], true, !filter); + auto right_domain = GetGeneratedDedupRef(*join_op->children[1], true, !filter); + if ((left_domain != nullptr) == (right_domain != nullptr)) { return false; } - - auto dedup_ref = GetGeneratedDedupRef(*join->children[dedup_idx], false, true); - if (!dedup_ref) { - return false; - } - - BindingReplacementGraph replacement_bindings; - vector covered_dedup_bindings; - covered_dedup_bindings.reserve(comparison_join.conditions.size()); - vector base_replacement_bindings; - vector> base_replacement_expressions; - vector semi_conditions; - semi_conditions.reserve(comparison_join.conditions.size()); - - for (auto &cond : comparison_join.conditions) { - if (!cond.IsComparison() || !IsEqualityJoinCondition(cond)) { - return false; - } - - auto lhs_generated_idx = FindGeneratedOutputBinding(cond.GetLHS(), *dedup_ref); - auto rhs_generated_idx = FindGeneratedOutputBinding(cond.GetRHS(), *dedup_ref); - if (lhs_generated_idx.IsValid() == rhs_generated_idx.IsValid()) { - return false; - } - auto generated_idx = lhs_generated_idx.IsValid() ? lhs_generated_idx.GetIndex() : rhs_generated_idx.GetIndex(); - auto &generated_binding = dedup_ref->output_bindings[generated_idx]; - auto &generated_expression = *dedup_ref->output_expressions[generated_idx]; - auto &other_side = lhs_generated_idx.IsValid() ? cond.GetRHS() : cond.GetLHS(); - - ColumnBinding other_binding; - if (!GetBoundColumnRefBinding(other_side, other_binding)) { - return false; - } - if (!replacement_bindings.TryAdd( - ReplacementBinding(generated_binding, other_binding, generated_expression.GetReturnType()))) { - return false; - } - - ColumnBinding base_binding; - if (GetBoundColumnRefBinding(generated_expression, base_binding) && - base_binding.table_index == dedup_ref->cte_ref->table_index) { - if (!replacement_bindings.TryAdd(ReplacementBinding(base_binding, other_binding))) { - return false; - } - covered_dedup_bindings.emplace_back(base_binding); - base_replacement_bindings.push_back(base_binding); - base_replacement_expressions.push_back(other_side.Copy()); - } - - auto generated_expr = lhs_generated_idx.IsValid() ? cond.GetLHS().Copy() : cond.GetRHS().Copy(); - auto other_expr = lhs_generated_idx.IsValid() ? cond.GetRHS().Copy() : cond.GetLHS().Copy(); - auto comparison_type = - lhs_generated_idx.IsValid() ? FlipComparisonExpression(cond.GetComparisonType()) : cond.GetComparisonType(); - semi_conditions.emplace_back(std::move(other_expr), std::move(generated_expr), comparison_type); - } - if (!CoversAllDedupColumns(*dedup_ref, covered_dedup_bindings)) { - return false; - } - - vector> generated_output_replacements; - generated_output_replacements.reserve(dedup_ref->output_expressions.size()); - for (auto &expr : dedup_ref->output_expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesGeneratedSide(*rewritten_expr, *dedup_ref)) { - return false; - } - generated_output_replacements.push_back(std::move(rewritten_expr)); - } - - if (dedup_idx == 0) { - std::swap(comparison_join.children[0], comparison_join.children[1]); - } - comparison_join.join_type = JoinType::SEMI; - comparison_join.conditions = std::move(semi_conditions); - comparison_join.left_projection_map.clear(); - comparison_join.right_projection_map.clear(); - comparison_join.ResolveOperatorTypes(); - - ColumnBindingReplacer replacer; - replacement_bindings.AddTo(replacer); - replacer.BuildIndex(); - replacer.stop_operator = join.get(); - replacer.VisitOperator(rewrite_root); - ReplaceOperatorBindings(rewrite_root, dedup_ref->output_bindings, generated_output_replacements, join.get()); - replacements.Merge(replacement_bindings); - MergeBindingExpressionReplacements(replacements, dedup_ref->output_bindings, generated_output_replacements); - return true; -} - -bool GeneratedDedupRefEliminator::PreserveFilterCrossProductAsSemi(unique_ptr &filter_op, - BindingReplacementGraph &replacements) { - auto &filter = filter_op->Cast(); - if (filter.HasProjectionMap() || filter.children.size() != 1 || - filter.children[0]->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { - return false; - } - auto &cross_product = *filter.children[0]; - if (cross_product.children.size() != 2) { - return false; - } - - const idx_t dedup_idx = GetGeneratedDedupRef(*cross_product.children[0], false, true) ? 0 : 1; - auto dedup_ref = GetGeneratedDedupRef(*cross_product.children[dedup_idx], false, true); - if (!dedup_ref) { - return false; - } - - filter.SplitPredicates(); - vector consumed(filter.expressions.size(), false); - vector covered_dedup_bindings; - covered_dedup_bindings.reserve(dedup_ref->output_bindings.size()); - vector base_replacement_bindings; - vector> base_replacement_expressions; - vector semi_conditions; - BindingReplacementGraph replacement_bindings; - - for (idx_t expr_idx = 0; expr_idx < filter.expressions.size(); expr_idx++) { - auto &expr = *filter.expressions[expr_idx]; - if (!BoundComparisonExpression::IsComparison(expr) || !IsEqualityComparison(expr.GetExpressionType())) { - continue; - } - auto &comparison = expr.Cast(); - auto &lhs = BoundComparisonExpression::Left(comparison); - auto &rhs = BoundComparisonExpression::Right(comparison); - - auto lhs_generated_idx = FindGeneratedOutputBinding(lhs, *dedup_ref); - auto rhs_generated_idx = FindGeneratedOutputBinding(rhs, *dedup_ref); - if (lhs_generated_idx.IsValid() == rhs_generated_idx.IsValid()) { - continue; - } - - auto generated_idx = lhs_generated_idx.IsValid() ? lhs_generated_idx.GetIndex() : rhs_generated_idx.GetIndex(); - auto &generated_binding = dedup_ref->output_bindings[generated_idx]; - auto &generated_expression = *dedup_ref->output_expressions[generated_idx]; - auto &other_side = lhs_generated_idx.IsValid() ? rhs : lhs; - - ColumnBinding other_binding; - if (!GetBoundColumnRefBinding(other_side, other_binding)) { - return false; - } - if (!replacement_bindings.TryAdd( - ReplacementBinding(generated_binding, other_binding, generated_expression.GetReturnType()))) { - return false; - } - - ColumnBinding base_binding; - if (GetBoundColumnRefBinding(generated_expression, base_binding) && - base_binding.table_index == dedup_ref->cte_ref->table_index) { - if (!replacement_bindings.TryAdd(ReplacementBinding(base_binding, other_binding))) { - return false; + const idx_t domain_side = left_domain ? 0 : 1; + auto domain = left_domain ? std::move(left_domain) : std::move(right_domain); + vector conditions; + vector consumed; + 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]; + if (!BoundComparisonExpression::IsComparison(expression)) { + continue; } - covered_dedup_bindings.emplace_back(base_binding); - base_replacement_bindings.push_back(base_binding); - base_replacement_expressions.push_back(other_side.Copy()); - } - - auto generated_expr = lhs_generated_idx.IsValid() ? lhs.Copy() : rhs.Copy(); - auto other_expr = lhs_generated_idx.IsValid() ? rhs.Copy() : lhs.Copy(); - auto comparison_type = - lhs_generated_idx.IsValid() ? FlipComparisonExpression(expr.GetExpressionType()) : expr.GetExpressionType(); - semi_conditions.emplace_back(std::move(other_expr), std::move(generated_expr), comparison_type); - consumed[expr_idx] = true; - } - - if (semi_conditions.empty() || !CoversAllDedupColumns(*dedup_ref, covered_dedup_bindings)) { - return false; - } - for (idx_t expr_idx = 0; expr_idx < filter.expressions.size(); expr_idx++) { - if (!consumed[expr_idx] && ExpressionReferencesGeneratedSide(*filter.expressions[expr_idx], *dedup_ref)) { - return false; - } - } - - vector> generated_output_replacements; - generated_output_replacements.reserve(dedup_ref->output_expressions.size()); - for (auto &expr : dedup_ref->output_expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesGeneratedSide(*rewritten_expr, *dedup_ref)) { - return false; - } - generated_output_replacements.push_back(std::move(rewritten_expr)); - } - - auto semi_join = make_uniq(JoinType::SEMI); - semi_join->conditions = std::move(semi_conditions); - semi_join->children.push_back(std::move(cross_product.children[1 - dedup_idx])); - semi_join->children.push_back(std::move(cross_product.children[dedup_idx])); - semi_join->ResolveOperatorTypes(); - - unique_ptr replacement_op = std::move(semi_join); - for (idx_t expr_idx = 0; expr_idx < filter.expressions.size(); expr_idx++) { - if (consumed[expr_idx]) { - continue; - } - AddFilterToOperator(replacement_op, std::move(filter.expressions[expr_idx])); - } - - filter_op = std::move(replacement_op); - ColumnBindingReplacer replacer; - replacement_bindings.AddTo(replacer); - replacer.BuildIndex(); - replacer.stop_operator = filter_op.get(); - replacer.VisitOperator(rewrite_root); - ReplaceOperatorBindings(rewrite_root, dedup_ref->output_bindings, generated_output_replacements, filter_op.get()); - replacements.Merge(replacement_bindings); - MergeBindingExpressionReplacements(replacements, dedup_ref->output_bindings, generated_output_replacements); - return true; -} - -bool GeneratedDedupRefEliminator::RemoveJoin(unique_ptr &join, BindingReplacementGraph &replacements) { - auto &comparison_join = join->Cast(); - if (comparison_join.join_type != JoinType::INNER && comparison_join.join_type != JoinType::SEMI) { - return false; - } - - auto left_is_generated = GetGeneratedDedupRef(*join->children[0], false, true) != nullptr; - auto right_is_generated = GetGeneratedDedupRef(*join->children[1], false, true) != nullptr; - if (left_is_generated == right_is_generated) { - return false; - } - const idx_t dedup_idx = left_is_generated ? 0 : 1; - - auto dedup_ref = GetGeneratedDedupRef(*join->children[dedup_idx], true, true); - if (!dedup_ref) { - return false; - } - - BindingReplacementGraph replacement_bindings; - bool all_equality_conditions = true; - vector covered_dedup_bindings; - covered_dedup_bindings.reserve(comparison_join.conditions.size()); - vector base_replacement_bindings; - vector> base_replacement_expressions; - vector> join_filter_expressions; - vector> not_null_filter_expressions; - - for (auto &cond : comparison_join.conditions) { - if (!cond.IsComparison()) { - return false; - } - all_equality_conditions = all_equality_conditions && IsEqualityJoinCondition(cond); - - auto lhs_generated_idx = FindGeneratedOutputBinding(cond.GetLHS(), *dedup_ref); - auto rhs_generated_idx = FindGeneratedOutputBinding(cond.GetRHS(), *dedup_ref); - if (lhs_generated_idx.IsValid() == rhs_generated_idx.IsValid()) { - return false; - } - auto generated_idx = lhs_generated_idx.IsValid() ? lhs_generated_idx.GetIndex() : rhs_generated_idx.GetIndex(); - auto &generated_binding = dedup_ref->output_bindings[generated_idx]; - auto &generated_expression = *dedup_ref->output_expressions[generated_idx]; - auto &other_side = lhs_generated_idx.IsValid() ? cond.GetRHS() : cond.GetLHS(); - - ColumnBinding other_binding; - if (!GetBoundColumnRefBinding(other_side, other_binding)) { - return false; - } - if (!replacement_bindings.TryAdd( - ReplacementBinding(generated_binding, other_binding, generated_expression.GetReturnType()))) { - return false; - } - - ColumnBinding base_binding; - if (GetBoundColumnRefBinding(generated_expression, base_binding) && - base_binding.table_index == dedup_ref->cte_ref->table_index) { - if (!replacement_bindings.TryAdd(ReplacementBinding(base_binding, other_binding))) { - return false; + auto &comparison = expression.Cast(); + auto &left = BoundComparisonExpression::Left(comparison); + auto &right = BoundComparisonExpression::Right(comparison); + if (FindDomainOutput(left, *domain).IsValid() == FindDomainOutput(right, *domain).IsValid()) { + continue; } - covered_dedup_bindings.emplace_back(base_binding); - base_replacement_bindings.push_back(base_binding); - base_replacement_expressions.push_back(other_side.Copy()); - } - - join_filter_expressions.push_back( - BoundComparisonExpression::Create(cond.GetComparisonType(), cond.GetLHS().Copy(), cond.GetRHS().Copy())); - if (cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM && - cond.GetComparisonType() != ExpressionType::COMPARE_DISTINCT_FROM) { - auto is_not_null_expr = - make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - is_not_null_expr->GetChildrenMutable().push_back(other_side.Copy()); - not_null_filter_expressions.push_back(std::move(is_not_null_expr)); - } - } - if (!CoversAllDedupColumns(*dedup_ref, covered_dedup_bindings)) { - return false; - } - - vector> generated_output_replacements; - generated_output_replacements.reserve(dedup_ref->output_expressions.size()); - for (auto &expr : dedup_ref->output_expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesGeneratedSide(*rewritten_expr, *dedup_ref)) { - return false; - } - generated_output_replacements.push_back(std::move(rewritten_expr)); - } - - vector> filter_expressions; - if (all_equality_conditions) { - for (auto &expr : dedup_ref->filters) { - ReplaceExpressionBindings(expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesGeneratedSide(*expr, *dedup_ref)) { - return false; + conditions.emplace_back(left.Copy(), right.Copy(), expression.GetExpressionType()); + if (FindDomainOutput(left, *domain).IsValid() != (domain_side == 0)) { + conditions.back().Swap(); } - filter_expressions.push_back(std::move(expr)); + consumed[index] = true; } - for (auto &expr : join_filter_expressions) { - ReplaceExpressionBindings(expr, dedup_ref->output_bindings, generated_output_replacements); - ReplaceExpressionBindings(expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesGeneratedSide(*expr, *dedup_ref)) { + for (idx_t index = 0; index < consumed.size(); index++) { + if (!consumed[index] && ReferencesDomain(*filter->expressions[index], *domain)) { return false; } - if (IsTautologicalNotDistinctComparison(*expr)) { - continue; - } - filter_expressions.push_back(std::move(expr)); } } else { - if (dedup_ref->has_projection || - !RemoveInequalityJoinConditions(*join, comparison_join.conditions, dedup_idx)) { + auto &join = join_op->Cast(); + if (join.join_type != JoinType::INNER && (join.join_type != JoinType::SEMI || domain_side != 1)) { return false; } - filter_expressions = std::move(dedup_ref->filters); - for (auto &expr : not_null_filter_expressions) { - filter_expressions.push_back(std::move(expr)); + for (auto &condition : join.conditions) { + conditions.push_back(condition.Copy()); } } - - unique_ptr replacement_op = std::move(comparison_join.children[1 - dedup_idx]); - if (!filter_expressions.empty()) { - auto new_filter = make_uniq(); - new_filter->expressions = std::move(filter_expressions); - new_filter->children.emplace_back(std::move(replacement_op)); - replacement_op = std::move(new_filter); - } - - join = std::move(replacement_op); - - ColumnBindingReplacer replacer; - replacement_bindings.AddTo(replacer); - replacer.BuildIndex(); - replacer.VisitOperator(rewrite_root); - ReplaceOperatorBindings(rewrite_root, dedup_ref->output_bindings, generated_output_replacements); - replacements.Merge(replacement_bindings); - MergeBindingExpressionReplacements(replacements, dedup_ref->output_bindings, generated_output_replacements); - return true; -} - -bool GeneratedDedupRefEliminator::RemoveFilterCrossProduct(unique_ptr &filter_op, - BindingReplacementGraph &replacements) { - auto &filter = filter_op->Cast(); - D_ASSERT(filter.children.size() == 1); - auto &cross_product = *filter.children[0]; - D_ASSERT(cross_product.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT); - - const idx_t dedup_idx = GetGeneratedDedupRef(*cross_product.children[0]) ? 0 : 1; - auto dedup_ref = GetGeneratedDedupRef(*cross_product.children[dedup_idx], true); - if (!dedup_ref) { + GeneratedDomainReplacement replacement; + if (!replacement.Analyze(conditions, *domain, action)) { return false; } - - vector> generated_filter_expressions = std::move(dedup_ref->filters); - - filter.SplitPredicates(); - vector consumed(filter.expressions.size(), false); - vector join_conditions; - BindingReplacementGraph replacement_bindings; - bool all_equality_conditions = true; - vector covered_dedup_bindings; - - for (idx_t expr_idx = 0; expr_idx < filter.expressions.size(); expr_idx++) { - auto &expr = *filter.expressions[expr_idx]; - if (!BoundComparisonExpression::IsComparison(expr)) { - continue; - } - auto &comparison = expr.Cast(); - auto &lhs = BoundComparisonExpression::Left(comparison); - auto &rhs = BoundComparisonExpression::Right(comparison); - if (lhs.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || - rhs.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - continue; - } - - auto &lhs_colref = lhs.Cast(); - auto &rhs_colref = rhs.Cast(); - auto lhs_dedup = lhs_colref.Binding().table_index == dedup_ref->cte_ref->table_index; - auto rhs_dedup = rhs_colref.Binding().table_index == dedup_ref->cte_ref->table_index; - if (lhs_dedup == rhs_dedup) { - continue; - } - - auto comparison_type = expr.GetExpressionType(); - if (lhs_dedup) { - if (!replacement_bindings.TryAdd(ReplacementBinding(lhs_colref.Binding(), rhs_colref.Binding()))) { - return false; - } - covered_dedup_bindings.emplace_back(lhs_colref.Binding()); - if (dedup_idx == 0) { - join_conditions.emplace_back(lhs.Copy(), rhs.Copy(), comparison_type); - } else { - join_conditions.emplace_back(rhs.Copy(), lhs.Copy(), FlipComparisonExpression(comparison_type)); - } - if (comparison_type != ExpressionType::COMPARE_NOT_DISTINCT_FROM && - comparison_type != ExpressionType::COMPARE_DISTINCT_FROM) { - auto is_not_null_expr = - make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - is_not_null_expr->GetChildrenMutable().push_back(rhs.Copy()); - generated_filter_expressions.push_back(std::move(is_not_null_expr)); - } - } else { - if (!replacement_bindings.TryAdd(ReplacementBinding(rhs_colref.Binding(), lhs_colref.Binding()))) { - return false; - } - covered_dedup_bindings.emplace_back(rhs_colref.Binding()); - if (dedup_idx == 0) { - join_conditions.emplace_back(rhs.Copy(), lhs.Copy(), FlipComparisonExpression(comparison_type)); - } else { - join_conditions.emplace_back(lhs.Copy(), rhs.Copy(), comparison_type); - } - if (comparison_type != ExpressionType::COMPARE_NOT_DISTINCT_FROM && - comparison_type != ExpressionType::COMPARE_DISTINCT_FROM) { - auto is_not_null_expr = - make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN); - is_not_null_expr->GetChildrenMutable().push_back(lhs.Copy()); - generated_filter_expressions.push_back(std::move(is_not_null_expr)); - } - } - all_equality_conditions = all_equality_conditions && IsEqualityJoinCondition(join_conditions.back()); - consumed[expr_idx] = true; - } - - if (join_conditions.size() != dedup_ref->cte_ref->chunk_types.size() || - !CoversAllDedupColumns(*dedup_ref, covered_dedup_bindings)) { + if (!replacement.all_equality && + (action != GeneratedDomainAction::REMOVE || !RemoveInequalityJoinConditions(*op, conditions, domain_side))) { return false; } - for (idx_t expr_idx = 0; expr_idx < filter.expressions.size(); expr_idx++) { - if (!consumed[expr_idx] && ExpressionReferencesGeneratedDedupRef(*filter.expressions[expr_idx], *dedup_ref)) { - return false; + if (filter) { + auto join = make_uniq(JoinType::INNER); + join->conditions = std::move(conditions); + join->children = std::move(join_op->children); + vector> remaining; + for (idx_t index = 0; index < consumed.size(); index++) { + if (!consumed[index]) { + remaining.push_back(std::move(filter->expressions[index])); + } } - } - - if (!all_equality_conditions && !RemoveInequalityJoinConditions(*filter_op, join_conditions, dedup_idx)) { - return false; - } - - unique_ptr replacement_op = std::move(cross_product.children[1 - dedup_idx]); - for (idx_t expr_idx = 0; expr_idx < filter.expressions.size(); expr_idx++) { - if (!consumed[expr_idx]) { - generated_filter_expressions.push_back(std::move(filter.expressions[expr_idx])); + // Restore the complete tree before applying binding replacements to its ancestors. + op = std::move(join); + replacement.Apply(binder, op, 1 - domain_side, *domain, action, rewrite_root, replacements); + for (auto &expression : remaining) { + AddFilterToOperator(op, std::move(expression)); } + } else { + replacement.Apply(binder, op, 1 - domain_side, *domain, action, rewrite_root, replacements); } - if (!generated_filter_expressions.empty()) { - auto new_filter = make_uniq(); - new_filter->expressions = std::move(generated_filter_expressions); - new_filter->children.emplace_back(std::move(replacement_op)); - replacement_op = std::move(new_filter); - } - - filter_op = std::move(replacement_op); - - ColumnBindingReplacer replacer; - replacement_bindings.AddTo(replacer); - replacer.BuildIndex(); - replacer.VisitOperator(rewrite_root); - replacements.Merge(replacement_bindings); return true; } @@ -1839,18 +1526,9 @@ idx_t GeneratedDedupRefEliminator::Remove() { return dedup_ref_count; } -struct GeneratedDomainRef { - optional_ptr cte_ref; - vector source_bindings; - vector output_bindings; - vector> output_expressions; - vector> filters; - bool has_selection = false; -}; - class GeneratedDomainJoinEliminator { public: - GeneratedDomainJoinEliminator(unique_ptr &rewrite_root, + GeneratedDomainJoinEliminator(Binder &binder, unique_ptr &rewrite_root, const vector &generated_dedup_cte_indexes, const set &preserve_marker_indexes); @@ -1863,16 +1541,13 @@ class GeneratedDomainJoinEliminator { bool under_aggregate = false, bool under_evidence_side = false, bool negated_marker_filter_above = false); - unique_ptr GetGeneratedDedupRef(LogicalOperator &op, bool collect_filters = false, - bool allow_projection = false) const; - unique_ptr GetGeneratedDomainDefinition(LogicalOperator &op) const; - unique_ptr GetGeneratedDomainRef(LogicalOperator &op, bool collect_filters = false, - bool allow_projection = false) const; + unique_ptr GetGeneratedDedupRef(LogicalOperator &op, bool collect_filters = false, + bool allow_projection = false) const; + unique_ptr GetGeneratedDomainRef(LogicalOperator &op) const; bool CTEHasSelection(TableIndex cte_index, vector &seen_ctes) const; bool OperatorHasSelection(LogicalOperator &op, vector &seen_ctes) const; - bool GeneratedDedupRefHasSelection(const GeneratedDedupRef &dedup_ref) const; + bool GeneratedDedupRefHasSelection(const GeneratedDomainRef &dedup_ref) const; - optional_idx FindOutputBinding(Expression &expr, const vector &bindings) const; bool ContainsRecursiveCTERef(LogicalOperator &op) const; bool RemoveGeneratedDedupJoin(unique_ptr &join, BindingReplacementGraph &replacements, @@ -1881,16 +1556,17 @@ class GeneratedDomainJoinEliminator { bool under_aggregate, bool under_evidence_side); private: + Binder &binder; unique_ptr &rewrite_root; const vector &generated_dedup_cte_indexes; const set &preserve_marker_indexes; vector> ctes; }; -GeneratedDomainJoinEliminator::GeneratedDomainJoinEliminator(unique_ptr &rewrite_root, +GeneratedDomainJoinEliminator::GeneratedDomainJoinEliminator(Binder &binder, unique_ptr &rewrite_root, const vector &generated_dedup_cte_indexes, const set &preserve_marker_indexes) - : rewrite_root(rewrite_root), generated_dedup_cte_indexes(generated_dedup_cte_indexes), + : binder(binder), rewrite_root(rewrite_root), generated_dedup_cte_indexes(generated_dedup_cte_indexes), preserve_marker_indexes(preserve_marker_indexes) { } @@ -1940,7 +1616,7 @@ bool GeneratedDomainJoinEliminator::OperatorHasSelection(LogicalOperator &op, ve return false; } -bool GeneratedDomainJoinEliminator::GeneratedDedupRefHasSelection(const GeneratedDedupRef &dedup_ref) const { +bool GeneratedDomainJoinEliminator::GeneratedDedupRefHasSelection(const GeneratedDomainRef &dedup_ref) const { if (!dedup_ref.cte_ref) { return false; } @@ -1948,134 +1624,14 @@ bool GeneratedDomainJoinEliminator::GeneratedDedupRefHasSelection(const Generate return CTEHasSelection(dedup_ref.cte_ref->cte_index, seen_ctes); } -unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDedupRef(LogicalOperator &op, - bool collect_filters, - bool allow_projection) const { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cteref = op.Cast(); - if (std::find(generated_dedup_cte_indexes.begin(), generated_dedup_cte_indexes.end(), cteref.cte_index) == - generated_dedup_cte_indexes.end()) { - return nullptr; - } - - auto result = make_uniq(); - result->cte_ref = cteref; - result->output_bindings = cteref.GetColumnBindings(); - result->output_expressions.reserve(result->output_bindings.size()); - for (idx_t col_idx = 0; col_idx < result->output_bindings.size(); col_idx++) { - result->output_expressions.push_back( - make_uniq(cteref.chunk_types[col_idx], result->output_bindings[col_idx])); - } - return result; - } - if (op.type == LogicalOperatorType::LOGICAL_FILTER) { - auto &filter = op.Cast(); - if (filter.HasProjectionMap() || filter.children.size() != 1) { - return nullptr; - } - auto result = GetGeneratedDedupRef(*filter.children[0], collect_filters, allow_projection); - if (!result) { - return nullptr; - } - if (collect_filters) { - for (auto &expr : filter.expressions) { - auto filter_expr = expr->Copy(); - ReplaceExpressionBindings(filter_expr, result->output_bindings, result->output_expressions); - result->filters.push_back(std::move(filter_expr)); - } - } - return result; - } - if (allow_projection && op.type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto &projection = op.Cast(); - if (projection.children.size() != 1) { - return nullptr; - } - auto result = GetGeneratedDedupRef(*projection.children[0], collect_filters, allow_projection); - if (!result) { - return nullptr; - } - - auto child_bindings = result->output_bindings; - auto child_expressions = std::move(result->output_expressions); - result->output_bindings = projection.GetColumnBindings(); - result->output_expressions.clear(); - result->output_expressions.reserve(projection.expressions.size()); - for (auto &expr : projection.expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, child_bindings, child_expressions); - result->output_expressions.push_back(std::move(rewritten_expr)); - } - result->has_projection = true; - return result; - } - return nullptr; +unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDedupRef(LogicalOperator &op, + bool collect_filters, + bool allow_projection) const { + return duckdb::GetGeneratedDedupRef(op, generated_dedup_cte_indexes, collect_filters, allow_projection); } -unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDomainDefinition(LogicalOperator &op) const { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cteref = op.Cast(); - if (std::find(generated_dedup_cte_indexes.begin(), generated_dedup_cte_indexes.end(), cteref.cte_index) == - generated_dedup_cte_indexes.end()) { - return nullptr; - } - - auto result = make_uniq(); - result->source_bindings = cteref.GetColumnBindings(); - result->output_bindings = result->source_bindings; - result->output_expressions.reserve(result->output_bindings.size()); - for (idx_t col_idx = 0; col_idx < result->output_bindings.size(); col_idx++) { - result->output_expressions.push_back( - make_uniq(cteref.chunk_types[col_idx], result->output_bindings[col_idx])); - } - return result; - } - if (op.type == LogicalOperatorType::LOGICAL_FILTER) { - auto &filter = op.Cast(); - if (filter.HasProjectionMap() || filter.children.size() != 1) { - return nullptr; - } - auto result = GetGeneratedDomainDefinition(*filter.children[0]); - if (!result) { - return nullptr; - } - for (auto &expr : filter.expressions) { - auto filter_expr = expr->Copy(); - ReplaceExpressionBindings(filter_expr, result->output_bindings, result->output_expressions); - result->filters.push_back(std::move(filter_expr)); - } - return result; - } - if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto &projection = op.Cast(); - if (projection.children.size() != 1) { - return nullptr; - } - auto result = GetGeneratedDomainDefinition(*projection.children[0]); - if (!result) { - return nullptr; - } - - auto child_bindings = result->output_bindings; - auto child_expressions = std::move(result->output_expressions); - result->output_bindings = projection.GetColumnBindings(); - result->output_expressions.clear(); - result->output_expressions.reserve(projection.expressions.size()); - for (auto &expr : projection.expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, child_bindings, child_expressions); - result->output_expressions.push_back(std::move(rewritten_expr)); - } - return result; - } - return nullptr; -} - -unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDomainRef(LogicalOperator &op, - bool collect_filters, - bool allow_projection) const { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cteref = op.Cast(); +unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDomainRef(LogicalOperator &op) const { + auto resolve = [&](LogicalCTERef &cteref) -> unique_ptr { if (std::find(generated_dedup_cte_indexes.begin(), generated_dedup_cte_indexes.end(), cteref.cte_index) != generated_dedup_cte_indexes.end()) { return nullptr; @@ -2088,7 +1644,7 @@ unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDomain if (cte->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { return nullptr; } - auto result = GetGeneratedDomainDefinition(*cte->children[0]); + auto result = GetGeneratedDedupRef(*cte->children[0], true, true); if (!result || result->output_expressions.size() != cteref.chunk_types.size()) { return nullptr; } @@ -2098,57 +1654,8 @@ unique_ptr GeneratedDomainJoinEliminator::GetGeneratedDomain vector seen_ctes; result->has_selection = CTEHasSelection(cteref.cte_index, seen_ctes); return result; - } - if (op.type == LogicalOperatorType::LOGICAL_FILTER) { - auto &filter = op.Cast(); - if (filter.HasProjectionMap() || filter.children.size() != 1) { - return nullptr; - } - auto result = GetGeneratedDomainRef(*filter.children[0], collect_filters, allow_projection); - if (!result) { - return nullptr; - } - if (collect_filters) { - for (auto &expr : filter.expressions) { - auto filter_expr = expr->Copy(); - ReplaceExpressionBindings(filter_expr, result->output_bindings, result->output_expressions); - result->filters.push_back(std::move(filter_expr)); - } - } - return result; - } - if (allow_projection && op.type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto &projection = op.Cast(); - if (projection.children.size() != 1) { - return nullptr; - } - auto result = GetGeneratedDomainRef(*projection.children[0], collect_filters, allow_projection); - if (!result) { - return nullptr; - } - - auto child_bindings = result->output_bindings; - auto child_expressions = std::move(result->output_expressions); - result->output_bindings = projection.GetColumnBindings(); - result->output_expressions.clear(); - result->output_expressions.reserve(projection.expressions.size()); - for (auto &expr : projection.expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, child_bindings, child_expressions); - result->output_expressions.push_back(std::move(rewritten_expr)); - } - return result; - } - return nullptr; -} - -optional_idx GeneratedDomainJoinEliminator::FindOutputBinding(Expression &expr, - const vector &bindings) const { - ColumnBinding binding; - if (!GetBoundColumnRefBinding(expr, binding)) { - return optional_idx(); - } - return FindBindingIndex(bindings, binding); + }; + return ReadGeneratedDomainRef(op, resolve, true, true); } bool GeneratedDomainJoinEliminator::ContainsRecursiveCTERef(LogicalOperator &op) const { @@ -2172,127 +1679,34 @@ bool GeneratedDomainJoinEliminator::RemoveGeneratedDedupJoin(unique_ptrCast(); - if (comparison_join.join_type != JoinType::INNER && - (comparison_join.join_type != JoinType::SEMI || !GetGeneratedDedupRef(*join->children[1], false, true))) { + if (comparison_join.join_type != JoinType::INNER && comparison_join.join_type != JoinType::SEMI) { return false; } - auto left_is_generated = GetGeneratedDedupRef(*join->children[0], false, true) != nullptr; - auto right_is_generated = GetGeneratedDedupRef(*join->children[1], false, true) != nullptr; - if (left_is_generated == right_is_generated) { + auto left_generated = GetGeneratedDedupRef(*join->children[0], true, true); + auto right_generated = GetGeneratedDedupRef(*join->children[1], true, true); + if ((left_generated != nullptr) == (right_generated != nullptr) || + (comparison_join.join_type == JoinType::SEMI && !right_generated)) { return false; } - const idx_t dedup_idx = left_is_generated ? 0 : 1; + const idx_t dedup_idx = left_generated ? 0 : 1; if (ContainsRecursiveCTERef(*join->children[1 - dedup_idx])) { return false; } - auto dedup_ref = GetGeneratedDedupRef(*join->children[dedup_idx], true, true); - if (!dedup_ref) { - return false; - } + auto dedup_ref = left_generated ? std::move(left_generated) : std::move(right_generated); if ((under_aggregate || under_evidence_side) && GeneratedDedupRefHasSelection(*dedup_ref)) { // The first CTE rewrite can preserve selected domains below aggregates or existence checks as regular joins. // Do not substitute that selected generated CTE away in the cleanup pass. return false; } - vector covered_dedup_bindings; - vector base_replacement_bindings; - vector> base_replacement_expressions; - vector> join_filter_expressions; - BindingReplacementGraph replacement_bindings; - for (auto &cond : comparison_join.conditions) { - if (!cond.IsComparison() || !IsEqualityJoinCondition(cond)) { - return false; - } - auto lhs_generated_idx = FindOutputBinding(cond.GetLHS(), dedup_ref->output_bindings); - auto rhs_generated_idx = FindOutputBinding(cond.GetRHS(), dedup_ref->output_bindings); - if (lhs_generated_idx.IsValid() == rhs_generated_idx.IsValid()) { - return false; - } - auto generated_idx = lhs_generated_idx.IsValid() ? lhs_generated_idx.GetIndex() : rhs_generated_idx.GetIndex(); - auto &generated_binding = dedup_ref->output_bindings[generated_idx]; - auto &generated_expression = *dedup_ref->output_expressions[generated_idx]; - auto &other_side = lhs_generated_idx.IsValid() ? cond.GetRHS() : cond.GetLHS(); - - ColumnBinding other_binding; - if (!GetBoundColumnRefBinding(other_side, other_binding)) { - return false; - } - if (!replacement_bindings.TryAdd(ReplacementBinding(generated_binding, other_binding))) { - return false; - } - - ColumnBinding base_binding; - if (GetBoundColumnRefBinding(generated_expression, base_binding) && - base_binding.table_index == dedup_ref->cte_ref->table_index) { - if (!replacement_bindings.TryAdd(ReplacementBinding(base_binding, other_binding))) { - return false; - } - covered_dedup_bindings.emplace_back(base_binding); - if (!AddExpressionReplacement(base_replacement_bindings, base_replacement_expressions, base_binding, - other_side.Copy())) { - return false; - } - } - - join_filter_expressions.push_back( - BoundComparisonExpression::Create(cond.GetComparisonType(), cond.GetLHS().Copy(), cond.GetRHS().Copy())); - } - - auto cte_bindings = LogicalOperator::GenerateColumnBindings(dedup_ref->cte_ref->table_index, - dedup_ref->cte_ref->chunk_types.size()); - if (!CoversAllBindings(cte_bindings, covered_dedup_bindings)) { + GeneratedDomainReplacement replacement; + if (!replacement.Analyze(comparison_join.conditions, *dedup_ref, GeneratedDomainAction::REMOVE) || + !replacement.all_equality) { return false; } - - vector> generated_output_replacements; - generated_output_replacements.reserve(dedup_ref->output_expressions.size()); - for (auto &expr : dedup_ref->output_expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesBinding(*rewritten_expr, dedup_ref->output_bindings) || - ExpressionReferencesBinding(*rewritten_expr, cte_bindings)) { - return false; - } - generated_output_replacements.push_back(std::move(rewritten_expr)); - } - - vector> filter_expressions; - for (auto &expr : dedup_ref->filters) { - ReplaceExpressionBindings(expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesBinding(*expr, dedup_ref->output_bindings) || - ExpressionReferencesBinding(*expr, cte_bindings)) { - return false; - } - filter_expressions.push_back(std::move(expr)); - } - for (auto &expr : join_filter_expressions) { - ReplaceExpressionBindings(expr, dedup_ref->output_bindings, generated_output_replacements); - ReplaceExpressionBindings(expr, base_replacement_bindings, base_replacement_expressions); - if (ExpressionReferencesBinding(*expr, dedup_ref->output_bindings) || - ExpressionReferencesBinding(*expr, cte_bindings)) { - return false; - } - if (IsTautologicalNotDistinctComparison(*expr)) { - continue; - } - filter_expressions.push_back(std::move(expr)); - } - - unique_ptr replacement_op = std::move(comparison_join.children[1 - dedup_idx]); - for (auto &expr : filter_expressions) { - AddFilterToOperator(replacement_op, std::move(expr)); - } - join = std::move(replacement_op); - - ColumnBindingReplacer column_replacer; - replacement_bindings.AddTo(column_replacer); - column_replacer.BuildIndex(); - column_replacer.VisitOperator(*rewrite_root); - ReplaceOperatorBindings(*rewrite_root, dedup_ref->output_bindings, generated_output_replacements); - replacements.Merge(replacement_bindings); - MergeBindingExpressionReplacements(replacements, dedup_ref->output_bindings, generated_output_replacements); + replacement.Apply(binder, join, 1 - dedup_idx, *dedup_ref, GeneratedDomainAction::REMOVE, *rewrite_root, + replacements); return true; } @@ -2306,24 +1720,14 @@ bool GeneratedDomainJoinEliminator::RemoveGeneratedDomainJoin(unique_ptrchildren[0], false, true); auto right_generated = GetGeneratedDedupRef(*join->children[1], false, true); - auto left_domain = GetGeneratedDomainRef(*join->children[0], false, true); - auto right_domain = GetGeneratedDomainRef(*join->children[1], false, true); - auto left_is_generated = left_generated != nullptr; - auto right_is_generated = right_generated != nullptr; - auto left_is_domain = left_domain != nullptr; - auto right_is_domain = right_domain != nullptr; - if (left_is_generated == right_is_generated || left_is_domain == right_is_domain) { - return false; - } - if (left_is_generated == left_is_domain) { + if ((left_generated != nullptr) == (right_generated != nullptr)) { return false; } - const idx_t generated_idx = left_is_generated ? 0 : 1; - const idx_t domain_idx = 1 - generated_idx; - auto generated_ref = GetGeneratedDedupRef(*join->children[generated_idx], true, true); - auto domain_ref = GetGeneratedDomainRef(*join->children[domain_idx], true, true); - if (!generated_ref || !domain_ref) { + const idx_t generated_idx = left_generated ? 0 : 1; + auto generated_ref = left_generated ? std::move(left_generated) : std::move(right_generated); + auto domain_ref = GetGeneratedDomainRef(*join->children[1 - generated_idx]); + if (!domain_ref) { return false; } if ((under_aggregate || under_evidence_side) && (domain_ref->has_selection || !domain_ref->filters.empty())) { @@ -2332,90 +1736,22 @@ bool GeneratedDomainJoinEliminator::RemoveGeneratedDomainJoin(unique_ptr source_replacement_bindings; - vector> source_replacement_expressions; - vector covered_source_bindings; - vector> join_filter_expressions; - for (auto &cond : comparison_join.conditions) { - if (!cond.IsComparison() || !IsEqualityJoinCondition(cond)) { + for (auto &condition : comparison_join.conditions) { + if (!condition.IsComparison()) { return false; } - - auto lhs_generated_idx = FindOutputBinding(cond.GetLHS(), generated_ref->output_bindings); - auto rhs_generated_idx = FindOutputBinding(cond.GetRHS(), generated_ref->output_bindings); - auto lhs_domain_idx = FindOutputBinding(cond.GetLHS(), domain_ref->output_bindings); - auto rhs_domain_idx = FindOutputBinding(cond.GetRHS(), domain_ref->output_bindings); - - const bool lhs_generated = lhs_generated_idx.IsValid(); - const bool rhs_generated = rhs_generated_idx.IsValid(); - const bool lhs_domain = lhs_domain_idx.IsValid(); - const bool rhs_domain = rhs_domain_idx.IsValid(); - if (lhs_generated == rhs_generated || lhs_domain == rhs_domain || lhs_generated == lhs_domain) { + auto &base_expression = generated_idx == 0 ? condition.GetLHS() : condition.GetRHS(); + if (!FindDomainOutput(base_expression, *generated_ref).IsValid()) { return false; } - - auto domain_output_idx = lhs_domain ? lhs_domain_idx.GetIndex() : rhs_domain_idx.GetIndex(); - auto &domain_expression = *domain_ref->output_expressions[domain_output_idx]; - ColumnBinding source_binding; - if (GetBoundColumnRefBinding(domain_expression, source_binding) && - FindBindingIndex(domain_ref->source_bindings, source_binding).IsValid()) { - auto generated_expression = lhs_generated ? cond.GetLHS().Copy() : cond.GetRHS().Copy(); - if (!AddExpressionReplacement(source_replacement_bindings, source_replacement_expressions, source_binding, - std::move(generated_expression))) { - return false; - } - covered_source_bindings.emplace_back(source_binding); - } - - join_filter_expressions.push_back( - BoundComparisonExpression::Create(cond.GetComparisonType(), cond.GetLHS().Copy(), cond.GetRHS().Copy())); } - if (!CoversAllBindings(domain_ref->source_bindings, covered_source_bindings)) { + GeneratedDomainReplacement replacement; + if (!replacement.Analyze(comparison_join.conditions, *domain_ref, GeneratedDomainAction::REMOVE) || + !replacement.all_equality) { return false; } - - vector> domain_output_replacements; - domain_output_replacements.reserve(domain_ref->output_expressions.size()); - for (auto &expr : domain_ref->output_expressions) { - auto rewritten_expr = expr->Copy(); - ReplaceExpressionBindings(rewritten_expr, source_replacement_bindings, source_replacement_expressions); - if (ExpressionReferencesBinding(*rewritten_expr, domain_ref->output_bindings) || - ExpressionReferencesBinding(*rewritten_expr, domain_ref->source_bindings)) { - return false; - } - domain_output_replacements.push_back(std::move(rewritten_expr)); - } - - vector> filter_expressions; - for (auto &expr : domain_ref->filters) { - ReplaceExpressionBindings(expr, source_replacement_bindings, source_replacement_expressions); - if (ExpressionReferencesBinding(*expr, domain_ref->output_bindings) || - ExpressionReferencesBinding(*expr, domain_ref->source_bindings)) { - return false; - } - filter_expressions.push_back(std::move(expr)); - } - for (auto &expr : join_filter_expressions) { - ReplaceExpressionBindings(expr, domain_ref->output_bindings, domain_output_replacements); - ReplaceExpressionBindings(expr, source_replacement_bindings, source_replacement_expressions); - if (ExpressionReferencesBinding(*expr, domain_ref->output_bindings) || - ExpressionReferencesBinding(*expr, domain_ref->source_bindings)) { - return false; - } - if (IsTautologicalNotDistinctComparison(*expr)) { - continue; - } - filter_expressions.push_back(std::move(expr)); - } - - unique_ptr replacement_op = std::move(comparison_join.children[generated_idx]); - for (auto &expr : filter_expressions) { - AddFilterToOperator(replacement_op, std::move(expr)); - } - join = std::move(replacement_op); - - ReplaceOperatorBindings(*rewrite_root, domain_ref->output_bindings, domain_output_replacements); - MergeBindingExpressionReplacements(replacements, domain_ref->output_bindings, domain_output_replacements); + replacement.Apply(binder, join, generated_idx, *domain_ref, GeneratedDomainAction::REMOVE, *rewrite_root, + replacements); return true; } @@ -2663,7 +1999,7 @@ BindingReplacementGraph DelimJoinCTERewriter::MaterializeDelimJoinAsCTE(unique_p if (cte_deliminator_enabled) { auto cte_deliminator_timer = QueryProfiler::Get(binder.context).StartTimerInternal(CTE_DELIMINATOR_PROFILER_KEY); - GeneratedDedupRefEliminator eliminator(binder.context, plan, dedup_cte_index, dedup_ref_count, rewrite_root, + GeneratedDedupRefEliminator eliminator(binder, plan, dedup_cte_index, dedup_ref_count, rewrite_root, preserve_evidence_side, preserve_nested_evidence_side); dedup_ref_count = eliminator.Remove(); auto &join = plan->Cast(); @@ -2869,7 +2205,7 @@ void DelimJoinCTERewriter::Rewrite(unique_ptr &plan) { if (cte_deliminator_enabled) { auto cte_deliminator_timer = QueryProfiler::Get(binder.context).StartTimerInternal(CTE_DELIMINATOR_PROFILER_KEY); - GeneratedDomainJoinEliminator generated_domain_join_eliminator(plan, generated_dedup_cte_indexes, + GeneratedDomainJoinEliminator generated_domain_join_eliminator(binder, plan, generated_dedup_cte_indexes, preserve_marker_indexes); generated_domain_join_eliminator.Rewrite(); } diff --git a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp index ce296f910..1b60f2b9e 100644 --- a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp +++ b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp @@ -377,9 +377,6 @@ FlattenDependentJoins::DecorrelateSubtreeInternal(unique_ptr &p output.right_payload.erase(right_entry); } } - auto left_child_requires_domain = RequiresDomain(*plan->children[0]); - auto requires_full_rhs_decorrelation = left_child_requires_domain || op.join_type != JoinType::SINGLE; - // Phase 1: prepare the left side in the current flattener context. auto outer_state = PrepareDependentJoinLeft(plan, propagate_null_values, std::move(state)); // Phase 2: push the active correlated state through the right subtree in a child flattener. @@ -399,13 +396,6 @@ FlattenDependentJoins::DecorrelateSubtreeInternal(unique_ptr &p definition_state.replacement_graph); // the domain probe above cached access entries for definition operators this replaced child_flatten.InvalidateAccessCache(); - if (requires_full_rhs_decorrelation) { - auto result = DecorrelateSubtree(plan, propagate_null_values, std::move(outer_state.bindings)); - result.replacement_graph.Merge(outer_state.replacement_graph); - detached_cte->children[1] = std::move(plan); - plan = std::move(detached_cte); - return result; - } } } @@ -578,8 +568,21 @@ vector FlattenDependentJoins::GetCTERefCorrelatedPositions(const L void FlattenDependentJoins::AddCTERefJoinConditions(LogicalComparisonJoin &join, const LogicalCTERef &cteref, const vector &positions, const vector &state) const { + optional_idx identity; + auto cte_entry = binder.recursive_ctes.find(cteref.cte_index); + if (cte_entry != binder.recursive_ctes.end()) { + auto &columns = cte_entry->second->Cast().correlated_columns; + auto delim_index = columns.GetDelimIndex(); + if (delim_index < columns.size()) { + auto index = GetCorrelatedIndex(columns[delim_index].binding); + if (index.IsValid() && positions[index.GetIndex()].IsValid()) { + identity = index; + } + } + } for (idx_t i = 0; i < positions.size(); i++) { - if (!positions[i].IsValid()) { + // The CTE's row identity determines all its correlation payloads. + if (!positions[i].IsValid() || (identity.IsValid() && i != identity.GetIndex())) { continue; } JoinCondition cond(make_uniq( @@ -1190,11 +1193,9 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownFullOuterJo expressions.push_back(make_uniq(join_types[position], binding)); } for (idx_t i = 0; i < correlated_columns.size(); i++) { - auto coalesce = - make_uniq(ExpressionType::OPERATOR_COALESCE, correlated_columns[i].type); - coalesce->GetChildrenMutable().push_back( - make_uniq(correlated_columns[i].type, left_state.bindings[i])); - coalesce->GetChildrenMutable().push_back( + auto coalesce = make_uniq( + ExpressionType::OPERATOR_COALESCE, correlated_columns[i].type, + make_uniq(correlated_columns[i].type, left_state.bindings[i]), make_uniq(correlated_columns[i].type, right_state.bindings[i])); expressions.push_back(std::move(coalesce)); } diff --git a/src/duckdb/src/planner/subquery/rewrite_correlated_expressions.cpp b/src/duckdb/src/planner/subquery/rewrite_correlated_expressions.cpp index b50eaf619..45758e0f0 100644 --- a/src/duckdb/src/planner/subquery/rewrite_correlated_expressions.cpp +++ b/src/duckdb/src/planner/subquery/rewrite_correlated_expressions.cpp @@ -66,15 +66,12 @@ unique_ptr RewriteCorrelatedExpressions::VisitReplace(BoundColumnRef D_ASSERT(current_entry != current_binding_map.end()); auto original_binding = expr.Binding(); if (original_binding == current_entry->second) { - expr.DepthMutable() = 0; - return nullptr; + return expr.WithDepth(0); } - expr.BindingMutable() = current_entry->second; - RegisterCorrelatedBinding(original_binding, expr.Binding()); + RegisterCorrelatedBinding(original_binding, current_entry->second); // The current representative is produced inside the converted algebra. Once a // reference points at it, it is local regardless of the original binder depth. - expr.DepthMutable() = 0; - return nullptr; + return expr.WithBinding(current_entry->second, 0); } RewriteCorrelatedAggregates::RewriteCorrelatedAggregates( @@ -93,8 +90,8 @@ unique_ptr RewriteCorrelatedAggregates::VisitReplace(BoundColumnRefE auto entry = replacement_map.find(expr.Binding()); if (entry != replacement_map.end()) { // Replace this with CASE WHEN the aggregate group is missing THEN EMPTY_RESULT ELSE AGGREGATE END. - auto is_null = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); - is_null->GetChildrenMutable().push_back( + auto is_null = make_uniq( + ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, make_uniq(LogicalType::BIGINT, entry->second.marker)); auto check = std::move(is_null); auto result_if_true = make_uniq(expr.GetReturnType(), entry->second.empty_result); diff --git a/src/duckdb/src/planner/table_binding.cpp b/src/duckdb/src/planner/table_binding.cpp index 3cff39fd1..4857b98cc 100644 --- a/src/duckdb/src/planner/table_binding.cpp +++ b/src/duckdb/src/planner/table_binding.cpp @@ -384,6 +384,10 @@ bool CTEBinding::CanBeReferenced() const { return cte_type == CTEType::CAN_BE_REFERENCED; } +bool CTEBinding::IsRecursiveSelfReference() const { + return cte_type == CTEType::CANNOT_BE_REFERENCED_RECURSIVE; +} + bool CTEBinding::IsReferenced() const { return reference_count > 0; } diff --git a/src/duckdb/src/planner/table_filter_set.cpp b/src/duckdb/src/planner/table_filter_set.cpp index 2e746b486..97102e827 100644 --- a/src/duckdb/src/planner/table_filter_set.cpp +++ b/src/duckdb/src/planner/table_filter_set.cpp @@ -89,12 +89,16 @@ static unique_ptr WrapStructFilterPath(unique_ptr filt } static void NormalizeLegacyExpression(unique_ptr &expr) { - ExpressionIterator::VisitExpressionMutable( - expr, [](BoundColumnRefExpression &col_ref, unique_ptr &owned_expr) { - owned_expr = make_uniq(col_ref.GetAlias(), col_ref.GetReturnType(), 0ULL); - }); - ExpressionIterator::VisitExpressionMutable( - expr, [](BoundReferenceExpression &ref, unique_ptr &owned_expr) { ref.IndexMutable() = 0; }); + expr = ExpressionIterator::PreorderReplace(std::move(expr), [](const Expression &child) -> unique_ptr { + switch (child.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: + return make_uniq(child.GetAlias(), child.GetReturnType(), 0ULL); + case ExpressionClass::BOUND_REF: + return child.Cast().WithIndex(0); + default: + return nullptr; + } + }); } static unique_ptr TrySerializeComparisonToLegacyFilter(const BoundFunctionExpression &comparison) { @@ -418,9 +422,8 @@ void TableFilterSet::PushFilter(ProjectionIndex col_idx, unique_ptr } else { // there is already a filter: AND it together auto &existing = ExpressionFilter::GetExpressionFilter(*entry->second, "TableFilterSet::PushFilter"); - auto and_expr = make_uniq(ExpressionType::CONJUNCTION_AND); - and_expr->GetChildrenMutable().push_back(std::move(existing.expr)); - and_expr->GetChildrenMutable().push_back(std::move(new_filter.expr)); + auto and_expr = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(existing.expr), + std::move(new_filter.expr)); filters[col_idx] = make_uniq(std::move(and_expr)); } } diff --git a/src/duckdb/src/planner/table_filter_state.cpp b/src/duckdb/src/planner/table_filter_state.cpp index cbb0ff4a2..2b04ab4e5 100644 --- a/src/duckdb/src/planner/table_filter_state.cpp +++ b/src/duckdb/src/planner/table_filter_state.cpp @@ -1,3 +1,5 @@ +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/planner/table_filter_state.hpp" #include "duckdb/common/operator/comparison_operators.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" @@ -16,12 +18,12 @@ namespace duckdb { static unique_ptr TryCreateFastExecutor(const Expression &expression, bool inside_selectivity_optional); -static void InitializeExecutor(ClientContext &context, const Expression &expression, ExpressionFilterState &state) { +static void InitializeExecutor(Context &context, const Expression &expression, ExpressionFilterState &state) { state.executor = make_uniq(context); state.executor->AddExpression(expression); } -ExpressionFilterState::ExpressionFilterState(ClientContext &context, const Expression &expression) { +ExpressionFilterState::ExpressionFilterState(Context &context, const Expression &expression) { can_throw = expression.CanThrow(); fast_executor = TryCreateFastExecutor(expression, false); InitializeExecutor(context, expression, *this); @@ -323,6 +325,9 @@ class BloomFilterExecutor final : public ExpressionFilterExecutor { const auto hash_capacity = sel.IsSet() ? scan_count : approved_tuple_count; PrepareCapacity(hash_capacity); + if (sel.IsSet() && sel.data() == bloom_sel.data()) { + bloom_sel.Initialize(current_capacity); + } if (sel.IsSet()) { VectorOperations::Hash(vector, hashes, sel, approved_tuple_count); if (hashes.GetVectorType() == VectorType::FLAT_VECTOR) { @@ -466,6 +471,9 @@ class PrefixRangeFilterExecutor final : public ExpressionFilterExecutor { } PrepareCapacity(approved_tuple_count); + if (sel.IsSet() && sel.data() == local_sel.data()) { + local_sel.Initialize(current_capacity); + } const auto has_selection = sel.IsSet(); const auto result_count = has_selection ? filter->LookupKeys(vector, sel, local_sel, approved_tuple_count) : filter->LookupKeys(vector, local_sel, approved_tuple_count); @@ -691,7 +699,7 @@ static unique_ptr TryCreateFastExecutor(const Expressi unique_ptr TableFilterState::Initialize(ClientContext &context, const TableFilter &filter) { auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "TableFilterState::Initialize"); - return make_uniq(context, *expr_filter.expr); + return make_uniq(context.GetContext(), *expr_filter.expr); } } // namespace duckdb diff --git a/src/duckdb/src/storage/block_allocator.cpp b/src/duckdb/src/storage/block_allocator.cpp index f99ab819d..33feceee4 100644 --- a/src/duckdb/src/storage/block_allocator.cpp +++ b/src/duckdb/src/storage/block_allocator.cpp @@ -1,4 +1,5 @@ #include "duckdb/storage/block_allocator.hpp" +#include "duckdb/storage/sharded_allocator_queue.hpp" #include "duckdb/common/allocator.hpp" #include "duckdb/common/types/uuid.hpp" @@ -6,6 +7,7 @@ #include "duckdb/common/thread.hpp" #include +#include #if defined(__linux__) && INTPTR_MAX == INT64_MAX #include @@ -53,14 +55,8 @@ struct BlockAllocatorConfig { static constexpr idx_t RECLAIM_BATCH_SIZE = 1024; //! Maximum blocks reclaimed by one background task. static constexpr idx_t MAX_FLUSH_BLOCKS = 64; - //! Width of each retention bucket, rounding return times up to the bucket end. - static constexpr idx_t RETENTION_INTERVAL_MS = 500; //! Minimum interval between bounded decay checks on each allocating thread. - static constexpr idx_t ACTIVE_DECAY_INTERVAL_MS = RETENTION_INTERVAL_MS; - //! Linear decay on the same one-second timescale as bundled jemalloc, without extra grace. - static constexpr idx_t RETENTION_DECAY_MS = DEFAULT_DECAY_DELAY * 1000; - //! Current bucket plus the complete decay history. - static constexpr idx_t RETENTION_BUCKETS = RETENTION_DECAY_MS / RETENTION_INTERVAL_MS + 1; + static constexpr idx_t ACTIVE_DECAY_INTERVAL_MS = AllocatorCacheRetention::INTERVAL_MS; }; static idx_t RetentionTimeMillis() { @@ -79,19 +75,17 @@ static uint32_t RetentionBucketCount(const uint64_t bucket) { return static_cast(bucket); } -void BlockAllocator::InitializeRetention(const idx_t now_ms) const { - const auto epoch = now_ms / BlockAllocatorConfig::RETENTION_INTERVAL_MS; - for (idx_t age = 0; age < retention_buckets.size(); age++) { - auto &bucket = retention_buckets[(epoch % retention_buckets.size() + retention_buckets.size() - age) % - retention_buckets.size()]; +void AllocatorCacheRetention::Reset(const idx_t now_ms) { + const auto epoch = now_ms / INTERVAL_MS; + for (idx_t age = 0; age < buckets.size(); age++) { + auto &bucket = buckets[(epoch % buckets.size() + buckets.size() - age) % buckets.size()]; bucket.store(PackRetentionBucket(static_cast(epoch - age), 0), std::memory_order_relaxed); } } -void BlockAllocator::AddRetention(const idx_t count, const idx_t now_ms) const { - const auto epoch = now_ms / BlockAllocatorConfig::RETENTION_INTERVAL_MS; - const auto capacity = DivBlockSize(pool_size); - auto &bucket = retention_buckets[epoch % retention_buckets.size()]; +void AllocatorCacheRetention::Return(const idx_t count, const idx_t capacity, const idx_t now_ms) { + const auto epoch = now_ms / INTERVAL_MS; + auto &bucket = buckets[epoch % buckets.size()]; auto current = bucket.load(std::memory_order_relaxed); do { const auto elapsed = static_cast(epoch - RetentionBucketEpoch(current)); @@ -109,11 +103,10 @@ void BlockAllocator::AddRetention(const idx_t count, const idx_t now_ms) const { } while (true); } -void BlockAllocator::ReuseRetention(idx_t count, const idx_t now_ms) const { - const auto epoch = now_ms / BlockAllocatorConfig::RETENTION_INTERVAL_MS; - for (idx_t age = 0; age < retention_buckets.size() && count > 0; age++) { - auto &bucket = retention_buckets[(epoch % retention_buckets.size() + retention_buckets.size() - age) % - retention_buckets.size()]; +void AllocatorCacheRetention::Reuse(idx_t count, const idx_t now_ms) { + const auto epoch = now_ms / INTERVAL_MS; + for (idx_t age = 0; age < buckets.size() && count > 0; age++) { + auto &bucket = buckets[(epoch % buckets.size() + buckets.size() - age) % buckets.size()]; auto current = bucket.load(std::memory_order_relaxed); while (RetentionBucketEpoch(current) == static_cast(epoch - age) && RetentionBucketCount(current) > 0) { @@ -128,21 +121,21 @@ void BlockAllocator::ReuseRetention(idx_t count, const idx_t now_ms) const { } } -idx_t BlockAllocator::RetentionTarget(const idx_t now_ms) const { - const auto epoch = now_ms / BlockAllocatorConfig::RETENTION_INTERVAL_MS; +idx_t AllocatorCacheRetention::Target(const idx_t now_ms) const { + const auto epoch = now_ms / INTERVAL_MS; idx_t weighted = 0; - const auto offset = now_ms % BlockAllocatorConfig::RETENTION_INTERVAL_MS; - for (auto &bucket : retention_buckets) { + const auto offset = now_ms % INTERVAL_MS; + for (auto &bucket : buckets) { const auto current = bucket.load(std::memory_order_relaxed); const auto age = static_cast(epoch - RetentionBucketEpoch(current)); - if (age >= retention_buckets.size()) { + if (age >= buckets.size()) { continue; } - const auto age_ms = age == 0 ? 0 : (age - 1) * BlockAllocatorConfig::RETENTION_INTERVAL_MS + offset; - const auto remaining_ms = BlockAllocatorConfig::RETENTION_DECAY_MS - age_ms; + const auto age_ms = age == 0 ? 0 : (age - 1) * INTERVAL_MS + offset; + const auto remaining_ms = DECAY_MS - age_ms; weighted += RetentionBucketCount(current) * remaining_ms; } - return weighted / BlockAllocatorConfig::RETENTION_DECAY_MS; + return weighted / DECAY_MS; } //===--------------------------------------------------------------------===// @@ -180,6 +173,24 @@ static void FreeVirtualMemory(const data_ptr_t pointer, const idx_t size) { } } +static bool ProtectVirtualMemory(const data_ptr_t pointer, const idx_t size) { +#if defined(_WIN32) + MEMORY_BASIC_INFORMATION info; + if (!VirtualQuery(pointer, &info, sizeof(info))) { + return false; + } + if (info.State == MEM_RESERVE) { + // Uncommitted reservations are already inaccessible; keep the guards unbacked. + const auto offset = uintptr_t(pointer) - uintptr_t(info.BaseAddress); + return offset <= info.RegionSize && size <= info.RegionSize - offset; + } + DWORD old_protection; + return VirtualProtect(pointer, size, PAGE_NOACCESS, &old_protection) != 0; +#else + return mprotect(pointer, size, PROT_NONE) == 0; +#endif +} + static void OnFirstAllocation(const data_ptr_t pointer, const idx_t size) { bool success = true; #if defined(_WIN32) @@ -209,8 +220,67 @@ static bool OnDeallocation(const data_ptr_t pointer, const idx_t size) { //===--------------------------------------------------------------------===// // BlockAllocatorThreadLocalState //===--------------------------------------------------------------------===// +static idx_t AllocatorShardCount() { +#ifndef DUCKDB_NO_THREADS + const idx_t cpus = std::thread::hardware_concurrency(); + return MaxValue(1, MinValue(256, (cpus + 3) / 4)); +#else + return 1; +#endif +} + +static idx_t AllocatorLocalShard(const idx_t count) { + return count == 1 ? 0 : (TaskScheduler::GetEstimatedCPUId() / 4) % count; +} + struct BlockQueue { - duckdb_moodycamel::ConcurrentQueue q; + BlockQueue(idx_t blocks, idx_t shards) + : blocks_per_shard(MaxValue(1, blocks / shards + (blocks % shards != 0))), + queues(MaxValue(1, blocks / blocks_per_shard + (blocks % blocks_per_shard != 0)), + blocks > blocks_per_shard) { + } + + void ReserveOverflow(idx_t blocks) { + for (idx_t shard = 0; shard < queues.Count(); shard++) { + queues.Get(shard).ReserveOverflow(MinValue(blocks_per_shard, blocks - shard * blocks_per_shard)); + } + } + void ReleaseOverflow() { + for (idx_t shard = 0; shard < queues.Count(); shard++) { + queues.Get(shard).ReserveOverflow(0); + } + } + idx_t Home(uint32_t block) const { + return block / blocks_per_shard; + } + bool Enqueue(uint32_t block) { + return queues.Get(Home(block)).EnqueueBulk(&block, 1); + } + template + bool EnqueueBulk(ITERATOR begin, idx_t count) { + if (queues.Count() == 1) { + return queues.Get(0).EnqueueBulk(begin, count); + } + while (count > 0) { + const auto shard = Home(*begin); + idx_t next = 1; + while (next < count && Home(begin[next]) == shard) { + next++; + } + if (!queues.Get(shard).EnqueueBulk(begin, next)) { + return false; + } + begin += next; + count -= next; + } + return true; + } + idx_t SizeApprox() const { + return queues.SizeApprox(); + } + + const idx_t blocks_per_shard; + ShardedAllocatorQueue queues; }; struct BlockAllocatorLifetimeState { @@ -236,6 +306,10 @@ class BlockAllocatorThreadLocalState { } data_ptr_t Allocate() { + const auto shard = block_allocator->GetLocalPoolShard(); + if (shard != preferred_shard && TryClear()) { + preferred_shard = shard; + } auto pointer = TryAllocateFromLocal(); if (pointer) { return pointer; @@ -249,6 +323,32 @@ class BlockAllocatorThreadLocalState { return pointer; } + // Borrow individual blocks so a remote batch cannot occupy this thread's local cache. + for (auto queue : {block_allocator->touched.get(), block_allocator->untouched.get()}) { + for (idx_t offset = 1; offset < queue->queues.Count(); offset++) { + uint32_t block; + if (!queue->queues.Get((preferred_shard + offset) % queue->queues.Count()).TryDequeueBulk(&block, 1)) { + continue; + } + pointer = block_allocator->GetPointer(block); + if (queue == block_allocator->touched.get()) { + block_allocator->UpdateCachedBlocks(-1, cache_slot); + OnSharedReuse(1); + } else { + try { + OnFirstAllocation(pointer, block_allocator->block_size); + } catch (...) { + // Retain ownership without allocating queue metadata while memory is exhausted. + D_ASSERT(untouched.empty()); + D_ASSERT(untouched.capacity() >= BlockAllocatorConfig::BATCH_SIZE); + untouched.push_back(block); + throw; + } + } + return pointer; + } + } + // We have also run out of global blocks, use fallback allocator return RetryAfterReclaiming( *block_allocator, [&] { return block_allocator->allocator.AllocateData(block_allocator->block_size); }); @@ -262,32 +362,73 @@ class BlockAllocatorThreadLocalState { } // Upon reaching the threshold, we return a local batch to global - std::sort(touched.begin(), touched.end()); ReturnTouched(BlockAllocatorConfig::BATCH_SIZE); } void Clear() DUCKDB_EXCLUDES(lifetime_state->lock) { + TryClear(); + touched.clear(); + untouched.clear(); + } + +private: + bool TryClear() DUCKDB_EXCLUDES(lifetime_state->lock) { if (lifetime_state) { annotated_lock_guard guard(lifetime_state->lock); if (lifetime_state->alive) { - if (!touched.empty()) { - ReturnTouched(touched.size()); - } - if (!untouched.empty()) { - block_allocator->untouched->q.enqueue_bulk(untouched.begin(), untouched.size()); - } + TryReturnTouched(touched.size()); + TryReturnBlocks(untouched, *block_allocator->untouched, untouched.size()); + return touched.empty() && untouched.empty(); } } touched.clear(); untouched.clear(); + return true; + } + + static idx_t TryReturnBlocks(vector &blocks, BlockQueue &queue, const idx_t count) { + D_ASSERT(count <= blocks.size()); + const auto initial_size = blocks.size(); + const auto remaining_size = initial_size - count; + if (queue.queues.Count() == 1) { + if (count > 0 && queue.queues.Get(0).EnqueueBulk(blocks.data() + remaining_size, count)) { + blocks.resize(remaining_size); + } + return initial_size - blocks.size(); + } + while (blocks.size() > remaining_size) { + const auto home = queue.Home(blocks.back()); + auto begin = blocks.size() - 1; + while (begin > remaining_size && queue.Home(blocks[begin - 1]) == home) { + begin--; + } + if (!queue.queues.Get(home).EnqueueBulk(blocks.data() + begin, blocks.size() - begin)) { + break; + } + blocks.resize(begin); + } + return initial_size - blocks.size(); + } + + bool TryReturnTouched(const idx_t count) { + if (count == 0) { + return true; + } + block_allocator->retention.Return(count, block_allocator->GetUsableBlockCount(), RetentionTimeMillis()); + if (count < touched.size() || block_allocator->touched->queues.Count() > 1) { + std::sort(touched.begin(), touched.end()); + } + const auto returned = TryReturnBlocks(touched, *block_allocator->touched, count); + if (returned < count) { + block_allocator->retention.Reuse(count - returned, RetentionTimeMillis()); + } + return returned == count; } -private: void ReturnTouched(const idx_t count) { - block_allocator->AddRetention(count, RetentionTimeMillis()); - block_allocator->touched->q.enqueue_bulk(touched.end() - NumericCast::difference_type>(count), - count); - touched.resize(touched.size() - count); + const auto remaining_size = touched.size() - count; + TryReturnTouched(count); + touched.resize(remaining_size); } void Initialize(const BlockAllocator &block_allocator_p) { @@ -298,11 +439,21 @@ class BlockAllocatorThreadLocalState { cache_slot = block_allocator_p.next_cache_slot.fetch_add(1, std::memory_order_relaxed) % block_allocator_p.cached_blocks.size(); next_decay_check = 0; + preferred_shard = block_allocator_p.GetLocalPoolShard(); untouched.reserve(BlockAllocatorConfig::BATCH_SIZE); touched.reserve(BlockAllocatorConfig::FREE_THRESHOLD); } data_ptr_t TryAllocateFromLocal() { + if (!touched.empty() && block_allocator->touched->queues.Count() > 1 && + block_allocator->touched->Home(touched.back()) != preferred_shard) { + // Prefer returning foreign frees, but keep them reusable if queue metadata allocation fails. + TryReturnTouched(touched.size()); + // The returned batch may also contain local blocks; prefer those to untouched backing. + if (touched.empty()) { + TryGetBatch(touched, *block_allocator->touched); + } + } if (!touched.empty()) { const auto pointer = block_allocator->GetPointer(touched.back()); touched.pop_back(); @@ -318,26 +469,31 @@ class BlockAllocatorThreadLocalState { return nullptr; } + void OnSharedReuse(idx_t count) { + const auto now = RetentionTimeMillis(); + block_allocator->retention.Reuse(count, now); + if (now >= next_decay_check) { + next_decay_check = now + BlockAllocatorConfig::ACTIVE_DECAY_INTERVAL_MS; + try { + block_allocator->FlushAllocationCache(BlockAllocatorConfig::MAX_FLUSH_BLOCKS * + block_allocator->block_size, + BlockAllocator::ReclaimMode::OPPORTUNISTIC); + block_allocator->FreeInternal(optional_idx(), BlockAllocatorConfig::MAX_FLUSH_BLOCKS, + BlockAllocator::ReclaimMode::OPPORTUNISTIC); + } catch (...) { + // Failed reclamation leaves blocks available for reuse. + } + } + } + bool TryGetBatch(vector &local, BlockQueue &global) { D_ASSERT(local.empty()); local.resize(BlockAllocatorConfig::BATCH_SIZE); - const auto size = global.q.try_dequeue_bulk(local.begin(), BlockAllocatorConfig::BATCH_SIZE); + const auto size = + global.queues.Get(preferred_shard).TryDequeueBulk(local.begin(), BlockAllocatorConfig::BATCH_SIZE); local.resize(size); if (size > 0 && RefersToSameObject(global, *block_allocator->touched)) { - const auto now = RetentionTimeMillis(); - block_allocator->ReuseRetention(size, now); - if (now >= next_decay_check) { - next_decay_check = now + BlockAllocatorConfig::ACTIVE_DECAY_INTERVAL_MS; - try { - block_allocator->FlushAllocationCache(BlockAllocatorConfig::MAX_FLUSH_BLOCKS * - block_allocator->block_size, - BlockAllocator::ReclaimMode::OPPORTUNISTIC); - block_allocator->FreeInternal(optional_idx(), BlockAllocatorConfig::MAX_FLUSH_BLOCKS, - BlockAllocator::ReclaimMode::OPPORTUNISTIC); - } catch (...) { - // Failed reclamation leaves blocks available for reuse. - } - } + OnSharedReuse(size); } std::sort(local.begin(), local.end()); return !local.empty(); @@ -349,6 +505,7 @@ class BlockAllocatorThreadLocalState { shared_ptr lifetime_state; idx_t next_decay_check = 0; idx_t cache_slot = 0; + idx_t preferred_shard = 0; vector untouched; vector touched; @@ -388,25 +545,26 @@ static bool ThreadHasLocalState() { // BlockAllocator //===--------------------------------------------------------------------===// class AllocationCache { - using Queue = duckdb_moodycamel::ConcurrentQueue; static constexpr idx_t MIN_SHIFT = 19; static constexpr idx_t MAX_SHIFT = 32; - static constexpr idx_t MAX_SHARDS = 256; - static constexpr idx_t CPUS_PER_SHARD = 4; static constexpr idx_t MAX_LOCAL_SPARES = 16; // 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 alignas(64) Bucket { - vector queues; - alignas(64) atomic count {0}; + explicit Bucket(idx_t shard_count) : queues(shard_count) { + } + + 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}; }; public: - explicit AllocationCache(Allocator &allocator) : allocator(allocator), shard_count(GetShardCount()) { + explicit AllocationCache(Allocator &allocator) : allocator(allocator), shard_count(AllocatorShardCount()) { for (auto &bucket : buckets) { - bucket.queues.resize(shard_count); + bucket = make_uniq(shard_count); } } ~AllocationCache() { @@ -420,17 +578,18 @@ class AllocationCache { data_ptr_t TryAllocate(idx_t size) { D_ASSERT(SupportsSize(size)); const auto shard = LocalShard(); - auto &bucket = buckets[CountZeros::Trailing(size) - MIN_SHIFT]; + auto &bucket = *buckets[CountZeros::Trailing(size) - MIN_SHIFT]; data_ptr_t pointer; - if (bucket.queues[shard].try_dequeue(pointer)) { + if (bucket.queues.Get(shard).TryDequeue(pointer)) { bucket.count.fetch_sub(1, std::memory_order_relaxed); return 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++) { - auto &queue = bucket.queues[(shard + offset) % shard_count]; - if ((reserve == 0 || queue.size_approx() > reserve) && queue.try_dequeue(pointer)) { + 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; } @@ -439,20 +598,20 @@ class AllocationCache { } bool TryFree(data_ptr_t pointer, idx_t size) { D_ASSERT(SupportsSize(size)); - const auto shard = LocalShard(); if (!pointer) { return false; } - auto &bucket = buckets[CountZeros::Trailing(size) - MIN_SHIFT]; - if (bucket.count.fetch_add(1, std::memory_order_relaxed) < - MaxValue(MAX_CACHED_BYTES_PER_BUCKET / size, 1)) { + const auto shard = 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) { try { const auto now = RetentionTimeMillis(); auto last_return = bucket.last_return_ms.load(std::memory_order_relaxed); while (last_return < now && !bucket.last_return_ms.compare_exchange_weak(last_return, now, std::memory_order_relaxed)) { } - if (bucket.queues[shard].enqueue(pointer)) { + if (bucket.queues.Get(shard).Enqueue(pointer)) { return true; } } catch (...) { @@ -466,11 +625,7 @@ class AllocationCache { idx_t GetCachedMemory(optional_idx idle_before = optional_idx()) const { idx_t bytes = 0; for (idx_t i = 0; i < buckets.size(); i++) { - const auto &bucket = buckets[i]; - if (!idle_before.IsValid() || - bucket.last_return_ms.load(std::memory_order_relaxed) <= idle_before.GetIndex()) { - bytes += bucket.count.load(std::memory_order_relaxed) << (MIN_SHIFT + i); - } + bytes += Reclaimable(*buckets[i], idle_before) * (static_cast(1) << (MIN_SHIFT + i)); } return bytes; } @@ -479,18 +634,15 @@ class AllocationCache { idx_t Flush(idx_t byte_limit, optional_idx idle_before = optional_idx()) { idx_t freed = 0; for (idx_t i = buckets.size(); i > 0 && freed < byte_limit; i--) { - auto &bucket = buckets[i - 1]; + auto &bucket = *buckets[i - 1]; const idx_t size = static_cast(1) << (MIN_SHIFT + i - 1); // A snapshot bounds the work even if producers continue returning buffers. - auto remaining = bucket.count.load(std::memory_order_relaxed); - for (auto &queue : bucket.queues) { + 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; - while (remaining > 0 && freed < byte_limit) { - if (idle_before.IsValid() && - bucket.last_return_ms.load(std::memory_order_relaxed) > idle_before.GetIndex()) { - break; - } - if (!queue.try_dequeue(pointer)) { + while (remaining > 0 && freed < byte_limit && Reclaimable(bucket, idle_before) > 0) { + if (!queue.TryDequeue(pointer)) { break; } allocator.FreeData(pointer, size); @@ -504,37 +656,51 @@ class AllocationCache { } private: - static idx_t GetShardCount() { -#ifndef DUCKDB_NO_THREADS - const idx_t cpus = std::thread::hardware_concurrency(); - return MaxValue(1, MinValue(MAX_SHARDS, (cpus + CPUS_PER_SHARD - 1) / CPUS_PER_SHARD)); -#else - return 1; -#endif + static idx_t Reclaimable(const Bucket &bucket, optional_idx idle_before) { + if (idle_before.IsValid() && bucket.last_return_ms.load(std::memory_order_relaxed) > idle_before.GetIndex()) { + return 0; + } + return bucket.count.load(std::memory_order_relaxed); } +private: idx_t LocalShard() const { - const auto cpu = TaskScheduler::GetEstimatedCPUId(); - return (cpu / CPUS_PER_SHARD) % shard_count; + return AllocatorLocalShard(buckets[0]->queues.Count()); } Allocator &allocator; const idx_t shard_count; - array buckets; + array, MAX_SHIFT - MIN_SHIFT + 1> buckets; }; +idx_t BlockAllocator::GetGuardBlockCount() const { + // Power-of-two blocks of at least 64 KiB align to all supported OS page sizes. + if (touched->blocks_per_shard > 1 && block_size >= 64ULL * 1024) { + return touched->queues.Count() - 1; + } + return 0; +} + +idx_t BlockAllocator::GetUsableBlockCount() const { + return DivBlockSize(pool_size) - GetGuardBlockCount(); +} + BlockAllocator::BlockAllocator(Allocator &allocator_p, const idx_t block_size_p, const idx_t pool_size_p) + : BlockAllocator(allocator_p, block_size_p, pool_size_p, AllocatorShardCount()) { +} + +BlockAllocator::BlockAllocator(Allocator &allocator_p, const idx_t block_size_p, const idx_t pool_size_p, + const idx_t shard_count) : uuid(UUID::GenerateRandomUUID()), allocator(allocator_p), allocation_cache(make_uniq(allocator)), block_size(block_size_p), block_size_div_shift(CountZeros::Trailing(block_size)), pool_size(sizeof(void *) == 8 ? pool_size_p - pool_size_p % block_size : 0), pool_state(pool_size != 0 && DivBlockSize(pool_size) <= NumericLimits::Maximum() ? PoolState::UNINITIALIZED : PoolState::UNAVAILABLE), - touched(make_unsafe_uniq()), lifetime_state(make_shared_ptr()) { - static_assert(std::tuple_size::value == BlockAllocatorConfig::RETENTION_BUCKETS, - "Retention bucket storage must match the decay configuration"); + touched(make_unsafe_uniq(DivBlockSize(pool_size), shard_count)), + lifetime_state(make_shared_ptr()) { D_ASSERT(IsPowerOfTwo(block_size)); - InitializeRetention(RetentionTimeMillis()); + retention.Reset(RetentionTimeMillis()); } BlockAllocator::~BlockAllocator() { @@ -542,7 +708,14 @@ BlockAllocator::~BlockAllocator() { annotated_lock_guard guard(lifetime_state->lock); lifetime_state->alive = false; } - GetBlockAllocatorThreadLocalState(*this).Clear(); + // creating the state of a thread that has none, or re-initializing it for this allocator, allocates + if (ThreadHasLocalState()) { + try { + GetBlockAllocatorThreadLocalState(*this).Clear(); + } catch (...) { + // Not allowed to throw in destructor! + } + } if (IsInitialized()) { try { FreeVirtualMemory(pool_base, pool_size); @@ -588,27 +761,44 @@ bool BlockAllocator::InitializePool() const { unsafe_unique_ptr queue; try { - queue = make_unsafe_uniq(); + queue = make_unsafe_uniq(DivBlockSize(pool_size), touched->queues.Count()); + queue->ReserveOverflow(DivBlockSize(pool_size)); + touched->ReserveOverflow(DivBlockSize(pool_size)); uint32_t block_ids[STANDARD_VECTOR_SIZE]; const auto count = DivBlockSize(pool_size); - for (idx_t block_id = 0; block_id < count; block_id += STANDARD_VECTOR_SIZE) { - const auto next = MinValue(count - block_id, STANDARD_VECTOR_SIZE); - for (idx_t i = 0; i < next; i++) { - block_ids[i] = NumericCast(block_id + i); + const auto guard_block_count = GetGuardBlockCount(); + for (idx_t shard = 0; shard < queue->queues.Count(); shard++) { + const auto start = shard * queue->blocks_per_shard; + auto end = MinValue(count, start + queue->blocks_per_shard); + if (shard < guard_block_count) { + // Skip the last slot: ProtectPoolGuards uses it to separate adjacent shard mappings. + end--; } - if (!queue->q.enqueue_bulk(block_ids, next)) { - pool_state.store(PoolState::UNAVAILABLE, std::memory_order_release); - return false; + for (idx_t block_id = start; block_id < end; block_id += STANDARD_VECTOR_SIZE) { + const auto next = MinValue(end - block_id, STANDARD_VECTOR_SIZE); + for (idx_t i = 0; i < next; i++) { + block_ids[i] = NumericCast(block_id + i); + } + if (!queue->queues.Get(shard).EnqueueBulk(block_ids, next)) { + touched->ReleaseOverflow(); + pool_state.store(PoolState::UNAVAILABLE, std::memory_order_release); + return false; + } } } } catch (const std::bad_alloc &) { + touched->ReleaseOverflow(); pool_state.store(PoolState::UNAVAILABLE, std::memory_order_release); return false; } const auto pointer = AllocateVirtualMemory(pool_size); - if (!pointer) { + if (!pointer || !ProtectPoolGuards(pointer)) { + touched->ReleaseOverflow(); pool_state.store(PoolState::UNAVAILABLE, std::memory_order_release); + if (pointer) { + FreeVirtualMemory(pointer, pool_size); + } return false; } untouched = std::move(queue); @@ -617,6 +807,19 @@ bool BlockAllocator::InitializePool() const { return true; } +bool BlockAllocator::ProtectPoolGuards(data_ptr_t pointer) const { + // Separate writable VMAs reduce contention on Linux's VMA reference counter during page faults. + // That contention can bottleneck first-touch faults and skew NUMA placement toward one node. + const auto guard_block_count = GetGuardBlockCount(); + for (idx_t shard = 0; shard < guard_block_count; shard++) { + const auto guard_block_id = (shard + 1) * touched->blocks_per_shard - 1; + if (!ProtectVirtualMemory(pointer + guard_block_id * block_size, block_size)) { + return false; + } + } + return true; +} + bool BlockAllocator::IsInitialized() const { return pool_state.load(std::memory_order_acquire) == PoolState::READY; } @@ -638,6 +841,10 @@ idx_t BlockAllocator::DivBlockSize(const idx_t n) const { return n >> block_size_div_shift; } +idx_t BlockAllocator::GetLocalPoolShard() const { + return AllocatorLocalShard(touched->queues.Count()); +} + uint32_t BlockAllocator::GetBlockID(const data_ptr_t pointer) const { D_ASSERT(IsInPool(pointer)); const auto offset = NumericCast(pointer - pool_base); @@ -649,6 +856,12 @@ uint32_t BlockAllocator::GetBlockID(const data_ptr_t pointer) const { void BlockAllocator::VerifyBlockID(const uint32_t block_id) const { D_ASSERT(block_id < DivBlockSize(pool_size)); + D_ASSERT(!IsGuardBlock(block_id)); +} + +bool BlockAllocator::IsGuardBlock(const uint32_t block_id) const { + const auto home = touched->Home(block_id); + return home < GetGuardBlockCount() && idx_t(block_id) + 1 == (home + 1) * touched->blocks_per_shard; } data_ptr_t BlockAllocator::GetPointer(const uint32_t block_id) const { @@ -675,7 +888,8 @@ idx_t BlockAllocator::GetCachedMemory() const { idx_t BlockAllocator::GetCachedPoolMemory() const { int64_t count = 0; - const auto slots = MinValue(next_cache_slot.load(std::memory_order_relaxed), cached_blocks.size()); + const auto slots = + MaxValue(1, MinValue(next_cache_slot.load(std::memory_order_relaxed), cached_blocks.size())); for (idx_t i = 0; i < slots; i++) { count += cached_blocks[i].count.load(std::memory_order_relaxed); } @@ -699,6 +913,14 @@ void BlockAllocator::FreeData(const data_ptr_t pointer, const idx_t size) const return; } D_ASSERT(size == block_size); + if (!ThreadHasLocalState()) { + // creating the state of a thread that only frees allocates and registers a thread_local destructor, which + // glibc aborts on when memory is exhausted: hand the block to the global pool directly + UpdateCachedBlocks(1, 0); + retention.Return(1, GetUsableBlockCount(), RetentionTimeMillis()); + touched->Enqueue(GetBlockID(pointer)); + return; + } GetBlockAllocatorThreadLocalState(*this).Free(pointer); } @@ -713,7 +935,7 @@ data_ptr_t BlockAllocator::ReallocateData(const data_ptr_t pointer, const idx_t return RetryAfterReclaiming(*this, [&] { return allocator.ReallocateData(pointer, old_size, new_size); }); } - // Either old or new can be in the pool: allocate, copy, and free + // Pool allocations must retain their matching allocation/release paths. const auto new_pointer = AllocateData(new_size); memcpy(new_pointer, pointer, MinValue(old_size, new_size)); FreeData(pointer, old_size); @@ -903,7 +1125,7 @@ void BlockAllocator::ThreadExit() const { } idx_t BlockAllocator::GetFreeBlockCount() const { - return touched->q.size_approx(); + return touched->SizeApprox(); } idx_t BlockAllocator::GetReclaimableBlockCount(const ReclaimMode mode, const optional_idx cache_limit) const { @@ -916,7 +1138,7 @@ idx_t BlockAllocator::GetReclaimableBlockCount(const ReclaimMode mode, const opt if (mode == ReclaimMode::FORCE) { return available; } - return available - MinValue(available, RetentionTarget(RetentionTimeMillis())); + return available - MinValue(available, retention.Target(RetentionTimeMillis())); } idx_t BlockAllocator::FlushPool(const optional_idx block_limit, const optional_idx task_limit, const ReclaimMode mode, @@ -932,7 +1154,7 @@ idx_t BlockAllocator::FlushPool(const optional_idx block_limit, const optional_i static idx_t AllocationCacheIdleCutoff() { const auto now = RetentionTimeMillis(); - return now - MinValue(now, BlockAllocatorConfig::RETENTION_DECAY_MS); + return now - MinValue(now, AllocatorCacheRetention::DECAY_MS); } bool BlockAllocator::HasReclaimableMemory() const { @@ -962,8 +1184,8 @@ idx_t BlockAllocator::FlushAllocationCache(idx_t byte_limit, ReclaimMode mode) c idx_t BlockAllocator::TrimCachedMemory(idx_t memory_headroom, optional_idx pool_block_limit) const noexcept { const auto cached = allocation_cache->GetCachedMemory(); // Avoid reading the fixed pool's per-thread counters when even its capacity fits. - if (cached <= memory_headroom && - (pool_size <= memory_headroom - cached || GetCachedPoolMemory() <= memory_headroom - cached)) { + if (cached <= memory_headroom && (GetUsableBlockCount() * block_size <= memory_headroom - cached || + GetCachedPoolMemory() <= memory_headroom - cached)) { return 0; } idx_t freed = 0; @@ -1080,7 +1302,15 @@ idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optiona if (eligible == 0) { return 0; } - count = touched->q.try_dequeue_bulk(to_free_buffer.begin(), MinValue(eligible, batch_size)); + count = 0; + for (idx_t attempt = 0; attempt < touched->queues.Count(); attempt++) { + auto &queue = touched->queues.Get(reclaim_shard); + reclaim_shard = (reclaim_shard + 1) % touched->queues.Count(); + count = queue.TryDequeueBulk(to_free_buffer.begin(), MinValue(eligible, batch_size)); + if (count > 0) { + break; + } + } reclaiming_blocks += count; } if (count == 0) { @@ -1100,9 +1330,9 @@ idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optiona if (!FreeContiguousBlocks(to_free_buffer[start], to_free_buffer[end - 1])) { annotated_lock_guard guard(flush_lock); reclaiming_blocks -= count - start; - touched->q.enqueue_bulk(to_free_buffer.begin() + - NumericCast::difference_type>(start), - count - start); + touched->EnqueueBulk(to_free_buffer.begin() + + NumericCast::difference_type>(start), + count - start); return 0; } { @@ -1110,7 +1340,7 @@ idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optiona UpdateCachedBlocks(-NumericCast(end - start), 0); reclaiming_blocks -= end - start; } - untouched->q.enqueue_bulk( + untouched->EnqueueBulk( to_free_buffer.begin() + NumericCast::difference_type>(start), end - start); start = end; } @@ -1119,6 +1349,8 @@ idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optiona } bool BlockAllocator::FreeContiguousBlocks(const uint32_t block_id_start, const uint32_t block_id_end_including) const { + VerifyBlockID(block_id_end_including); + D_ASSERT(touched->Home(block_id_start) == touched->Home(block_id_end_including)); const auto pointer = GetPointer(block_id_start); const auto num_blocks = block_id_end_including - block_id_start + 1; const auto size = num_blocks * block_size; diff --git a/src/duckdb/src/storage/buffer/buffer_pool.cpp b/src/duckdb/src/storage/buffer/buffer_pool.cpp index fb9e16443..1c717703e 100644 --- a/src/duckdb/src/storage/buffer/buffer_pool.cpp +++ b/src/duckdb/src/storage/buffer/buffer_pool.cpp @@ -10,6 +10,8 @@ #include "duckdb/storage/object_cache.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" +#include + namespace duckdb { static idx_t FileBufferTypeToEvictionQueueTypeIdx(const FileBufferType &type) { @@ -270,8 +272,7 @@ void EvictionQueue::PurgeIteration(const idx_t purge_size) { total_dead_nodes -= dead_count; - // Re-enqueue alive nodes via producer token — goes into a dedicated sub-queue - // that the consumer token has already passed + // Re-enqueue alive nodes into the purge producer's dedicated sub-queue. if (alive_count > 0) { #ifdef DUCKDB_NO_THREADS // The fallback queue can throw after publishing a prefix of a bulk insertion. @@ -286,7 +287,9 @@ void EvictionQueue::PurgeIteration(const idx_t purge_size) { } } #else - if (!purge_producer_token.valid() || !q.enqueue_bulk(purge_producer_token, purge_nodes.begin(), alive_count)) { + // A failed bulk enqueue leaves the input nodes untouched. + if (!purge_producer_token.valid() || + !q.enqueue_bulk(purge_producer_token, std::make_move_iterator(purge_nodes.begin()), alive_count)) { for (idx_t i = 0; i < alive_count; i++) { DiscardNode(purge_nodes[i]); } @@ -320,9 +323,10 @@ bool BufferPool::AddToEvictionQueue(BlockLock &lock, shared_ptr &ha // (uncontended) lock of the freshly created block before calling. memory.VerifyMutex(lock); D_ASSERT(memory.GetReaders() == 0); - // Repeated hash-table appends can reuse an entry while leaving the block evictable. + // Reusing the entry keeps a stale queue position, so a block in active use can be evicted earlier under pressure. + const auto tag = memory.GetMemoryTag(); if (!track_eviction_timestamps && memory.GetBufferType() == FileBufferType::MANAGED_BUFFER && - memory.GetMemoryTag() == MemoryTag::HASH_TABLE && memory.HasLiveQueueEntry(lock)) { + (tag == MemoryTag::HASH_TABLE || tag == MemoryTag::PARQUET_READER) && memory.HasLiveQueueEntry(lock)) { return false; } auto &queue = GetEvictionQueueForBlockMemory(memory); diff --git a/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp b/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp index 068386f23..818f07456 100644 --- a/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp +++ b/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp @@ -144,6 +144,7 @@ void WriteOverflowStringsToDisk::AllocateNewBlock(UncompressedStringSegmentState } offset = 0; block_id = new_block_id; + memset(handle.GetDataMutable() + GetStringSpace(), 0, sizeof(block_id_t)); auto &block_manager = partial_block_manager.GetBlockManager(); state.RegisterBlock(block_manager, new_block_id); } diff --git a/src/duckdb/src/storage/checkpoint_manager.cpp b/src/duckdb/src/storage/checkpoint_manager.cpp index bb58e20ae..e9ce2b29e 100644 --- a/src/duckdb/src/storage/checkpoint_manager.cpp +++ b/src/duckdb/src/storage/checkpoint_manager.cpp @@ -24,7 +24,6 @@ #include "duckdb/execution/index/unbound_index.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/client_context.hpp" -#include "duckdb/main/connection.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/parser/parsed_data/create_schema_info.hpp" #include "duckdb/planner/binder.hpp" @@ -39,21 +38,15 @@ #include "duckdb/transaction/duck_transaction_manager.hpp" #include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/transaction/transaction_manager.hpp" -#include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/parser/parsed_data/create_view_info.hpp" #include "duckdb/main/database.hpp" namespace duckdb { -ActiveCheckpointWrapper::ActiveCheckpointWrapper(Context &context, AttachedDatabase &db_p, - DuckTransactionManager &transaction_manager_p) - : db(db_p), transaction_manager(transaction_manager_p) { - if (!context.IsClient()) { - return; - } - checkpoint_connection = make_uniq(Connection::CreateInternal(db.GetDatabase())); - checkpoint_context = checkpoint_connection->context.get(); +ActiveCheckpointWrapper::ActiveCheckpointWrapper(optional_ptr checkpoint_context_p, + AttachedDatabase &db_p, DuckTransactionManager &transaction_manager_p) + : db(db_p), transaction_manager(transaction_manager_p), checkpoint_context(checkpoint_context_p) { } ActiveCheckpointWrapper::~ActiveCheckpointWrapper() { @@ -99,14 +92,10 @@ void ActiveCheckpointWrapper::Commit() { checkpoint_transaction = nullptr; } -optional_ptr ActiveCheckpointWrapper::GetCheckpointContext() const { - return checkpoint_context; -} - CheckpointWriter::CheckpointWriter(AttachedDatabase &db_p, QueryContext query_context, - optional_ptr client_context_p) - : db(db_p), owned_context(query_context.Valid() ? nullptr : db_p.GetDatabase().Services()), - context(query_context.Valid() ? *query_context.GetContext() : *owned_context), client_context(client_context_p) { + optional_ptr checkpoint_context_p) + : db(db_p), context(query_context.Valid() ? *query_context.GetContext() : db_p.GetDatabase().GetContext()), + checkpoint_context(checkpoint_context_p) { } CheckpointWriter::~CheckpointWriter() { @@ -116,8 +105,8 @@ void ReorderTableEntries(catalog_entry_vector_t &tables); SingleFileCheckpointWriter::SingleFileCheckpointWriter(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, CheckpointOptions options_p, - optional_ptr client_context) - : CheckpointWriter(db, context, client_context), + optional_ptr checkpoint_context) + : CheckpointWriter(db, context, checkpoint_context), partial_block_manager(GetContext(), block_manager, PartialBlockType::FULL_CHECKPOINT), options(options_p) { } @@ -234,25 +223,6 @@ static catalog_entry_vector_t GetCatalogEntries(vector(); - catalog.ScanSchemas(VisibilityBound::AllCommitted(), [&](DuckSchemaEntry &schema) { - if (has_buffered_replays) { - return; - } - schema.Scan(CatalogType::TABLE_ENTRY, VisibilityBound::AllCommitted(), [&](CatalogEntry &entry) { - if (has_buffered_replays || entry.type != CatalogType::TABLE_ENTRY) { - return; - } - auto &table = entry.Cast(); - auto &indexes = table.GetStorage().GetDataTableInfo()->GetIndexes(); - has_buffered_replays = indexes.HasBufferedReplays(); - }); - }); - return has_buffered_replays; -} - void SingleFileCheckpointWriter::CreateCheckpoint() { auto &storage_manager = db.GetStorageManager().Cast(); if (storage_manager.InMemory()) { @@ -262,10 +232,6 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { // don't checkpoint invalidated databases return; } - // A context-free checkpoint cannot persist buffered operations on an unbound index. Keep the WAL instead. - if (!GetContext().IsClient() && HasBufferedIndexReplays(db)) { - return; - } // assert that the checkpoint manager hasn't been used before D_ASSERT(!metadata_writer); @@ -290,11 +256,9 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { // to replay any concurrent commits that have succeeded and ensure these are not lost auto &transaction_manager = db.GetTransactionManager().Cast(); - // If there is a context (non shutdown path): this will create a new connection for the checkpoint, then in - // WALStartCheckpoint we will create a transaction for the checkpoint. - ActiveCheckpointWrapper active_checkpoint(GetContext(), db, transaction_manager); + // If there is a checkpoint context (non shutdown path), WALStartCheckpoint creates the checkpoint transaction. + ActiveCheckpointWrapper active_checkpoint(checkpoint_context, db, transaction_manager); auto has_wal = storage_manager.WALStartCheckpoint(meta_block, options, active_checkpoint); - checkpoint_context = active_checkpoint.GetCheckpointContext(); catalog_entry_vector_t catalog_entries; @@ -359,6 +323,12 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { throw IOException("Checkpoint aborted before header write (non-fatal) because of PRAGMA checkpoint_abort flag"); } + // a concurrent commit may have invalidated the database: do not publish the checkpoint + auto invalidation_error = db.InvalidationError("checkpoint"); + if (invalidation_error.HasError()) { + invalidation_error.Throw(); + } + // finally write the updated header DatabaseHeader header; header.meta_block = meta_block.block_pointer; @@ -440,7 +410,6 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { auto &index_list = table_info->GetIndexes(); index_list.MergeCheckpointDeltas(options.checkpoint_id); } - checkpoint_context = nullptr; active_checkpoint.Commit(); } @@ -769,18 +738,6 @@ void SingleFileCheckpointWriter::WriteTable(TableCatalogEntry &table, Serializer // Write the table metadata serializer.WriteProperty(100, "table", &table); - // Explicit checkpoints bind indexes before serialization, so that buffered index operations are replayed - // and not lost on a restart. Only explicit checkpoints have a client context. - if (TryGetClientContext() && checkpoint_context) { - D_ASSERT(checkpoint_context->transaction.HasActiveTransaction()); - // Bind indexes with checkpoint transaction, which is already running and read-only, so any transaction the - // binder still starts skips start_transaction_lock. - D_ASSERT(MetaTransaction::Get(*checkpoint_context).IsReadOnly()); - auto &info = table.GetStorage().GetDataTableInfo(); - info->BindIndexes(*checkpoint_context); - } - // FIXME: If we do not have a context, however, the unbound indexes have to be serialized to disk. - // Write the table data auto writer = GetTableDataWriter(table); if (writer) { diff --git a/src/duckdb/src/storage/compression/alp/alp.cpp b/src/duckdb/src/storage/compression/alp/alp.cpp index dc9b6e87a..4456a98ad 100644 --- a/src/duckdb/src/storage/compression/alp/alp.cpp +++ b/src/duckdb/src/storage/compression/alp/alp.cpp @@ -52,18 +52,22 @@ CompressionFunction GetAlpFunction(PhysicalType data_type) { template <> CompressionFunction GetAlpFunction(PhysicalType data_type) { - return CompressionFunction(CompressionType::COMPRESSION_ALP, data_type, AlpInitAnalyze, AlpAnalyze, + CompressionFunction result(CompressionType::COMPRESSION_ALP, data_type, AlpInitAnalyze, AlpAnalyze, AlpFinalAnalyze, AlpInitCompression, AlpCompress, AlpFinalizeCompress, AlpInitScan, AlpScan, AlpScanPartial, AlpSkip); + result.zero_initialize_segments = false; + return result; } template <> CompressionFunction GetAlpFunction(PhysicalType data_type) { - return CompressionFunction(CompressionType::COMPRESSION_ALP, data_type, AlpInitAnalyze, AlpAnalyze, + CompressionFunction result(CompressionType::COMPRESSION_ALP, data_type, AlpInitAnalyze, AlpAnalyze, AlpFinalAnalyze, AlpInitCompression, AlpCompress, AlpFinalizeCompress, AlpInitScan, AlpScan, AlpScanPartial, AlpSkip); + result.zero_initialize_segments = false; + return result; } CompressionFunction AlpCompressionFun::GetFunction(PhysicalType type) { diff --git a/src/duckdb/src/storage/compression/alprd.cpp b/src/duckdb/src/storage/compression/alprd.cpp index f29effd71..e5e2b14c2 100644 --- a/src/duckdb/src/storage/compression/alprd.cpp +++ b/src/duckdb/src/storage/compression/alprd.cpp @@ -54,18 +54,22 @@ CompressionFunction GetAlpRDFunction(PhysicalType data_type) { template <> CompressionFunction GetAlpRDFunction(PhysicalType data_type) { - return CompressionFunction(CompressionType::COMPRESSION_ALPRD, data_type, AlpRDInitAnalyze, + CompressionFunction result(CompressionType::COMPRESSION_ALPRD, data_type, AlpRDInitAnalyze, AlpRDAnalyze, AlpRDFinalAnalyze, AlpRDInitCompression, AlpRDCompress, AlpRDFinalizeCompress, AlpRDInitScan, AlpRDScan, AlpRDScanPartial, AlpRDSkip); + result.zero_initialize_segments = false; + return result; } template <> CompressionFunction GetAlpRDFunction(PhysicalType data_type) { - return CompressionFunction(CompressionType::COMPRESSION_ALPRD, data_type, AlpRDInitAnalyze, + CompressionFunction result(CompressionType::COMPRESSION_ALPRD, data_type, AlpRDInitAnalyze, AlpRDAnalyze, AlpRDFinalAnalyze, AlpRDInitCompression, AlpRDCompress, AlpRDFinalizeCompress, AlpRDInitScan, AlpRDScan, AlpRDScanPartial, AlpRDSkip); + result.zero_initialize_segments = false; + return result; } CompressionFunction AlpRDCompressionFun::GetFunction(PhysicalType type) { diff --git a/src/duckdb/src/storage/compression/bitpacking.cpp b/src/duckdb/src/storage/compression/bitpacking.cpp index 4bae820d8..1dffb2f4f 100644 --- a/src/duckdb/src/storage/compression/bitpacking.cpp +++ b/src/duckdb/src/storage/compression/bitpacking.cpp @@ -311,6 +311,16 @@ struct BitpackingState { return true; } + // values in compression_buffer are not overwritten when they are invalid, so set them to minimum such that they + // are packed as 0 instead. + if (has_invalid && has_valid) { + for (idx_t i = 0; i < compression_buffer_idx; i++) { + if (!compression_buffer_validity[i]) { + compression_buffer[i] = minimum; + } + } + } + CalculateFORStats(); CalculateDeltaStats(); @@ -787,6 +797,17 @@ struct BitpackingScanState : public SegmentScanState { idx_t segment_count; T decompression_buffer[BITPACKING_METADATA_GROUP_SIZE]; + //! Scratch space for dense selections, which scan the whole range before gathering the selected rows. + unsafe_unique_array select_buffer; + idx_t select_buffer_capacity = 0; + + T *GetSelectBuffer(idx_t count) { + if (count > select_buffer_capacity) { + select_buffer = make_unsafe_uniq_array_uninitialized(count); + select_buffer_capacity = count; + } + return select_buffer.get(); + } //! Group count derived from the segment row count read from disk. idx_t group_count; @@ -1034,16 +1055,11 @@ unique_ptr BitpackingInitScan(const QueryContext &context, Col // Scan base data //===--------------------------------------------------------------------===// template ::type, class T_U = typename MakeUnsigned::type> -void BitpackingScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, - idx_t result_offset) { - auto &scan_state = state.scan_state->Cast>(); +void BitpackingScanData(BitpackingScanState &scan_state, idx_t scan_count, T *result_data, idx_t result_offset) { if (scan_count == 0) { return; } - T *result_data = FlatVector::GetDataMutable(result); - result.SetVectorType(VectorType::FLAT_VECTOR); - if (scan_state.IsInitial()) { scan_state.LoadGroup(0); } @@ -1134,6 +1150,15 @@ void BitpackingScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t } } +template +void BitpackingScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, + idx_t result_offset) { + auto &scan_state = state.scan_state->Cast>(); + T *result_data = FlatVector::GetDataMutable(result); + result.SetVectorType(VectorType::FLAT_VECTOR); + BitpackingScanData(scan_state, scan_count, result_data, result_offset); +} + template void BitpackingScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result) { BitpackingScanPartial(segment, state, scan_count, result, 0); @@ -1142,6 +1167,46 @@ void BitpackingScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_c //===--------------------------------------------------------------------===// // Select //===--------------------------------------------------------------------===// +template +static bool BitpackingSelectIsDense(BitpackingScanState &scan_state, idx_t vector_count, const SelectionVector &sel, + idx_t sel_count) { + static constexpr idx_t GROUP_SIZE = BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; + // load the group the selection starts in, so that its mode is known + if (scan_state.IsInitial()) { + scan_state.LoadGroup(0); + } else if (scan_state.HasCurrentGroup() && scan_state.GetCurrentGroup().AtEnd() && + scan_state.GetCurrentGroup().index + 1 < scan_state.group_count) { + scan_state.LoadGroup(scan_state.GetCurrentGroup().index + 1); + } + idx_t base = 0; + if (scan_state.HasCurrentGroup()) { + auto ¤t = scan_state.GetCurrentGroup(); + if (!current.AtEnd() && (current.metadata.mode == BitpackingMode::CONSTANT || + current.metadata.mode == BitpackingMode::CONSTANT_DELTA)) { + // constant modes compute selected rows directly + return false; + } + base = current.offset % GROUP_SIZE; + } + 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) { + return false; + } + idx_t touched_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) { + return true; + } + } + } + return false; +} + template ::type> void BitpackingSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, const SelectionVector &sel, idx_t sel_count, idx_t result_offset, ScanVectorType scan_type) { @@ -1149,6 +1214,18 @@ 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 + if (BitpackingSelectIsDense(scan_state, vector_count, sel, sel_count)) { + auto scanned = scan_state.GetSelectBuffer(vector_count); + BitpackingScanData(scan_state, vector_count, scanned, 0); + for (idx_t i = 0; i < sel_count; i++) { + const idx_t index = sel.get_index(i); + D_ASSERT(index < vector_count); + result_data[i] = scanned[index]; + } + return; + } + idx_t previous_index = 0; auto next_index = [&](idx_t sel_idx) { const idx_t index = sel.get_index(sel_idx); @@ -1164,8 +1241,19 @@ void BitpackingSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vect while (i < sel_count) { const idx_t target = next_index(i); D_ASSERT(target >= pos && target < vector_count); - scan_state.Skip(target - pos); - pos = target; + idx_t skip_target = target; + if (scan_state.HasCurrentGroup()) { + auto ¤t = scan_state.GetCurrentGroup(); + if (current.metadata.mode == BitpackingMode::DELTA_FOR && !current.AtEnd() && + target - pos < current.Remaining()) { + // stop at the target's algorithm group: the prefix sum below covers the rows before the target + const idx_t target_in_algorithm_group = + (current.offset + (target - pos)) % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; + skip_target = target - MinValue(target_in_algorithm_group, target - pos); + } + } + scan_state.Skip(skip_target - pos); + pos = skip_target; if (!scan_state.HasCurrentGroup()) { ThrowBitpackingReadPastEnd(); } @@ -1227,6 +1315,11 @@ void BitpackingSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vect } result_data[i] = static_cast(carry); } + // finish the unpacked algorithm group so that the next Skip does not decode it again + const idx_t unpacked_end = MinValue(run_end, vector_count); + for (; cur < unpacked_end; cur++) { + carry += deltas[cur - pos] + frame; + } if (scan_state.is_bool) { VerifyBooleanValues(result_data + first, i - first); } @@ -1298,6 +1391,7 @@ CompressionFunction GetBitpackingFunction(PhysicalType data_type) { BitpackingScan, BitpackingScanPartial, BitpackingSkip); bitpacking.select = BitpackingSelect; bitpacking.get_segment_info = BitpackingGetSegmentInfo; + bitpacking.zero_initialize_segments = false; return bitpacking; } diff --git a/src/duckdb/src/storage/compression/dict_fsst.cpp b/src/duckdb/src/storage/compression/dict_fsst.cpp index 2779ec801..4c1e3dd67 100644 --- a/src/duckdb/src/storage/compression/dict_fsst.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst.cpp @@ -285,6 +285,7 @@ CompressionFunction DictFSSTCompressionFun::GetFunction(PhysicalType data_type) res.select = dict_fsst::DictFSSTSelect; res.filter = dict_fsst::DictFSSTFilter; res.get_segment_info = dict_fsst::DictFSSTGetSegmentInfo; + res.zero_initialize_segments = false; return res; } diff --git a/src/duckdb/src/storage/compression/dict_fsst/compression.cpp b/src/duckdb/src/storage/compression/dict_fsst/compression.cpp index 7293199fa..655a1fcfd 100644 --- a/src/duckdb/src/storage/compression/dict_fsst/compression.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst/compression.cpp @@ -97,6 +97,14 @@ idx_t DictFSSTCompressionState::Finalize() { auto string_lengths_dest = AlignValue(symbol_table_dest + symbol_table_size); auto dictionary_indices_dest = AlignValue(string_lengths_dest + string_lengths_space); + auto clear_gap = [&](idx_t start, idx_t end) { + memset(base_ptr + start, 0, end - start); + }; + clear_gap(0, dictionary_dest); + clear_gap(dictionary_dest + dictionary_offset, symbol_table_dest); + clear_gap(symbol_table_dest + symbol_table_size, string_lengths_dest); + clear_gap(string_lengths_dest + string_lengths_space, dictionary_indices_dest); + header_ptr->mode = ConvertToMode(append_state); header_ptr->symbol_table_size = NumericCast(symbol_table_size); header_ptr->dict_size = NumericCast(dictionary_offset); diff --git a/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp b/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp index dd0e3c244..70fa24ccf 100644 --- a/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp @@ -290,6 +290,7 @@ CompressionFunction FixedSizeGetFunction(PhysicalType data_type) { FixedSizeScan, FixedSizeScanPartial, UncompressedFunctions::EmptySkip, nullptr, FixedSizeInitAppend, FixedSizeAppend, FixedSizeFinalizeAppend); function.select = FixedSizeSelect; + function.zero_initialize_segments = false; return function; } diff --git a/src/duckdb/src/storage/compression/rle.cpp b/src/duckdb/src/storage/compression/rle.cpp index 1af50e02f..4cb9c1efd 100644 --- a/src/duckdb/src/storage/compression/rle.cpp +++ b/src/duckdb/src/storage/compression/rle.cpp @@ -290,15 +290,13 @@ struct RLEScanState : public SegmentScanState { //! Validate enough runs to cover every row in the segment. idx_t ValidateAllRuns() { - while (unvalidated_row_count > 0) { - ValidateThrough(validated_entry_count); - } + ValidateUntil(0); return validated_entry_count; } - //! Validate through entry_index and return that run. - ValidatedRun ValidateAndGetRun(idx_t entry_index) { - ValidateThrough(entry_index); + //! Read a run covered by the range validated before scanning, selecting or skipping. + ValidatedRun GetValidatedRun(idx_t entry_index) const { + D_ASSERT(entry_index < validated_entry_count); return {values[entry_index], run_counts[entry_index]}; } @@ -312,22 +310,41 @@ struct RLEScanState : public SegmentScanState { return entry_capacity; } - private: - //! Validate through entry_index without advancing the scan. - void ValidateThrough(idx_t entry_index) { - while (validated_entry_count <= entry_index) { - if (validated_entry_count >= entry_capacity) { - ThrowRLERunCountArrayExhausted(); + //! Validate through the requested remaining-row count before decoding. + void ValidateUntil(idx_t remaining) { + static constexpr idx_t BATCH_SIZE = 32; + while (unvalidated_row_count > remaining && entry_capacity - validated_entry_count >= BATCH_SIZE) { + uint32_t batch_count = 0; + for (idx_t i = 0; i < BATCH_SIZE; i++) { + batch_count += run_counts[validated_entry_count + i]; } - auto run_count = run_counts[validated_entry_count]; - if (run_count > unvalidated_row_count) { - ThrowRLERunCountExceedsRemaining(run_count, unvalidated_row_count); + // Counts are unsigned 16-bit values, so their sum fits in uint32_t. If the entire + // batch ends before the requested row, every prefix fits in the remaining segment. + // At the boundary, validate individually to stop at the same run, including zeros. + if (batch_count >= unvalidated_row_count - remaining) { + break; } - unvalidated_row_count -= run_count; - validated_entry_count++; + unvalidated_row_count -= batch_count; + validated_entry_count += BATCH_SIZE; + } + while (unvalidated_row_count > remaining) { + ValidateNextRun(); } } + private: + void ValidateNextRun() { + if (validated_entry_count >= entry_capacity) { + ThrowRLERunCountArrayExhausted(); + } + auto run_count = run_counts[validated_entry_count]; + if (run_count > unvalidated_row_count) { + ThrowRLERunCountExceedsRemaining(run_count, unvalidated_row_count); + } + unvalidated_row_count -= run_count; + validated_entry_count++; + } + //! Values read from the segment between RLE_HEADER_SIZE and rle_count_offset. unsafe_array_ptr values; //! Run counts read from the segment between rle_count_offset and the segment end. @@ -360,10 +377,10 @@ struct RLEScanState : public SegmentScanState { layout(ReadSegmentLayout(handle, segment, segment_count)), entry_pos(0), position_in_entry(0) { } - //! Advances past empty entries while validating the current run. - ValidatedRun ValidateAndGetCurrentRun() { + //! Advances past empty entries within the validated range. + ValidatedRun GetCurrentRun() { while (true) { - auto run = layout.ValidateAndGetRun(entry_pos); + auto run = layout.GetValidatedRun(entry_pos); if (run.length != 0) { return run; } @@ -374,7 +391,7 @@ struct RLEScanState : public SegmentScanState { inline void SkipInternal(idx_t skip_count) { while (skip_count > 0) { - auto run_count = ValidateAndGetCurrentRun().length; + auto run_count = GetCurrentRun().length; D_ASSERT(position_in_entry < run_count); idx_t skip_amount = MinValue(skip_count, run_count - position_in_entry); @@ -394,9 +411,7 @@ struct RLEScanState : public SegmentScanState { // handled all entries in this RLE value // move to the next entry entry_pos++; - if (entry_pos > layout.GetEntryCapacity()) { - ThrowRLERunCountArrayExhausted(); - } + D_ASSERT(entry_pos <= layout.GetEntryCapacity()); position_in_entry = 0; } @@ -428,9 +443,10 @@ unique_ptr RLEInitScan(const QueryContext &context, ColumnSegm //===--------------------------------------------------------------------===// template void RLESkip(ColumnSegment &segment, ColumnScanState &state, idx_t skip_count) { - D_ASSERT(state.GetPositionInSegment() <= segment.count); - D_ASSERT(skip_count <= state.GetPositionInSegment()); auto &scan_state = state.scan_state->Cast>(); + D_ASSERT(state.GetPositionInSegment() <= scan_state.segment_count); + D_ASSERT(skip_count <= state.GetPositionInSegment()); + scan_state.layout.ValidateUntil(scan_state.segment_count - state.GetPositionInSegment()); scan_state.Skip(segment, skip_count); } @@ -466,12 +482,13 @@ static void RLEScanConstant(RLEScanState &scan_state, const typename RLEScanS template void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset) { - D_ASSERT(state.GetPositionInSegment() <= segment.count); - D_ASSERT(scan_count <= segment.count - state.GetPositionInSegment()); auto &scan_state = state.scan_state->Cast>(); + D_ASSERT(state.GetPositionInSegment() <= scan_state.segment_count); + D_ASSERT(scan_count <= scan_state.segment_count - state.GetPositionInSegment()); + scan_state.layout.ValidateUntil(scan_state.segment_count - state.GetPositionInSegment() - scan_count); // If we are scanning an entire Vector and it contains only a single run - auto current_run = scan_state.ValidateAndGetCurrentRun(); + auto current_run = scan_state.GetCurrentRun(); if (scan_state.position_in_entry < current_run.length && CanEmitConstantVector(scan_state.position_in_entry, current_run.length, scan_count)) { RLEScanConstant(scan_state, current_run, scan_count, result); @@ -482,7 +499,8 @@ void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_ const idx_t result_end = result_offset + scan_count; while (result_offset < result_end) { - auto run = scan_state.ValidateAndGetCurrentRun(); + // 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; idx_t remaining_scan_count = result_end - result_offset; T element = run.value; @@ -521,9 +539,12 @@ template void RLESelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, const SelectionVector &sel, idx_t sel_count, idx_t result_offset, ScanVectorType scan_type) { auto &scan_state = state.scan_state->Cast>(); + D_ASSERT(state.GetPositionInSegment() <= scan_state.segment_count); + D_ASSERT(vector_count <= scan_state.segment_count - state.GetPositionInSegment()); + scan_state.layout.ValidateUntil(scan_state.segment_count - state.GetPositionInSegment() - vector_count); // If we are scanning an entire Vector and it contains only a single run we don't need to select at all - auto current_run = scan_state.ValidateAndGetCurrentRun(); + auto current_run = scan_state.GetCurrentRun(); if (scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR && scan_state.position_in_entry < current_run.length && CanEmitConstantVector(scan_state.position_in_entry, current_run.length, vector_count)) { RLEScanConstant(scan_state, current_run, vector_count, result); @@ -543,7 +564,7 @@ void RLESelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun D_ASSERT(next_idx < vector_count); while (next_idx >= run_end) { scan_state.ForwardToNextRun(); - current_run = scan_state.ValidateAndGetCurrentRun(); + current_run = scan_state.GetCurrentRun(); run_end += current_run.length; } result_data.WriteValue(current_run.value); @@ -604,7 +625,7 @@ void RLEFilter(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun idx_t result_offset = 0; idx_t result_end = sel_count; while (result_offset < result_end) { - auto run = scan_state.ValidateAndGetCurrentRun(); + 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 @@ -643,7 +664,7 @@ void RLEFilter(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun // skip forward to the next index scan_state.SkipInternal(read_idx - prev_idx); prev_idx = read_idx; - auto run = scan_state.ValidateAndGetCurrentRun(); + 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; @@ -668,11 +689,13 @@ void RLEFilter(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun //===--------------------------------------------------------------------===// template CompressionFunction GetRLEFunction(PhysicalType data_type) { - return CompressionFunction(CompressionType::COMPRESSION_RLE, data_type, RLEInitAnalyze, RLEAnalyze, + CompressionFunction result(CompressionType::COMPRESSION_RLE, data_type, RLEInitAnalyze, RLEAnalyze, RLEFinalAnalyze, RLEInitCompression, RLECompress, RLEFinalizeCompress, RLEInitScan, RLEScan, RLEScanPartial, RLESkip, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, RLESelect, RLEFilter); + result.zero_initialize_segments = false; + return result; } CompressionFunction RLEFun::GetFunction(PhysicalType type) { diff --git a/src/duckdb/src/storage/compression/roaring/common.cpp b/src/duckdb/src/storage/compression/roaring/common.cpp index 597d206c1..c6045409a 100644 --- a/src/duckdb/src/storage/compression/roaring/common.cpp +++ b/src/duckdb/src/storage/compression/roaring/common.cpp @@ -308,10 +308,12 @@ CompressionFunction GetCompressionFunction(PhysicalType data_type) { default: throw InternalException("Roaring GetCompressionFunction, type %s not handled", EnumUtil::ToString(data_type)); } - return CompressionFunction(CompressionType::COMPRESSION_ROARING, data_type, roaring::RoaringInitAnalyze, analyze, + CompressionFunction result(CompressionType::COMPRESSION_ROARING, data_type, roaring::RoaringInitAnalyze, analyze, roaring::RoaringFinalAnalyze, roaring::RoaringInitCompression, compress, roaring::RoaringFinalizeCompress, roaring::RoaringInitScan, scan, scan_partial, roaring::RoaringSkip, roaring::RoaringInitSegment); + result.zero_initialize_segments = false; + return result; } CompressionFunction RoaringCompressionFun::GetFunction(PhysicalType type) { diff --git a/src/duckdb/src/storage/compression/roaring/compress.cpp b/src/duckdb/src/storage/compression/roaring/compress.cpp index 888e05d67..c9fa1083f 100644 --- a/src/duckdb/src/storage/compression/roaring/compress.cpp +++ b/src/duckdb/src/storage/compression/roaring/compress.cpp @@ -11,6 +11,14 @@ namespace duckdb { +//! Align the pointer and clear the skipped bytes +template +static data_ptr_t AlignAndClearPadding(data_ptr_t ptr) { + auto aligned = AlignPointer(ptr); + memset(ptr, 0, NumericCast(aligned - ptr)); + return aligned; +} + namespace roaring { ContainerCompressionState::ContainerCompressionState() { @@ -107,7 +115,7 @@ void ContainerCompressionState::OverrideArray(data_ptr_t &destination, bool null auto data_start = destination + sizeof(uint8_t) * COMPRESSED_SEGMENT_COUNT; compressed_arrays[nulls] = reinterpret_cast(data_start); } else { - destination = AlignPointer(destination); + destination = AlignAndClearPadding(destination); arrays[nulls] = reinterpret_cast(destination); } } @@ -121,7 +129,7 @@ void ContainerCompressionState::OverrideRun(data_ptr_t &destination, idx_t count auto data_start = destination + sizeof(uint8_t) * COMPRESSED_SEGMENT_COUNT; compressed_runs = reinterpret_cast(data_start); } else { - destination = AlignPointer(destination); + destination = AlignAndClearPadding(destination); runs = reinterpret_cast(destination); } } @@ -271,7 +279,7 @@ void RoaringCompressState::InitializeContainer() { // Override the pointer to write directly into the block if (metadata.IsUncompressed()) { - data_ptr = reinterpret_cast(AlignValue(reinterpret_cast(data_ptr))); + data_ptr = AlignAndClearPadding(data_ptr); memset(data_ptr, ~0, sizeof(validity_t) * (container_size / ValidityMask::BITS_PER_VALUE)); container_state.OverrideUncompressed(data_ptr); } else if (metadata.IsRun()) { @@ -308,6 +316,7 @@ void RoaringCompressState::FlushSegment() { // Size of the 'd' part auto unaligned_data_size = NumericCast(data_ptr - base_ptr); auto data_size = AlignValue(unaligned_data_size); + memset(data_ptr, 0, data_size - unaligned_data_size); data_ptr += data_size - unaligned_data_size; // Size of the 'm' part diff --git a/src/duckdb/src/storage/compression/standard_compression_state.cpp b/src/duckdb/src/storage/compression/standard_compression_state.cpp index d1ada3a20..fc4cd0c93 100644 --- a/src/duckdb/src/storage/compression/standard_compression_state.cpp +++ b/src/duckdb/src/storage/compression/standard_compression_state.cpp @@ -11,7 +11,8 @@ CompressionState::CompressionState(ColumnDataCheckpointData &checkpoint_data_p, unique_ptr CompressionState::CreateNewSegment() { return ColumnSegment::CreateTransientSegment(checkpoint_data.GetDatabase(), function, checkpoint_data.GetType(), - info.GetBlockSize(), info.GetBlockManager()); + info.GetBlockSize(), info.GetBlockManager(), + function.zero_initialize_segments); } const LogicalType &CompressionState::GetType() { diff --git a/src/duckdb/src/storage/compression/string_uncompressed.cpp b/src/duckdb/src/storage/compression/string_uncompressed.cpp index caaeeab12..086212eed 100644 --- a/src/duckdb/src/storage/compression/string_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/string_uncompressed.cpp @@ -236,17 +236,20 @@ idx_t UncompressedStringStorage::FinalizeAppend(ColumnSegment &segment, BaseStat // compute the total size required to store this segment auto offset_size = DICTIONARY_HEADER_SIZE + segment.count * sizeof(int32_t); auto total_size = offset_size + dict.size; + D_ASSERT(total_size <= segment.SegmentSize()); + auto dataptr = handle.GetDataMutable() + segment.GetBlockOffset(); CompressionInfo info(segment.GetBlockHandle()->GetBlockManager()); if (total_size >= info.GetCompactionFlushLimit()) { // the block is full enough, don't bother moving around the dictionary + // the whole segment is persisted, so clear the gap between the offsets and the dictionary + memset(dataptr + offset_size, 0, segment.SegmentSize() - total_size); return segment.SegmentSize(); } // the block has space left: figure out how much space we can save auto move_amount = segment.SegmentSize() - total_size; // move the dictionary so it lines up exactly with the offsets - auto dataptr = handle.GetDataMutable() + segment.GetBlockOffset(); memmove(dataptr + offset_size, dataptr + dict.end - dict.size, dict.size); dict.end -= move_amount; D_ASSERT(dict.end == total_size); @@ -285,7 +288,7 @@ void UncompressedStringStorage::VisitBlockIds(const ColumnSegment &segment, Bloc //===--------------------------------------------------------------------===// CompressionFunction StringUncompressed::GetFunction(PhysicalType data_type) { D_ASSERT(data_type == PhysicalType::VARCHAR); - return CompressionFunction( + CompressionFunction result( CompressionType::COMPRESSION_UNCOMPRESSED, data_type, UncompressedStringStorage::StringInitAnalyze, UncompressedStringStorage::StringAnalyze, UncompressedStringStorage::StringFinalAnalyze, UncompressedFunctions::InitCompression, UncompressedFunctions::Compress, @@ -296,6 +299,8 @@ CompressionFunction StringUncompressed::GetFunction(PhysicalType data_type) { UncompressedStringStorage::FinalizeAppend, UncompressedStringStorage::StringRevertAppend, UncompressedStringStorage::SerializeState, UncompressedStringStorage::DeserializeState, UncompressedStringStorage::VisitBlockIds, UncompressedStringInitPrefetch, UncompressedStringStorage::Select); + result.zero_initialize_segments = false; + return result; } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/storage/compression/validity_uncompressed.cpp b/src/duckdb/src/storage/compression/validity_uncompressed.cpp index 1f72f11b0..0e00c1bb1 100644 --- a/src/duckdb/src/storage/compression/validity_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/validity_uncompressed.cpp @@ -632,6 +632,7 @@ CompressionFunction ValidityUncompressed::GetFunction(PhysicalType data_type) { ValidityInitSegment, ValidityInitAppend, ValidityAppend, ValidityFinalizeAppend, ValidityRevertAppend); result.select = ValiditySelect; + 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 2f08c8f33..6e954383c 100644 --- a/src/duckdb/src/storage/compression/zstd.cpp +++ b/src/duckdb/src/storage/compression/zstd.cpp @@ -1,4 +1,3 @@ -#include "duckdb.hpp" #include "duckdb/common/constants.hpp" #include "duckdb/common/allocator.hpp" #include "duckdb/common/serializer/deserializer.hpp" @@ -43,10 +42,10 @@ static int32_t GetCompressionLevel() { return duckdb_zstd::ZSTD_defaultCLevel(); } -static constexpr idx_t ZSTD_VECTOR_SIZE = STANDARD_VECTOR_SIZE > 2048 ? STANDARD_VECTOR_SIZE : 2048; - namespace duckdb { +static constexpr idx_t ZSTD_VECTOR_SIZE = STANDARD_VECTOR_SIZE > 2048 ? STANDARD_VECTOR_SIZE : 2048; + static idx_t GetWritableSpace(const CompressionInfo &info) { return info.GetBlockSize() - sizeof(block_id_t); } @@ -281,7 +280,7 @@ class ZSTDCompressionState : public CompressionState { if (buffer_collection.CanFlush()) { auto &buffer_state = buffer_collection.GetCurrentBufferState(); - FlushPage(buffer_collection.BufferHandleMutable(), current_block_id); + FlushPage(buffer_collection.BufferHandleMutable(), current_block_id, buffer_state.offset); buffer_state.flags.Clear(); buffer_state.full = false; buffer_state.offset = 0; @@ -467,11 +466,15 @@ class ZSTDCompressionState : public CompressionState { return new_id; } - void FlushPage(BufferHandle &buffer, block_id_t block_id) { + void FlushPage(BufferHandle &buffer, block_id_t block_id, idx_t used_size) { if (block_id == INVALID_BLOCK) { return; } + auto &file_buffer = buffer.GetFileBuffer(); + D_ASSERT(used_size <= file_buffer.Size()); + memset(file_buffer.GetDataMutable() + used_size, 0, file_buffer.Size() - used_size); + // Write the current page to disk auto &block_manager = partial_block_manager.GetBlockManager(); block_manager.Write(partial_block_manager.GetQueryContext(), buffer.GetFileBuffer(), block_id); @@ -533,7 +536,7 @@ class ZSTDCompressionState : public CompressionState { return; } auto &buffer_handle = *buffer_handle_ptr; - FlushPage(buffer_handle, vector_state.starting_page); + FlushPage(buffer_handle, vector_state.starting_page, buffer_state.offset); buffer_state.offset = 0; buffer_state.full = false; } @@ -576,7 +579,7 @@ class ZSTDCompressionState : public CompressionState { throw InternalException("(ZSTDCompressionState::FlushSegment) Both extra pages were dirty (needed " "to be flushed), this should be impossible"); } - FlushPage(buffer_handle, buffer_collection.block_id); + FlushPage(buffer_handle, buffer_collection.block_id, buffer_state.offset); buffer_state.full = false; buffer_state.offset = 0; buffer_state.flags.Clear(); diff --git a/src/duckdb/src/storage/index_entry.cpp b/src/duckdb/src/storage/index_entry.cpp index 5e988028f..2d0b14f1c 100644 --- a/src/duckdb/src/storage/index_entry.cpp +++ b/src/duckdb/src/storage/index_entry.cpp @@ -31,7 +31,10 @@ void IndexEntry::Append(DataChunk &chunk, Vector &row_ids) { return; } auto &bound_index = owned_index->Cast(); - bound_index.Append(chunk, row_ids); + auto error = bound_index.Append(chunk, row_ids); + if (error.HasError()) { + error.Throw(); + } } ErrorData IndexEntry::Append(DataChunk &chunk, Vector &row_ids, const shared_ptr &delete_entry, @@ -61,7 +64,6 @@ ErrorData IndexEntry::Append(DataChunk &chunk, Vector &row_ids, const shared_ptr } } - ErrorData error; try { if (lookup_main_index) { IndexAppendInfo lookup_append_info; @@ -73,20 +75,19 @@ ErrorData IndexEntry::Append(DataChunk &chunk, Vector &row_ids, const shared_ptr } bound_index.VerifyAppend(chunk, lookup_append_info, optional_ptr()); } - - IndexAppendInfo index_append_info(append_mode, nullptr); - if (delete_index) { - index_append_info.delete_indexes.push_back(*delete_index); - } - if (append_index) { - error = append_index->Append(chunk, row_ids, index_append_info); - } else { - error = bound_index.Append(chunk, row_ids, index_append_info); - } } catch (std::exception &ex) { - error = ErrorData(ex); + // the lookup is read-only: nothing was inserted yet + return ErrorData(ex); } - return error; + + IndexAppendInfo index_append_info(append_mode, nullptr); + if (delete_index) { + index_append_info.delete_indexes.push_back(*delete_index); + } + if (append_index) { + return append_index->Append(chunk, row_ids, index_append_info); + } + return bound_index.Append(chunk, row_ids, index_append_info); } void IndexEntry::RevertAppend(DataChunk &chunk, Vector &row_ids) { @@ -137,6 +138,9 @@ void IndexEntry::AppendToDeleteIndexes(DataChunk &chunk, Vector &row_ids) { IndexAppendInfo index_append_info(IndexAppendMode::IGNORE_DUPLICATES, nullptr); auto result = bound_index.Append(chunk, row_ids, index_append_info); if (result.HasError()) { + if (result.Type() != ExceptionType::CONSTRAINT) { + result.Throw(); + } throw InternalException("unexpected constraint violation on delete ART: ", result.Message()); } } @@ -145,6 +149,9 @@ static void AppendIndexEntries(BoundIndex &index, DataChunk &chunk, Vector &row_ IndexAppendInfo append_info; const auto error = index.Append(chunk, row_ids, append_info); if (error.HasError()) { + if (error.Type() != ExceptionType::CONSTRAINT) { + error.Throw(); + } throw InternalException("Failed to append to %s: %s", index.GetIndexName(), error.Message()); } } @@ -445,6 +452,9 @@ void IndexEntry::Rebuild(const IndexRebuildScan &scan) { IndexRebuildAppend append = [&](DataChunk &chunk, Vector &row_ids) { auto error = bound_index.Append(chunk, row_ids); if (error.HasError()) { + if (error.Type() != ExceptionType::CONSTRAINT) { + error.Throw(); + } throw InternalException("Failed to rebuild index %s after vacuum: %s", bound_index.GetIndexName(), error.Message()); } diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 3e97b3910..46cb248c8 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -5,6 +5,7 @@ #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" #include "duckdb/main/attached_database.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/main/valid_checker.hpp" #include "duckdb/planner/table_filter.hpp" #include "duckdb/storage/data_table.hpp" @@ -197,37 +198,52 @@ ErrorData LocalTableStorage::AppendToIndexes(DuckTransaction &transaction, RowGr return error; } -void LocalTableStorage::AppendToTable(DuckTransaction &transaction, TableAppendState &append_state) { +ErrorData LocalTableStorage::AppendToTable(DuckTransaction &transaction, TableAppendState &append_state) { auto &table = table_ref.get(); - table.InitializeAppend(transaction, append_state); - auto &collection = *row_groups->collection; - for (auto &table_chunk : collection.Chunks(transaction)) { - // Append to the base table. - table.Append(table_chunk, append_state); + const auto index_end = append_state.current_row; + try { + table.InitializeAppend(transaction, append_state); + auto &collection = *row_groups->collection; + for (auto &table_chunk : collection.Chunks(transaction)) { + // Append to the base table. + table.Append(table_chunk, append_state); + } + table.FinalizeAppend(transaction, append_state); + } catch (std::exception &ex) { + // remove the rows and index entries that the failed append added + table.RevertFailedAppend(append_state); + // free the memory of the reverted rows before this storage is scanned again + append_state.row_group_append_state.states.reset(); + append_state.row_groups.reset(); + auto revert_error = RevertAppendToIndexes(transaction, append_state.row_start, index_end); + if (revert_error.HasError()) { + revert_error.Throw(); + } + return ErrorData(ex); } - table.FinalizeAppend(transaction, append_state); + return ErrorData(); } -void LocalTableStorage::AppendToIndexes(DuckTransaction &transaction, TableAppendState &append_state) { +ErrorData LocalTableStorage::AppendToIndexes(DuckTransaction &transaction, TableAppendState &append_state) { // In this function, we might scan all table columns, // as we might also append to the table itself (append_to_table). auto &table = table_ref.get(); if (!table.HasIndexes()) { // no indexes to append to - return; + return ErrorData(); } auto data_table_info = table.GetDataTableInfo(); auto &index_list = data_table_info->GetIndexes(); auto &collection = *row_groups->collection; auto error = AppendToIndexes(transaction, collection, index_list, table.GetTypes(), append_state.current_row); if (error.HasError()) { - // Revert all appended row IDs. + // the failing chunk's keys were already removed; revert the chunks appended before it auto revert_error = RevertAppendToIndexes(transaction, append_state.row_start, append_state.current_row); if (revert_error.HasError()) { revert_error.Throw(); } - error.Throw(); } + return error; } ErrorData LocalTableStorage::RevertAppendToIndexes(DuckTransaction &transaction, row_t row_start, row_t row_end) { @@ -617,53 +633,56 @@ void LocalStorage::Flush(DataTable &table, LocalTableStorage &storage, optional_ TableAppendState append_state; table.AppendLock(transaction, append_state); - if (storage.IsBulkAppend() || - (append_state.row_start == 0 && storage.deleted_rows == 0 && !storage.WritesToDisk())) { - // bulk append (at least one full row group, no deletes): move over the storage directly. - // Appends to an empty table are also merged directly if the table cannot be written to - // disk (temporary / in-memory / read-only, e.g. WAL replay of a read-only attach) - - // there are no optimistically written blocks to manage, and merging avoids re-appending - // row by row. - // first flush any outstanding blocks - storage.FlushBlocks(); - // Append to the indexes. - storage.AppendToIndexes(transaction, append_state); - // finally move over the row groups - table.MergeStorage(storage.GetCollection(), commit_state); - } else { - // check if we have written data - // if we have, we cannot merge to disk after all - // so we need to revert the data we have already written - // this happens when rows were deleted after a bulk append, or when the optimistic writer - // flushed a partial row group that does not qualify as a bulk append - storage.Rollback(); - // append to the indexes - storage.AppendToIndexes(transaction, append_state); - const auto index_end = append_state.current_row; - // after that is successful - append to the table - try { - storage.AppendToTable(transaction, append_state); - } catch (...) { - // remove the rows and index entries that the failed append added - try { - table.RevertFailedAppend(append_state); - // free the memory of the reverted rows before this storage is scanned again - append_state.row_group_append_state.states.reset(); - append_state.row_groups.reset(); - auto error = storage.RevertAppendToIndexes(transaction, append_state.row_start, index_end); - if (error.HasError()) { - error.Throw(); - } - } catch (std::exception &ex) { - ValidChecker::Invalidate(table.db.GetDatabase(), - "Failed to revert a failed append: " + ErrorData(ex).RawMessage()); + // until PushAppend, a returned error means the shared state was restored; anything thrown invalidates + ErrorData error; + try { + if (storage.IsBulkAppend() || + (append_state.row_start == 0 && storage.deleted_rows == 0 && !storage.WritesToDisk())) { + // bulk append (at least one full row group, no deletes): move over the storage directly. + // Appends to an empty table are also merged directly if the table cannot be written to + // disk (temporary / in-memory / read-only, e.g. WAL replay of a read-only attach) - + // there are no optimistically written blocks to manage, and merging avoids re-appending + // row by row. + // first flush any outstanding blocks + storage.FlushBlocks(); + // Append to the indexes. + error = storage.AppendToIndexes(transaction, append_state); + if (!error.HasError()) { + // finally move over the row groups + table.MergeStorage(storage.GetCollection(), commit_state); + } + } else { + // check if we have written data + // if we have, we cannot merge to disk after all + // so we need to revert the data we have already written + // this happens when rows were deleted after a bulk append, or when the optimistic writer + // flushed a partial row group that does not qualify as a bulk append + storage.Rollback(); + // append to the indexes + error = storage.AppendToIndexes(transaction, append_state); + if (!error.HasError()) { + // after that is successful - append to the table + error = storage.AppendToTable(transaction, append_state); } - throw; } + if (!error.HasError()) { + if (!table.db.IsSystem() && !table.db.IsTemporary() && + Settings::Get(table.db.GetDatabase())) { + throw IOException("Forced flush append failure (debug_force_flush_append_failure)"); + } + // table_entry is set through the append path (InitializeAppend/Append/LocalMerge/Alter) + D_ASSERT(storage.table_entry); + transaction.PushAppend(*storage.table_entry, NumericCast(append_state.row_start), append_count); + } + } catch (std::exception &ex) { + // the shared table or indexes may be partially modified: no checkpoint may persist them + table.db.Invalidate("flushing table \"" + table.GetTableName() + "\" during commit failed", + ErrorData(ex).RawMessage()); + throw; + } + if (error.HasError()) { + error.Throw(); } - // table_entry is set through the append path (InitializeAppend/Append/LocalMerge/Alter) - D_ASSERT(storage.table_entry); - transaction.PushAppend(*storage.table_entry, NumericCast(append_state.row_start), append_count); #ifdef DEBUG // Verify that our index memory is stable. diff --git a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp index f9366f67f..d72b3e25b 100644 --- a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp +++ b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp @@ -375,7 +375,10 @@ unique_ptr LogicalComparisonJoin::Deserialize(Deserializer &des deserializer.ReadPropertyWithDefault>(205, "mark_types", result->mark_types); deserializer.ReadPropertyWithDefault>>(206, "duplicate_eliminated_columns", result->duplicate_eliminated_columns); deserializer.ReadPropertyWithExplicitDefault(207, "delim_flipped", result->delim_flipped, false); - deserializer.ReadDeletedProperty>(208, "predicate"); + auto predicate = deserializer.ReadPropertyWithDefault>(208, "predicate"); + if (predicate) { + result->conditions.emplace_back(std::move(predicate)); + } return std::move(result); } @@ -953,7 +956,6 @@ void LogicalUpdate::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault(206, "update_is_del_and_insert", update_is_del_and_insert); serializer.WritePropertyWithDefault(207, "capture_old_rows", capture_old_rows, false); serializer.WritePropertyWithDefault>(208, "old_row_columns", old_row_columns); - serializer.WritePropertyWithDefault(209, "row_id_handling", row_id_handling, RowIdHandling::ASSUME_UNIQUE); } unique_ptr LogicalUpdate::Deserialize(Deserializer &deserializer) { @@ -967,7 +969,6 @@ unique_ptr LogicalUpdate::Deserialize(Deserializer &deserialize deserializer.ReadPropertyWithDefault(206, "update_is_del_and_insert", result->update_is_del_and_insert); deserializer.ReadPropertyWithExplicitDefault(207, "capture_old_rows", result->capture_old_rows, false); deserializer.ReadPropertyWithDefault>(208, "old_row_columns", result->old_row_columns); - deserializer.ReadPropertyWithExplicitDefault(209, "row_id_handling", result->row_id_handling, RowIdHandling::ASSUME_UNIQUE); return std::move(result); } diff --git a/src/duckdb/src/storage/serialization/serialize_nodes.cpp b/src/duckdb/src/storage/serialization/serialize_nodes.cpp index 472f02bf5..6a0414ae3 100644 --- a/src/duckdb/src/storage/serialization/serialize_nodes.cpp +++ b/src/duckdb/src/storage/serialization/serialize_nodes.cpp @@ -663,7 +663,9 @@ void SampleOptions::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault(101, "is_percentage", is_percentage); serializer.WriteProperty(102, "method", method); serializer.WritePropertyWithDefault(103, "seed", GetSeed()); - serializer.WritePropertyWithDefault(104, "repeatable", repeatable); + if (serializer.ShouldSerialize(StorageVersion::V2_0_0)) { + serializer.WriteProperty(104, "repeatable", repeatable); + } serializer.WritePropertyWithDefault(105, "sample_rate", sample_rate, -1.0); } @@ -676,7 +678,7 @@ unique_ptr SampleOptions::Deserialize(Deserializer &deserializer) result->sample_size = sample_size; result->is_percentage = is_percentage; result->method = method; - deserializer.ReadPropertyWithDefault(104, "repeatable", result->repeatable); + deserializer.ReadPropertyWithExplicitDefault(104, "repeatable", result->repeatable, result->seed.IsValid()); deserializer.ReadPropertyWithExplicitDefault(105, "sample_rate", result->sample_rate, -1.0); result->Verify(); return result; diff --git a/src/duckdb/src/storage/serialization/serialize_parse_info.cpp b/src/duckdb/src/storage/serialization/serialize_parse_info.cpp index 889af757c..9e4382872 100644 --- a/src/duckdb/src/storage/serialization/serialize_parse_info.cpp +++ b/src/duckdb/src/storage/serialization/serialize_parse_info.cpp @@ -10,6 +10,7 @@ #include "duckdb/parser/parsed_data/alter_table_info.hpp" #include "duckdb/parser/parsed_data/comment_on_column_info.hpp" #include "duckdb/parser/parsed_data/alter_database_info.hpp" +#include "duckdb/parser/parsed_data/alter_macro_info.hpp" #include "duckdb/parser/parsed_data/alter_schema_info.hpp" #include "duckdb/parser/parsed_data/attach_info.hpp" #include "duckdb/parser/parsed_data/copy_database_info.hpp" @@ -109,6 +110,9 @@ unique_ptr AlterInfo::Deserialize(Deserializer &deserializer) { case AlterType::ALTER_DATABASE: result = AlterDatabaseInfo::Deserialize(deserializer); break; + case AlterType::ALTER_MACRO: + result = AlterMacroInfo::Deserialize(deserializer); + break; case AlterType::ALTER_SCHEMA: result = AlterSchemaInfo::Deserialize(deserializer); break; @@ -241,6 +245,27 @@ unique_ptr AlterDatabaseInfo::Deserialize(Deserializer &deserializer) return std::move(result); } +void AlterMacroInfo::Serialize(Serializer &serializer) const { + AlterInfo::Serialize(serializer); + serializer.WriteProperty(300, "alter_macro_type", alter_macro_type); + serializer.WriteProperty(301, "entry_catalog_type", entry_catalog_type); +} + +unique_ptr AlterMacroInfo::Deserialize(Deserializer &deserializer) { + auto alter_macro_type = deserializer.ReadProperty(300, "alter_macro_type"); + auto entry_catalog_type = deserializer.ReadProperty(301, "entry_catalog_type"); + unique_ptr result; + switch (alter_macro_type) { + case AlterMacroType::REMOVE_OVERLOAD: + result = RemoveMacroOverloadInfo::Deserialize(deserializer); + break; + default: + throw SerializationException("Unsupported type for deserialization of AlterMacroInfo!"); + } + result->entry_catalog_type = entry_catalog_type; + return std::move(result); +} + void AlterSchemaInfo::Serialize(Serializer &serializer) const { AlterInfo::Serialize(serializer); serializer.WriteProperty(300, "alter_schema_type", alter_schema_type); @@ -611,6 +636,17 @@ unique_ptr RemoveFieldInfo::Deserialize(Deserializer &deserializ return std::move(result); } +void RemoveMacroOverloadInfo::Serialize(Serializer &serializer) const { + AlterMacroInfo::Serialize(serializer); + serializer.WritePropertyWithDefault>(400, "signature", signature); +} + +unique_ptr RemoveMacroOverloadInfo::Deserialize(Deserializer &deserializer) { + auto result = duckdb::unique_ptr(new RemoveMacroOverloadInfo()); + deserializer.ReadPropertyWithDefault>(400, "signature", result->signature); + return std::move(result); +} + void RenameColumnInfo::Serialize(Serializer &serializer) const { AlterTableInfo::Serialize(serializer); serializer.WritePropertyWithDefault(400, "old_name", old_name); diff --git a/src/duckdb/src/storage/single_file_block_manager.cpp b/src/duckdb/src/storage/single_file_block_manager.cpp index 03eacaac3..e28ca2b32 100644 --- a/src/duckdb/src/storage/single_file_block_manager.cpp +++ b/src/duckdb/src/storage/single_file_block_manager.cpp @@ -610,6 +610,7 @@ void SingleFileBlockManager::CreateNewDatabase(QueryContext context) { h1.block_alloc_size = GetBlockAllocSize(); h1.vector_size = STANDARD_VECTOR_SIZE; h1.storage_compatibility = options.storage_version; + header_buffer.Clear(); SerializeHeaderStructure(h1, header_buffer.GetDataMutable()); ChecksumAndWrite(context, header_buffer, Storage::FILE_HEADER_SIZE); @@ -623,6 +624,7 @@ void SingleFileBlockManager::CreateNewDatabase(QueryContext context) { h2.block_alloc_size = GetBlockAllocSize(); h2.vector_size = STANDARD_VECTOR_SIZE; h2.storage_compatibility = options.storage_version; + header_buffer.Clear(); SerializeHeaderStructure(h2, header_buffer.GetDataMutable()); ChecksumAndWrite(context, header_buffer, Storage::FILE_HEADER_SIZE * 2ULL); @@ -1487,7 +1489,7 @@ void SingleFileBlockManager::TrimFreeBlockRange(block_id_t start, block_id_t end } void SingleFileBlockManager::TrimFreeBlocks(const set &blocks) { - if (!DBConfig::Get(db).options.trim_free_blocks) { + if (!Settings::Get(DBConfig::Get(db))) { return; } lock_guard lock(single_file_block_lock); diff --git a/src/duckdb/src/storage/standard_buffer_manager.cpp b/src/duckdb/src/storage/standard_buffer_manager.cpp index 5af88943e..c5dc70200 100644 --- a/src/duckdb/src/storage/standard_buffer_manager.cpp +++ b/src/duckdb/src/storage/standard_buffer_manager.cpp @@ -63,7 +63,7 @@ unique_ptr StandardBufferManager::ConstructManagedBuffer(idx_t size, // non re-usable buffer (or mmap-backed, which we cannot rewrite): allocate a new buffer result = make_uniq(BlockAllocator::Get(db), type, size, block_header_size); } - result->Initialize(DBConfig::GetConfig(db).options.debug_initialize); + result->Initialize(Settings::Get(db)); return result; } diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index bb3ddb3d4..d90dc2db8 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -4,10 +4,12 @@ #include "duckdb/common/enums/checkpoint_abort.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/common/thread.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_data.hpp" +#include "duckdb/main/connection.hpp" #include "duckdb/main/query_profiler.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/main/database.hpp" @@ -25,6 +27,7 @@ #include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/transaction/duck_transaction_manager.hpp" #include "duckdb/storage/data_table.hpp" +#include "duckdb/storage/table/data_table_info.hpp" #include "mbedtls_wrapper.hpp" #include "duckdb/common/path.hpp" @@ -163,8 +166,8 @@ StorageManager::StorageManager(AttachedDatabase &db, string path_p, AttachOption auto &fs = FileSystem::Get(db); path = fs.ExpandPath(path); - auto services = db.GetDatabase().Services(); - storage_options.Initialize(*services, options.options); + auto &services = db.GetDatabase().GetContext(); + storage_options.Initialize(services, options.options); } StorageManager::~StorageManager() { @@ -193,6 +196,14 @@ void StorageManager::SetWALSize(idx_t size) { wal_size = size; } +void StorageManager::MarkBufferedIndexReplays() { + buffered_index_replays = true; +} + +bool StorageManager::HasBufferedIndexReplays() const { + return buffered_index_replays; +} + idx_t StorageManager::GetWALEntriesCount() const { return wal_entries_count; } @@ -253,6 +264,11 @@ bool StorageManager::WALStartCheckpoint(MetaBlockPointer meta_block, CheckpointO // not holding the commit lock yet - grab it guard = GetCommitLock(); } + // a commit that failed while we waited for the commit lock may have invalidated the database + auto invalidation_error = db.InvalidationError("checkpoint"); + if (invalidation_error.HasError()) { + invalidation_error.Throw(); + } // drain under the commit lock before the checkpoint transaction starts: its snapshot would // otherwise be bounded below commits whose WAL this checkpoint deletes auto &transaction_manager = DuckTransactionManager::Get(db); @@ -435,7 +451,7 @@ void SingleFileStorageManager::LoadDatabase(QueryContext context) { } options.io_mode = resolved_io_mode; options.mmap_reserve_size = storage_options.mmap_reserve_size; - options.debug_initialize = config.options.debug_initialize; + options.debug_initialize = Settings::Get(config); options.storage_version = storage_options.storage_version; if (storage_options.encryption) { @@ -693,8 +709,7 @@ idx_t SingleFileStorageCommitState::FlushCommit(bool sync_now) { auto &writer = wal.Initialize(); writer.Sync(); storage.SetWALSize(writer.GetFileSize()); - ValidChecker::Invalidate(storage.GetDatabase(), "Simulated crash before WAL_FLUSH write"); - ValidChecker::Invalidate(storage.GetAttached(), "Simulated crash before WAL_FLUSH write"); + storage.GetAttached().Invalidate("of a simulated crash", "Simulated crash before WAL_FLUSH write"); // Prevent `RevertCommit` from truncating the WAL so the torn records are kept for crash recovery state = WALCommitState::FLUSHED; throw FatalException("Simulated crash before WAL_FLUSH write"); @@ -757,11 +772,120 @@ bool SingleFileStorageManager::IsCheckpointClean(MetaBlockPointer checkpoint_id) unique_ptr SingleFileStorageManager::CreateCheckpointWriter(QueryContext context, CheckpointOptions options, - optional_ptr client_context) { + optional_ptr checkpoint_context) { if (InMemory()) { - return make_uniq(context, db, *block_manager, *this, options, client_context); + return make_uniq(context, db, *block_manager, *this, options, checkpoint_context); + } + return make_uniq(context, db, *block_manager, options, checkpoint_context); +} + +static vector> GetCommittedTables(AttachedDatabase &db) { + vector> tables; + auto &catalog = Catalog::GetCatalog(db).Cast(); + auto bound = VisibilityBound::AllCommitted(); + catalog.ScanSchemas(bound, [&](DuckSchemaEntry &schema) { + schema.Scan(CatalogType::TABLE_ENTRY, bound, [&](CatalogEntry &entry) { + if (!entry.internal && entry.type == CatalogType::TABLE_ENTRY) { + tables.push_back(entry.Cast()); + } + }); + }); + return tables; +} + +static vector> GetTablesWithUnboundIndexes(AttachedDatabase &db) { + // Don't take index locks inside the catalog scan: concurrent binds take them in the opposite order. + vector> result; + for (auto &table : GetCommittedTables(db)) { + if (table.get().GetStorage().GetDataTableInfo()->GetIndexes().HasUnbound()) { + result.push_back(table); + } + } + return result; +} + +static ErrorData TryBindIndexes(DataTableInfo &info, ClientContext &context) { + try { + info.BindIndexes(context); + } catch (std::exception &ex) { + ErrorData error(ex); + if (Exception::InvalidatesDatabase(error.Type()) || error.Type() == ExceptionType::INTERNAL) { + throw; + } + return error; + } + return ErrorData(); +} + +static bool HasBufferedReplays(const vector> &tables) { + for (auto &table : tables) { + if (table.get().GetStorage().GetDataTableInfo()->GetIndexes().HasBufferedReplays()) { + return true; + } + } + return false; +} + +bool SingleFileStorageManager::BindIndexesForCheckpoint(optional_ptr checkpoint_context, + bool explicit_checkpoint) { + // Explicit checkpoints also bind indexes without buffered replays, so that their tables can be vacuumed. + if (!buffered_index_replays && !explicit_checkpoint) { + return true; } - return make_uniq(context, db, *block_manager, options, client_context); + auto tables = GetTablesWithUnboundIndexes(db); + if (tables.empty()) { + buffered_index_replays = false; + return true; + } + + // Shutdown and DETACH do not bind. + if (!checkpoint_context) { + buffered_index_replays = HasBufferedReplays(tables); + return !buffered_index_replays; + } + + auto checkpoint_sleep_ms = Settings::Get(db.GetDatabase()); + if (checkpoint_sleep_ms > 0) { + ThreadUtil::SleepMs(checkpoint_sleep_ms); + } + + // Read-only: a concurrent FORCE CHECKPOINT holds start_transaction_lock while waiting for this checkpoint. + auto &transaction = checkpoint_context->transaction; + transaction.BeginTransaction(); + transaction.SetReadOnly(); + + // Indexes with buffered replays must be bound, otherwise the checkpoint would lose these operations. + ErrorData failure; + string failed_table; + for (auto &table : tables) { + auto &info = *table.get().GetStorage().GetDataTableInfo(); + if (!explicit_checkpoint && !info.GetIndexes().HasBufferedReplays()) { + continue; + } + auto error = TryBindIndexes(info, *checkpoint_context); + // A failed bind only matters if it leaves buffered replays behind. + if (error.HasError() && info.GetIndexes().HasBufferedReplays()) { + failure = std::move(error); + failed_table = info.GetTableName().GetIdentifierName(); + break; + } + } + // End the bind transaction: the checkpoint transaction runs on the same connection. + transaction.Rollback(nullptr); + + if (failure.HasError()) { + auto message = StringUtil::Format("an index on table \"%s\" has buffered operations and cannot be bound: %s", + failed_table, failure.RawMessage()); + if (explicit_checkpoint) { + throw Exception(failure.Type(), "Cannot CHECKPOINT: " + message); + } + // FIXME: every commit that triggers an automatic checkpoint retries the bind until it succeeds + DUCKDB_LOG_WARNING(db.GetDatabase(), "Skipped the checkpoint of database %s and kept its write-ahead log: %s", + db.GetName(), message); + return false; + } + buffered_index_replays = false; + return true; } void SingleFileStorageManager::CreateCheckpoint(QueryContext context, CheckpointOptions options, @@ -790,7 +914,21 @@ void SingleFileStorageManager::CreateCheckpoint(QueryContext context, Checkpoint auto &config = DBConfig::Get(db); // We only need to checkpoint if there is anything in the WAL. auto wal_size = GetWALSize(); - if (wal_size > 0 || config.options.force_checkpoint || options.action == CheckpointAction::ALWAYS_CHECKPOINT) { + auto should_checkpoint = wal_size > 0 || Settings::Get(config) || + options.action == CheckpointAction::ALWAYS_CHECKPOINT; + // Shared by the index binds before the checkpoint and by the checkpoint transaction. + unique_ptr checkpoint_connection; + optional_ptr checkpoint_context; + if (should_checkpoint && Context::TryGetClientContext(context.GetContext())) { + checkpoint_connection = make_uniq(Connection::CreateInternal(db.GetDatabase())); + checkpoint_context = checkpoint_connection->context.get(); + } + // Bind before the checkpoint starts: a failure after that invalidates the database. + if (should_checkpoint && !BindIndexesForCheckpoint(checkpoint_context, client_context != nullptr)) { + should_checkpoint = false; + } + + if (should_checkpoint) { try { // Start timing the checkpoint. auto profiler = Context::TryGetQueryProfiler(context.GetContext()); @@ -800,18 +938,18 @@ void SingleFileStorageManager::CreateCheckpoint(QueryContext context, Checkpoint } // Write the checkpoint. - auto checkpointer = CreateCheckpointWriter(context, options, client_context); + auto checkpointer = CreateCheckpointWriter(context, options, checkpoint_context); checkpointer->CreateCheckpoint(); timer.EndTimer(); } catch (std::exception &ex) { ErrorData error(ex); - if (db.IsInitialDatabase()) { + if (!db.SupportsScopedInvalidation()) { ValidChecker::Invalidate(db.GetDatabase(), error.RawMessage()); throw FatalException("Failed to create checkpoint because of error: %s", error.RawMessage()); } // A non-initial database can be detached and reattached, so scope invalidation to this db. - db.Invalidate(error.RawMessage()); + db.Invalidate("checkpointing failed", error.RawMessage()); throw IOException("Checkpoint failed for database %s. The database has been invalidated. Original " "error: %s", db.GetName(), error.RawMessage()); @@ -827,26 +965,8 @@ void SingleFileStorageManager::Destroy() { if (!load_complete) { return; } - vector> schemas; - // we scan the set of committed schemas - auto &catalog = Catalog::GetCatalog(db).Cast(); - catalog.ScanSchemas(VisibilityBound::AllCommitted(), [&](DuckSchemaEntry &entry) { schemas.push_back(entry); }); - - vector> tables; - for (auto &schema : schemas) { - schema.get().Scan(CatalogType::TABLE_ENTRY, VisibilityBound::AllCommitted(), [&](CatalogEntry &entry) { - if (entry.internal) { - return; - } - if (entry.type == CatalogType::TABLE_ENTRY) { - tables.push_back(entry.Cast()); - } - }); - } - - for (auto &table : tables) { - auto &data_table = table.get().GetStorage(); - data_table.Destroy(); + for (auto &table : GetCommittedTables(db)) { + table.get().GetStorage().Destroy(); } } diff --git a/src/duckdb/src/storage/table/column_segment.cpp b/src/duckdb/src/storage/table/column_segment.cpp index f2d08f553..0e0264935 100644 --- a/src/duckdb/src/storage/table/column_segment.cpp +++ b/src/duckdb/src/storage/table/column_segment.cpp @@ -49,11 +49,16 @@ unique_ptr ColumnSegment::CreatePersistentSegment(DatabaseInstanc unique_ptr ColumnSegment::CreateTransientSegment(DatabaseInstance &db, const CompressionFunction &function, const LogicalType &type, const idx_t segment_size, - BlockManager &block_manager) { + BlockManager &block_manager, bool zero_initialize) { // Allocate a buffer for the uncompressed segment. auto &buffer_manager = BufferManager::GetBufferManager(db); D_ASSERT(&buffer_manager == &block_manager.buffer_manager); auto block = buffer_manager.RegisterTransientMemory(segment_size, block_manager); + // we want to zero initialize segments that end up on disk + if (zero_initialize) { + auto handle = buffer_manager.Pin(block); + memset(handle.GetDataMutable(), 0, segment_size); + } return make_uniq(db, std::move(block), ColumnSegmentType::TRANSIENT, 0U, function, BaseStatistics::CreateEmpty(type), INVALID_BLOCK, 0U, segment_size); @@ -494,7 +499,9 @@ idx_t ColumnSegment::FilterSelection(SelectionVector &sel, Vector &vector, Unifi idx_t ColumnSegment::FilterSelection(SelectionVector &sel, Vector &vector, TableFilterState &filter_state, idx_t scan_count, idx_t &approved_tuple_count) { auto &state = filter_state.Cast(); - if (state.fast_executor && scan_count <= STANDARD_VECTOR_SIZE) { + if (state.fast_executor && + (scan_count <= STANDARD_VECTOR_SIZE || (vector.GetVectorType() == VectorType::FLAT_VECTOR && + !vector.GetType().IsNested() && scan_count <= vector.size()))) { return state.fast_executor->FilterSelection(sel, vector, scan_count, approved_tuple_count); } return ExecuteExpressionFilterSelection(sel, vector, state, scan_count, approved_tuple_count); diff --git a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp index 21fd27e82..21081e7f6 100644 --- a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp +++ b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp @@ -21,8 +21,8 @@ namespace duckdb { //===--------------------------------------------------------------------===// InMemoryCheckpointer::InMemoryCheckpointer(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, StorageManager &storage_manager, CheckpointOptions options_p, - optional_ptr client_context) - : CheckpointWriter(db, context, client_context), + 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) { } @@ -30,7 +30,7 @@ InMemoryCheckpointer::InMemoryCheckpointer(QueryContext context, AttachedDatabas void InMemoryCheckpointer::CreateCheckpoint() { auto &transaction_manager = DuckTransactionManager::Get(db); // appends that run alongside the checkpoint start new row groups, index changes go to the checkpoint deltas - ActiveCheckpointWrapper active_checkpoint(GetContext(), db, transaction_manager); + ActiveCheckpointWrapper active_checkpoint(checkpoint_context, db, transaction_manager); { unique_lock commit_lock; if (!options.commit_lock) { diff --git a/src/duckdb/src/storage/table/row_group.cpp b/src/duckdb/src/storage/table/row_group.cpp index 7a0bac679..f39f12abc 100644 --- a/src/duckdb/src/storage/table/row_group.cpp +++ b/src/duckdb/src/storage/table/row_group.cpp @@ -1062,12 +1062,6 @@ void RowGroup::ProcessPreparedScan(ScanOptions options, CollectionScanState &sta col_data.Filter(transaction, state.vector_index, state.column_scans[scan_idx], result_vector, sel, approved_tuple_count, filter.filter, table_filter_state); } - for (auto &table_filter : filter_list) { - if (table_filter.IsAlwaysTrue()) { - continue; - } - result.data[table_filter.scan_column_index].Slice(sel, approved_tuple_count); - } } if (approved_tuple_count == 0) { // all rows were filtered out by the table filters @@ -1086,6 +1080,15 @@ void RowGroup::ProcessPreparedScan(ScanOptions options, CollectionScanState &sta FinishVector(state); return; } + if (has_filters) { + // Slice only columns that will be returned. Empty chunks are reset above without allocating dictionaries. + for (auto &table_filter : filter_info.GetFilterList()) { + if (table_filter.IsAlwaysTrue()) { + continue; + } + result.data[table_filter.scan_column_index].Slice(sel, approved_tuple_count); + } + } //! Now we use the selection vector to fetch data for the other columns. for (idx_t i = 0; i < column_ids.size(); i++) { if (has_filters && filter_info.ColumnHasFilters(i)) { diff --git a/src/duckdb/src/storage/table/row_group_collection.cpp b/src/duckdb/src/storage/table/row_group_collection.cpp index 79836b5e4..51251c545 100644 --- a/src/duckdb/src/storage/table/row_group_collection.cpp +++ b/src/duckdb/src/storage/table/row_group_collection.cpp @@ -693,6 +693,8 @@ optional_idx RowGroupCollection::Append(DataChunk &chunk, TableAppendState &stat idx_t total_append_count = chunk.size(); idx_t remaining = chunk.size(); state.total_append_count += total_append_count; + DataChunk remaining_chunk; + reference append_chunk(chunk); while (true) { auto ¤t_row_group = state.row_group_append_state.row_group->GetNode(); // check how much we can fit into the current row_group @@ -700,7 +702,7 @@ optional_idx RowGroupCollection::Append(DataChunk &chunk, TableAppendState &stat MinValue(remaining, row_group_size - state.row_group_append_state.offset_in_row_group); if (append_count > 0) { auto previous_allocation_size = current_row_group.GetAllocationSize(); - current_row_group.Append(state.row_group_append_state, chunk, append_count); + current_row_group.Append(state.row_group_append_state, append_chunk, append_count); allocation_size += current_row_group.GetAllocationSize() - previous_allocation_size; } remaining -= append_count; @@ -711,10 +713,15 @@ optional_idx RowGroupCollection::Append(DataChunk &chunk, TableAppendState &stat current_row_group.FinalizeAppend(state.row_group_append_state); // we expect max 1 iteration of this loop (i.e. a single chunk should never overflow more than one // row_group) - D_ASSERT(chunk.size() == remaining + append_count); - // slice the input chunk - if (remaining < chunk.size()) { - chunk.Slice(append_count, remaining); + D_ASSERT(append_chunk.get().size() == remaining + append_count); + // slice the remaining rows into a separate chunk, so the input chunk is left untouched + if (remaining < append_chunk.get().size()) { + if (remaining_chunk.ColumnCount() == 0) { + remaining_chunk.InitializeEmpty(chunk.GetTypes()); + } + remaining_chunk.Reference(chunk); + remaining_chunk.Slice(total_append_count - remaining, remaining); + append_chunk = remaining_chunk; } // append a new row_group flushed_row_group_idx = state.row_group_append_state.row_group->GetIndex(); diff --git a/src/duckdb/src/storage/table/variant/variant_shredding.cpp b/src/duckdb/src/storage/table/variant/variant_shredding.cpp index 3bcfb9483..0d9e8fff1 100644 --- a/src/duckdb/src/storage/table/variant/variant_shredding.cpp +++ b/src/duckdb/src/storage/table/variant/variant_shredding.cpp @@ -748,7 +748,8 @@ void VariantColumnData::ShredVariantData(const Vector &input, Vector &output, id ListVector::SetListSize(values, 0); auto &keys_entry = ListVector::GetChildMutable(keys); - OrderedOwningStringMap dictionary(StringVector::GetStringAllocator(keys_entry)); + OrderedOwningStringMap dictionary; + auto &keys_arena = StringVector::GetStringAllocator(keys_entry); SelectionVector keys_selvec; keys_selvec.Initialize(original_keys_size); @@ -775,7 +776,7 @@ void VariantColumnData::ShredVariantData(const Vector &input, Vector &output, id auto &values_list_entry = variant_data.values_data[row]; values_list_entry.offset = ListVector::GetListSize(values); - VariantNormalizerState normalizer_state(row, variant_data, dictionary, keys_selvec); + VariantNormalizerState normalizer_state(row, variant_data, dictionary, keys_arena, keys_selvec); for (idx_t i = 0; i < unshredded_values.size(); i++) { auto &unshredded_value = unshredded_values[i]; auto value_index = unshredded_value.source_value_index; diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index cd8b94b34..582dccfb5 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -527,7 +527,7 @@ unique_ptr WriteAheadLogReplayer::ReplayLog(unique_ptr(config) || error.Type() != ExceptionType::SERIALIZATION) { con.Rollback(); error.Throw("Failure while replaying WAL file \"" + wal_path + "\": "); } @@ -690,7 +690,7 @@ unique_ptr WriteAheadLogReplayer::ReplayLog(unique_ptr(config) || error.Type() != ExceptionType::SERIALIZATION) { error.Throw("Failure while replaying WAL file \"" + wal_path + "\": "); } } catch (...) { diff --git a/src/duckdb/src/storage/write_ahead_log.cpp b/src/duckdb/src/storage/write_ahead_log.cpp index 5e90b3e76..e18f765e9 100644 --- a/src/duckdb/src/storage/write_ahead_log.cpp +++ b/src/duckdb/src/storage/write_ahead_log.cpp @@ -617,6 +617,10 @@ void WriteAheadLog::SyncUpTo(idx_t offset) { if (error.HasError()) { // the OS may have dropped the dirty pages: this WAL must never be synced again sync_failed = true; + auto &attached = GetDatabase(); + if (attached.SupportsScopedInvalidation()) { + attached.Invalidate("syncing its WAL failed", error.RawMessage()); + } } else { durable_offset = target; } diff --git a/src/duckdb/src/transaction/commit_state.cpp b/src/duckdb/src/transaction/commit_state.cpp index 50c3136fd..7537081cd 100644 --- a/src/duckdb/src/transaction/commit_state.cpp +++ b/src/duckdb/src/transaction/commit_state.cpp @@ -5,7 +5,6 @@ #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" #include "duckdb/catalog/catalog_entry/duck_schema_entry.hpp" #include "duckdb/catalog/catalog_entry/trigger_catalog_entry.hpp" -#include "duckdb/catalog/catalog_entry/scalar_macro_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/type_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/view_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/dependency/dependency_entry.hpp" @@ -292,10 +291,13 @@ void CommitState::CommitEntry(UndoFlags type, data_ptr_t data, CommitInfo &info) if (new_entry.type == CatalogType::DEPENDENCY_ENTRY) { auto &dep = new_entry.Cast(); if (dep.Side() == DependencyEntryType::SUBJECT) { - new_entry.set->VerifyExistenceOfDependency(commit_id, new_entry); + new_entry.set->VerifyExistenceOfDependency(commit_id, transaction.view.visibility_bound, new_entry); } } else if (new_entry.type == CatalogType::DELETED_ENTRY && old_entry.set) { old_entry.set->CommitDrop(commit_id, transaction.view.visibility_bound, old_entry); + } else if (old_entry.set && new_entry.InvalidatesDependents(old_entry)) { + // an alter that breaks what dependents rely on must not race a dependency created meanwhile, like a drop + old_entry.set->VerifyCommitDrop(commit_id, transaction.view.visibility_bound, old_entry); } // Grab a write lock on the catalog auto &duck_catalog = catalog.Cast(); diff --git a/src/duckdb/src/transaction/duck_transaction.cpp b/src/duckdb/src/transaction/duck_transaction.cpp index b6668ae12..1c2d2197e 100644 --- a/src/duckdb/src/transaction/duck_transaction.cpp +++ b/src/duckdb/src/transaction/duck_transaction.cpp @@ -326,16 +326,13 @@ ErrorData DuckTransaction::Commit(AttachedDatabase &db, CommitInfo &commit_info, } catch (std::exception &ex) { // If we fail to revert the commit, the database is left in an undefined state - invalidate it. // Record both the original commit error and the revert error so the root cause stays visible. - ValidChecker::Invalidate(db.GetDatabase(), - "Failed to revert transaction commit, database is in an undefined state. " - "Original commit error: " + - error_data.RawMessage() + ". RevertCommit error: " + ErrorData(ex).RawMessage()); + db.Invalidate("reverting a failed commit failed, leaving it in an undefined state", + "commit error: " + error_data.RawMessage() + + ". RevertCommit error: " + ErrorData(ex).RawMessage()); } catch (...) { // last line of defense: this is a noexcept function, nothing may escape - ValidChecker::Invalidate(db.GetDatabase(), - "Failed to revert transaction commit (unknown error), database is in an " - "undefined state. Original commit error: " + - error_data.RawMessage()); + db.Invalidate("reverting a failed commit failed, leaving it in an undefined state", + "commit error: " + error_data.RawMessage() + ". RevertCommit error: unknown error"); } return error_data; } diff --git a/src/duckdb/src/transaction/duck_transaction_manager.cpp b/src/duckdb/src/transaction/duck_transaction_manager.cpp index f19557670..7a3efb701 100644 --- a/src/duckdb/src/transaction/duck_transaction_manager.cpp +++ b/src/duckdb/src/transaction/duck_transaction_manager.cpp @@ -381,7 +381,9 @@ ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Tran // any failure during checkpoint will cause this transactions' changes to be lost, // while later concurrent commits will not be // this can cause undefined state, as those commits were made assuming this one was already committed - if (undo_properties.estimated_size >= Settings::Get(context)) { + // we must write the WAL if an unbound index has buffered replays: the checkpoint may be skipped + if (undo_properties.estimated_size >= Settings::Get(context) && + !db.GetStorageManager().HasBufferedIndexReplays()) { skip_wal_write_due_to_checkpoint = true; } } @@ -394,8 +396,10 @@ ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Tran t_lock.unlock(); // grab the commit lock and hold it until the entire commit is finished held_commit_lock = db.GetStorageManager().GetCommitLock(); + // a commit that failed while we waited for the commit lock may have invalidated the database + error = db.InvalidationError("commit"); - if (!skip_wal_write_due_to_checkpoint) { + if (!error.HasError() && !skip_wal_write_due_to_checkpoint) { error = transaction.AppendLocalStorage(context, db, commit_state); if (!error.HasError() && should_write_to_wal) { // Commit the changes to the WAL. @@ -519,7 +523,7 @@ ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Tran // published and no longer revertable, but not durable: invalidate. The WAL keeps the // bytes; whether a restart replays them is in doubt error = ErrorData(ex); - ValidChecker::Invalidate(db, "Failed to sync the WAL after committing: " + error.Message()); + db.Invalidate("syncing the WAL after a commit failed", error.RawMessage()); // no checkpoint after a failed commit, as on the rollback path above checkpoint_decision = CheckpointDecision(error.Message()); lock.reset(); diff --git a/src/duckdb/src/transaction/meta_transaction.cpp b/src/duckdb/src/transaction/meta_transaction.cpp index c66efde63..42b31ecda 100644 --- a/src/duckdb/src/transaction/meta_transaction.cpp +++ b/src/duckdb/src/transaction/meta_transaction.cpp @@ -149,7 +149,7 @@ ErrorData MetaTransaction::Commit() { try { if (!error.HasError()) { // Commit the transaction. - error = transaction_manager.CommitTransaction(context, transaction); + error = db.ScopeFatalError(transaction_manager.CommitTransaction(context, transaction)); transaction_ref.state = error.HasError() ? TransactionState::ROLLED_BACK : TransactionState::COMMITTED; } else { // Rollback due to previous error. @@ -157,7 +157,7 @@ ErrorData MetaTransaction::Commit() { transaction_ref.state = TransactionState::ROLLED_BACK; } } catch (std::exception &ex) { - error.Merge(ErrorData(ex)); + error.Merge(db.ScopeFatalError(ErrorData(ex))); transaction_ref.state = TransactionState::ROLLED_BACK; } } @@ -184,7 +184,7 @@ void MetaTransaction::Rollback() { auto &transaction = transaction_ref.transaction; transaction_manager.RollbackTransaction(transaction); } catch (std::exception &ex) { - error.Merge(ErrorData(ex)); + error.Merge(db.ScopeFatalError(ErrorData(ex))); } transaction_ref.state = TransactionState::ROLLED_BACK; } diff --git a/src/duckdb/src/transaction/transaction_context.cpp b/src/duckdb/src/transaction/transaction_context.cpp index 5e9abcec2..18717adc8 100644 --- a/src/duckdb/src/transaction/transaction_context.cpp +++ b/src/duckdb/src/transaction/transaction_context.cpp @@ -23,8 +23,9 @@ TransactionContext::~TransactionContext() { try { Rollback(nullptr); } catch (std::exception &ex) { - ErrorData data(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 } diff --git a/src/duckdb/third_party/concurrentqueue/blockingconcurrentqueue.h b/src/duckdb/third_party/concurrentqueue/blockingconcurrentqueue.h index 916a5a277..b33fe23c6 100644 --- a/src/duckdb/third_party/concurrentqueue/blockingconcurrentqueue.h +++ b/src/duckdb/third_party/concurrentqueue/blockingconcurrentqueue.h @@ -1,8 +1,9 @@ -// Provides an efficient blocking version of moodycamel::ConcurrentQueue. -// ©2015-2016 Cameron Desrochers. Distributed under the terms of the simplified +// Provides an efficient blocking version of duckdb_moodycamel::ConcurrentQueue. +// ©2015-2020 Cameron Desrochers. Distributed under the terms of the simplified // BSD license, available at the top of concurrentqueue.h. +// Also dual-licensed under the Boost Software License (see LICENSE.md) // Uses Jeff Preshing's semaphore implementation (under the terms of its -// separate zlib license, embedded below). +// separate zlib license, see lightweightsemaphore.h). #pragma once @@ -55,18 +56,18 @@ class BlockingConcurrentQueue // includes making the memory effects of construction visible, possibly with a // memory barrier). explicit BlockingConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE) - : inner(capacity), sema(create(), &BlockingConcurrentQueue::template destroy) + : inner(capacity), sema(create(0, static_cast(Traits::MAX_SEMA_SPINS)), &BlockingConcurrentQueue::template destroy) { - assert(reinterpret_cast((BlockingConcurrentQueue*)1) == &((BlockingConcurrentQueue*)1)->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member"); + assert(reinterpret_cast(reinterpret_cast(1)) == &(reinterpret_cast(1))->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member"); if (!sema) { MOODYCAMEL_THROW(std::bad_alloc()); } } BlockingConcurrentQueue(size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers) - : inner(minCapacity, maxExplicitProducers, maxImplicitProducers), sema(create(), &BlockingConcurrentQueue::template destroy) + : inner(minCapacity, maxExplicitProducers, maxImplicitProducers), sema(create(0, static_cast(Traits::MAX_SEMA_SPINS)), &BlockingConcurrentQueue::template destroy) { - assert(reinterpret_cast((BlockingConcurrentQueue*)1) == &((BlockingConcurrentQueue*)1)->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member"); + assert(reinterpret_cast(reinterpret_cast(1)) == &(reinterpret_cast(1))->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member"); if (!sema) { MOODYCAMEL_THROW(std::bad_alloc()); } @@ -178,12 +179,13 @@ class BlockingConcurrentQueue inline bool enqueue_bulk(It itemFirst, size_t count) { if ((details::likely)(inner.enqueue_bulk(std::forward(itemFirst), count))) { - sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count); + assert(static_cast(count) >= 0); + sema->signal(static_cast(static_cast(count))); return true; } return false; } - + // Enqueues several items using an explicit producer token. // Allocates memory if required. Only fails if memory allocation fails // (or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed). @@ -194,7 +196,8 @@ class BlockingConcurrentQueue inline bool enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count) { if ((details::likely)(inner.enqueue_bulk(token, std::forward(itemFirst), count))) { - sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count); + assert(static_cast(count) >= 0); + sema->signal(static_cast(static_cast(count))); return true; } return false; @@ -263,12 +266,13 @@ class BlockingConcurrentQueue inline bool try_enqueue_bulk(It itemFirst, size_t count) { if (inner.try_enqueue_bulk(std::forward(itemFirst), count)) { - sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count); + assert(static_cast(count) >= 0); + sema->signal(static_cast(static_cast(count))); return true; } return false; } - + // Enqueues several items using an explicit producer token. // Does not allocate memory. Fails if not enough room to enqueue. // Note: Use std::make_move_iterator if the elements should be moved @@ -278,7 +282,8 @@ class BlockingConcurrentQueue inline bool try_enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count) { if (inner.try_enqueue_bulk(token, std::forward(itemFirst), count)) { - sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count); + assert(static_cast(count) >= 0); + sema->signal(static_cast(static_cast(count))); return true; } return false; @@ -326,13 +331,14 @@ class BlockingConcurrentQueue inline size_t try_dequeue_bulk(It itemFirst, size_t max) { size_t count = 0; - max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max); + assert(static_cast(max) >= 0); + max = static_cast(sema->tryWaitMany(static_cast(static_cast(max)))); while (count != max) { count += inner.template try_dequeue_bulk(itemFirst, max - count); } return count; } - + // Attempts to dequeue several elements from the queue using an explicit consumer token. // Returns the number of items actually dequeued. // Returns 0 if all producer streams appeared empty at the time they @@ -342,7 +348,8 @@ class BlockingConcurrentQueue inline size_t try_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max) { size_t count = 0; - max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max); + assert(static_cast(max) >= 0); + max = static_cast(sema->tryWaitMany(static_cast(static_cast(max)))); while (count != max) { count += inner.template try_dequeue_bulk(token, itemFirst, max - count); } @@ -446,13 +453,14 @@ class BlockingConcurrentQueue inline size_t wait_dequeue_bulk(It itemFirst, size_t max) { size_t count = 0; - max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max); + assert(static_cast(max) >= 0); + max = static_cast(sema->waitMany(static_cast(static_cast(max)))); while (count != max) { count += inner.template try_dequeue_bulk(itemFirst, max - count); } return count; } - + // Attempts to dequeue several elements from the queue. // Returns the number of items actually dequeued, which can // be 0 if the timeout expires while waiting for elements, @@ -464,7 +472,8 @@ class BlockingConcurrentQueue inline size_t wait_dequeue_bulk_timed(It itemFirst, size_t max, std::int64_t timeout_usecs) { size_t count = 0; - max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs); + assert(static_cast(max) >= 0); + max = static_cast(sema->waitMany(static_cast(static_cast(max)), timeout_usecs)); while (count != max) { count += inner.template try_dequeue_bulk(itemFirst, max - count); } @@ -491,7 +500,8 @@ class BlockingConcurrentQueue inline size_t wait_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max) { size_t count = 0; - max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max); + assert(static_cast(max) >= 0); + max = static_cast(sema->waitMany(static_cast(static_cast(max)))); while (count != max) { count += inner.template try_dequeue_bulk(token, itemFirst, max - count); } @@ -509,7 +519,8 @@ class BlockingConcurrentQueue inline size_t wait_dequeue_bulk_timed(consumer_token_t& token, It itemFirst, size_t max, std::int64_t timeout_usecs) { size_t count = 0; - max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs); + assert(static_cast(max) >= 0); + max = static_cast(sema->waitMany(static_cast(static_cast(max)), timeout_usecs)); while (count != max) { count += inner.template try_dequeue_bulk(token, itemFirst, max - count); } @@ -536,32 +547,25 @@ class BlockingConcurrentQueue // Thread-safe. inline size_t size_approx() const { - return (size_t)sema->availableApprox(); + return static_cast(sema->availableApprox()); } // Returns true if the underlying atomic variables used by // the queue are lock-free (they should be on most platforms). // Thread-safe. - static bool is_lock_free() + static constexpr bool is_lock_free() { return ConcurrentQueue::is_lock_free(); } private: - template - static inline U* create() - { - auto p = (Traits::malloc)(sizeof(U)); - return p != nullptr ? new (p) U : nullptr; - } - - template - static inline U* create(A1&& a1) + template + static inline U* create(A1&& a1, A2&& a2) { - auto p = (Traits::malloc)(sizeof(U)); - return p != nullptr ? new (p) U(std::forward(a1)) : nullptr; + void* p = (Traits::malloc)(sizeof(U)); + return p != nullptr ? new (p) U(std::forward(a1), std::forward(a2)) : nullptr; } template @@ -585,4 +589,4 @@ inline void swap(BlockingConcurrentQueue& a, BlockingConcurrentQueue< a.swap(b); } -} // end namespace moodycamel +} // end namespace duckdb_moodycamel diff --git a/src/duckdb/third_party/concurrentqueue/concurrentqueue.h b/src/duckdb/third_party/concurrentqueue/concurrentqueue.h index b62b637bf..a86e73bca 100644 --- a/src/duckdb/third_party/concurrentqueue/concurrentqueue.h +++ b/src/duckdb/third_party/concurrentqueue/concurrentqueue.h @@ -5,7 +5,7 @@ // http://moodycamel.com/blog/2014/detailed-design-of-a-lock-free-queue // Simplified BSD license: -// Copyright (c) 2013-2016, Cameron Desrochers. +// Copyright (c) 2013-2020, Cameron Desrochers. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, @@ -27,16 +27,24 @@ // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Also dual-licensed under the Boost Software License (see LICENSE.md) #pragma once -#if defined(__GNUC__) +#if defined(__GNUC__) && !defined(__INTEL_COMPILER) // Disable -Wconversion warnings (spuriously triggered when Traits::size_t and // Traits::index_t are set to < 32 bits, causing integer promotion, causing warnings // upon assigning any computed values) #endif +#if defined(_MSC_VER) && (!defined(_HAS_CXX17) || !_HAS_CXX17) +// VS2019 with /W4 warns about constant conditional expressions but unless /std=c++17 or higher +// does not support `if constexpr`, so we have no choice but to simply disable the warning +#pragma warning(push) +#pragma warning(disable: 4127) // conditional expression is constant +#endif + #if defined(__APPLE__) #include #endif @@ -53,6 +61,7 @@ #include // for CHAR_BIT #include #include // partly for __WINPTHREADS_VERSION if on MinGW-w64 w/ POSIX threading +#include // used for thread exit synchronization // Platform-specific definitions of a numeric thread ID type and an invalid value namespace duckdb_moodycamel { namespace details { @@ -80,7 +89,7 @@ namespace duckdb_moodycamel { namespace details { static const thread_id_t invalid_thread_id2 = 0xFFFFFFFFU; // Not technically guaranteed to be invalid, but is never used in practice. Note that all Win32 thread IDs are presently multiples of 4. static inline thread_id_t thread_id() { return static_cast(::GetCurrentThreadId()); } } } -#elif defined(__arm__) || defined(_M_ARM) || defined(__aarch64__) || (defined(__APPLE__) && TARGET_OS_IPHONE) || defined(__MVS__) +#elif defined(__arm__) || defined(_M_ARM) || defined(__aarch64__) || (defined(__APPLE__) && TARGET_OS_IPHONE) || defined(__MVS__) || defined(MOODYCAMEL_NO_THREAD_LOCAL) namespace duckdb_moodycamel { namespace details { static_assert(sizeof(std::thread::id) == 4 || sizeof(std::thread::id) == 8, "std::thread::id is expected to be either 4 or 8 bytes"); @@ -194,9 +203,9 @@ namespace duckdb_moodycamel { namespace details { // VS2013 doesn't support `thread_local`, and MinGW-w64 w/ POSIX threading has a crippling bug: http://sourceforge.net/p/mingw-w64/bugs/445 // g++ <=4.7 doesn't support thread_local either. // Finally, iOS/ARM doesn't have support for it either, and g++/ARM allows it to compile but it's unconfirmed to actually work -#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && (!defined(__MINGW32__) && !defined(__MINGW64__) || !defined(__WINPTHREADS_VERSION)) && (!defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) && (!defined(__APPLE__) || !TARGET_OS_IPHONE) && !defined(__arm__) && !defined(_M_ARM) && !defined(__aarch64__) && !defined(__MVS__) -// Assume `thread_local` is fully supported in all other C++11 compilers/platforms -//#define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED // always disabled for now since several users report having problems with it on +#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && (!defined(__MINGW32__) && !defined(__MINGW64__) || !defined(__WINPTHREADS_VERSION)) && (!defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) && (!defined(__APPLE__) || !TARGET_OS_IPHONE) && !defined(__arm__) && !defined(_M_ARM) && !defined(__aarch64__) && !defined(__MVS__) && !defined(MOODYCAMEL_NO_THREAD_LOCAL) +// DuckDB enqueues from thread-local destructors, after this notifier may have been destroyed. +//#define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED #endif #endif #endif @@ -211,18 +220,43 @@ namespace duckdb_moodycamel { namespace details { #endif #endif +namespace duckdb_moodycamel { namespace details { #ifndef MOODYCAMEL_ALIGNAS -// VS2013 doesn't support alignas or alignof +// VS2013 doesn't support alignas or alignof, and align() requires a constant literal #if defined(_MSC_VER) && _MSC_VER <= 1800 #define MOODYCAMEL_ALIGNAS(alignment) __declspec(align(alignment)) #define MOODYCAMEL_ALIGNOF(obj) __alignof(obj) +#define MOODYCAMEL_ALIGNED_TYPE_LIKE(T, obj) typename details::Vs2013Aligned::value, T>::type + template struct Vs2013Aligned { }; // default, unsupported alignment + template struct Vs2013Aligned<1, T> { typedef __declspec(align(1)) T type; }; + template struct Vs2013Aligned<2, T> { typedef __declspec(align(2)) T type; }; + template struct Vs2013Aligned<4, T> { typedef __declspec(align(4)) T type; }; + template struct Vs2013Aligned<8, T> { typedef __declspec(align(8)) T type; }; + template struct Vs2013Aligned<16, T> { typedef __declspec(align(16)) T type; }; + template struct Vs2013Aligned<32, T> { typedef __declspec(align(32)) T type; }; + template struct Vs2013Aligned<64, T> { typedef __declspec(align(64)) T type; }; + template struct Vs2013Aligned<128, T> { typedef __declspec(align(128)) T type; }; + template struct Vs2013Aligned<256, T> { typedef __declspec(align(256)) T type; }; #else + template struct identity { typedef T type; }; #define MOODYCAMEL_ALIGNAS(alignment) alignas(alignment) #define MOODYCAMEL_ALIGNOF(obj) alignof(obj) +#define MOODYCAMEL_ALIGNED_TYPE_LIKE(T, obj) alignas(alignof(obj)) typename details::identity::type #endif #endif +} } +// TSAN can false report races in lock-free code. To enable TSAN to be used from projects that use this one, +// we can apply per-function compile-time suppression. +// See https://clang.llvm.org/docs/ThreadSanitizer.html#has-feature-thread-sanitizer +#define MOODYCAMEL_NO_TSAN +#if defined(__has_feature) + #if __has_feature(thread_sanitizer) + #undef MOODYCAMEL_NO_TSAN + #define MOODYCAMEL_NO_TSAN __attribute__((no_sanitize("thread"))) + #endif // TSAN +#endif // TSAN // Compiler-specific likely/unlikely hints namespace duckdb_moodycamel { namespace details { @@ -304,6 +338,12 @@ struct ConcurrentQueueDefaultTraits // How many full blocks can be expected for a single implicit producer? This should // reflect that number's maximum for optimal performance. Must be a power of 2. + // Note: This impacts the maximum number of elements that can be enqueued by a + // single implicit producer when using try_enqueue/try_enqeue_bulk exclusively (which + // cannot allocate), since it limits the number of blocks that the producer can hold to + // store elements. When pre-allocating blocks for use with try-enqueueing, configure + // this initial size to the desired maximum number of blocks per implicit producer. + // Alternately, use the regular enqueue methods, which can grow the index as needed. static const size_t IMPLICIT_INITIAL_INDEX_SIZE = 32; // The initial size of the hash table mapping thread IDs to implicit producers. @@ -322,7 +362,20 @@ struct ConcurrentQueueDefaultTraits // that this limit is enforced at the block level (for performance reasons), i.e. // it's rounded up to the nearest block size. static const size_t MAX_SUBQUEUE_SIZE = details::const_numeric_max::value; - + + // The number of times to spin before sleeping when waiting on a semaphore. + // Recommended values are on the order of 1000-10000 unless the number of + // consumer threads exceeds the number of idle cores (in which case try 0-100). + // Only affects instances of the BlockingConcurrentQueue. + static const int MAX_SEMA_SPINS = 10000; + + // Whether to recycle dynamically-allocated blocks into an internal free list or + // not. If false, only pre-allocated blocks (controlled by the constructor + // arguments) will be recycled, and all others will be `free`d back to the heap. + // Note that blocks consumed by explicit producers are only freed on destruction + // of the queue (not following destruction of the token) regardless of this trait. + static const bool RECYCLE_ALLOCATED_BLOCKS = false; + #ifndef MCDBGQ_USE_RELACY // Memory allocation can be customized if needed. @@ -405,22 +458,24 @@ namespace details static inline size_t hash_thread_id(thread_id_t id) { static_assert(sizeof(thread_id_t) <= 8, "Expected a platform where thread IDs are at most 64-bit values"); +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuseless-cast" +#endif return static_cast(hash_32_or_64::thread_id_hash_t)>::hash( thread_id_converter::prehash(id))); +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif } template static inline bool circular_less_than(T a, T b) { -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4554) -#endif static_assert(std::is_integral::value && !std::numeric_limits::is_signed, "circular_less_than is intended to be used only with unsigned integer types"); - return static_cast(a - b) > static_cast(static_cast(1) << static_cast(sizeof(T) * CHAR_BIT - 1)); -#ifdef _MSC_VER -#pragma warning(pop) -#endif + return static_cast(a - b) > static_cast(static_cast(1) << (static_cast(sizeof(T) * CHAR_BIT - 1))); + // Note: extra parens around rhs of operator<< is MSVC bug: https://developercommunity2.visualstudio.com/t/C4554-triggers-when-both-lhs-and-rhs-is/10034931 + // silencing the bug requires #pragma warning(disable: 4554) around the calling code and has no effect when done here. } template @@ -450,9 +505,9 @@ namespace details template static inline void swap_relaxed(std::atomic& left, std::atomic& right) { - T temp = std::move(left.load(std::memory_order_relaxed)); - left.store(std::move(right.load(std::memory_order_relaxed)), std::memory_order_relaxed); - right.store(std::move(temp), std::memory_order_relaxed); + T temp = left.load(std::memory_order_relaxed); + left.store(right.load(std::memory_order_relaxed), std::memory_order_relaxed); + right.store(temp, std::memory_order_relaxed); } template @@ -499,6 +554,8 @@ namespace details typedef RelacyThreadExitListener ThreadExitListener; typedef RelacyThreadExitNotifier ThreadExitNotifier; #else + class ThreadExitNotifier; + struct ThreadExitListener { typedef void (*callback_t)(void*); @@ -506,22 +563,29 @@ namespace details void* userData; ThreadExitListener* next; // reserved for use by the ThreadExitNotifier + ThreadExitNotifier* chain; // reserved for use by the ThreadExitNotifier }; - - + class ThreadExitNotifier { public: static void subscribe(ThreadExitListener* listener) { auto& tlsInst = instance(); + std::lock_guard guard(mutex()); listener->next = tlsInst.tail; + listener->chain = &tlsInst; tlsInst.tail = listener; } static void unsubscribe(ThreadExitListener* listener) { - auto& tlsInst = instance(); + std::lock_guard guard(mutex()); + if (!listener->chain) { + return; // race with ~ThreadExitNotifier + } + auto& tlsInst = *listener->chain; + listener->chain = nullptr; ThreadExitListener** prev = &tlsInst.tail; for (auto ptr = tlsInst.tail; ptr != nullptr; ptr = ptr->next) { if (ptr == listener) { @@ -541,7 +605,9 @@ namespace details { // This thread is about to exit, let everyone know! assert(this == &instance() && "If this assert fails, you likely have a buggy compiler! Change the preprocessor conditions such that MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED is no longer defined."); + std::lock_guard guard(mutex()); for (auto ptr = tail; ptr != nullptr; ptr = ptr->next) { + ptr->chain = nullptr; ptr->callback(ptr->userData); } } @@ -552,6 +618,13 @@ namespace details static thread_local ThreadExitNotifier notifier; return notifier; } + + static inline std::mutex& mutex() + { + // Must be static because the ThreadExitNotifier could be destroyed while unsubscribe is called + static std::mutex mutex; + return mutex; + } private: ThreadExitListener* tail; @@ -733,7 +806,7 @@ class ConcurrentQueue // queue is fully constructed before it starts being used by other threads (this // includes making the memory effects of construction visible, possibly with a // memory barrier). - explicit ConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE) + explicit ConcurrentQueue(size_t capacity = 32 * BLOCK_SIZE) : producerListTail(nullptr), producerCount(0), initialBlockPoolIndex(0), @@ -979,6 +1052,9 @@ class ConcurrentQueue // Does not allocate memory. Fails if not enough room to enqueue (or implicit // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE // is 0). + // Note: If using only try_enqueue/try_enqueue_bulk with pre-allocated blocks, configure + // Traits::IMPLICIT_INITIAL_INDEX_SIZE appropriately to ensure the index has sufficient + // capacity for the number of blocks each producer may need. // Thread-safe. inline bool try_enqueue(T const& item) { @@ -990,6 +1066,9 @@ class ConcurrentQueue // Does not allocate memory (except for one-time implicit producer). // Fails if not enough room to enqueue (or implicit production is // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0). + // Note: If using only try_enqueue/try_enqueue_bulk with pre-allocated blocks, configure + // Traits::IMPLICIT_INITIAL_INDEX_SIZE appropriately to ensure the index has sufficient + // capacity for the number of blocks each producer may need. // Thread-safe. inline bool try_enqueue(T&& item) { @@ -1017,6 +1096,9 @@ class ConcurrentQueue // Does not allocate memory (except for one-time implicit producer). // Fails if not enough room to enqueue (or implicit production is // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0). + // Note: If using only try_enqueue/try_enqueue_bulk with pre-allocated blocks, configure + // Traits::IMPLICIT_INITIAL_INDEX_SIZE appropriately to ensure the index has sufficient + // capacity for the number of blocks each producer may need. // Note: Use std::make_move_iterator if the elements should be moved // instead of copied. // Thread-safe. @@ -1275,7 +1357,7 @@ class ConcurrentQueue // Returns true if the underlying atomic variables used by // the queue are lock-free (they should be on most platforms). // Thread-safe. - static bool is_lock_free() + static constexpr bool is_lock_free() { return details::static_is_lock_free::value == 2 && @@ -1419,7 +1501,7 @@ class ConcurrentQueue while (head != nullptr) { auto prevHead = head; auto refs = head->freeListRefs.load(std::memory_order_relaxed); - if ((refs & REFS_MASK) == 0 || !head->freeListRefs.compare_exchange_strong(refs, refs + 1, std::memory_order_acquire, std::memory_order_relaxed)) { + if ((refs & REFS_MASK) == 0 || !head->freeListRefs.compare_exchange_strong(refs, refs + 1, std::memory_order_acquire)) { head = freeListHead.load(std::memory_order_acquire); continue; } @@ -1469,7 +1551,7 @@ class ConcurrentQueue node->freeListRefs.store(1, std::memory_order_release); if (!freeListHead.compare_exchange_strong(head, node, std::memory_order_release, std::memory_order_relaxed)) { // Hmm, the add failed, but we can only try again when the refcount goes back to zero - if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST - 1, std::memory_order_release) == 1) { + if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST - 1, std::memory_order_acq_rel) == 1) { continue; } } @@ -1499,7 +1581,7 @@ class ConcurrentQueue struct Block { Block() - : next(nullptr), elementsCompletelyDequeued(0), freeListRefs(0), freeListNext(nullptr), shouldBeOnFreeList(false), dynamicallyAllocated(true) + : next(nullptr), elementsCompletelyDequeued(0), freeListRefs(0), freeListNext(nullptr), dynamicallyAllocated(true) { #ifdef MCDBGQ_TRACKMEM owner = nullptr; @@ -1544,7 +1626,7 @@ class ConcurrentQueue } else { // Increment counter - auto prevVal = elementsCompletelyDequeued.fetch_add(1, std::memory_order_release); + auto prevVal = elementsCompletelyDequeued.fetch_add(1, std::memory_order_acq_rel); assert(prevVal < BLOCK_SIZE); return prevVal == BLOCK_SIZE - 1; } @@ -1567,7 +1649,7 @@ class ConcurrentQueue } else { // Increment counter - auto prevVal = elementsCompletelyDequeued.fetch_add(count, std::memory_order_release); + auto prevVal = elementsCompletelyDequeued.fetch_add(count, std::memory_order_acq_rel); assert(prevVal + count <= BLOCK_SIZE); return prevVal + count == BLOCK_SIZE; } @@ -1608,7 +1690,7 @@ class ConcurrentQueue private: static_assert(std::alignment_of::value <= sizeof(T), "The queue does not support types with an alignment greater than their size at this time"); - MOODYCAMEL_ALIGNAS(MOODYCAMEL_ALIGNOF(T)) char elements[sizeof(T) * BLOCK_SIZE]; + MOODYCAMEL_ALIGNED_TYPE_LIKE(char[sizeof(T) * BLOCK_SIZE], T) elements; public: Block* next; std::atomic elementsCompletelyDequeued; @@ -1616,7 +1698,6 @@ class ConcurrentQueue public: std::atomic freeListRefs; std::atomic freeListNext; - std::atomic shouldBeOnFreeList; bool dynamicallyAllocated; // Perhaps a better name for this would be 'isNotPartOfInitialBlockPool' #ifdef MCDBGQ_TRACKMEM @@ -1649,7 +1730,7 @@ class ConcurrentQueue { } - virtual ~ProducerBase() { }; + virtual ~ProducerBase() { } template inline bool dequeue(U& element) @@ -1685,10 +1766,13 @@ class ConcurrentQueue inline index_t getTail() const { return tailIndex.load(std::memory_order_relaxed); } protected: std::atomic tailIndex; // Where to enqueue to next + // Separate producer and consumer writes without requiring aligned allocation. + char producerPadding[64 - sizeof(std::atomic)]; std::atomic headIndex; // Where to dequeue from next std::atomic dequeueOptimisticCount; std::atomic dequeueOvercommit; + char consumerPadding[64 - sizeof(std::atomic)]; Block* tailBlock; @@ -1771,12 +1855,7 @@ class ConcurrentQueue auto block = this->tailBlock; do { auto nextBlock = block->next; - if (block->dynamicallyAllocated) { - destroy(block); - } - else { - this->parent->add_block_to_free_list(block); - } + this->parent->add_block_to_free_list(block); block = nextBlock; } while (block != this->tailBlock); } @@ -1858,7 +1937,7 @@ class ConcurrentQueue ++pr_blockIndexSlotsUsed; } - if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new ((T*)nullptr) T(std::forward(element)))) { + MOODYCAMEL_CONSTEXPR_IF (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (static_cast(nullptr)) T(std::forward(element)))) { // The constructor may throw. We want the element not to appear in the queue in // that case (without corrupting the queue): MOODYCAMEL_TRY { @@ -1884,7 +1963,7 @@ class ConcurrentQueue blockIndex.load(std::memory_order_relaxed)->front.store(pr_blockIndexFront, std::memory_order_release); pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1); - if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new ((T*)nullptr) T(std::forward(element)))) { + MOODYCAMEL_CONSTEXPR_IF (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (static_cast(nullptr)) T(std::forward(element)))) { this->tailIndex.store(newTailIndex, std::memory_order_release); return true; } @@ -1998,7 +2077,7 @@ class ConcurrentQueue } template - bool enqueue_bulk(It itemFirst, size_t count) + bool MOODYCAMEL_NO_TSAN enqueue_bulk(It itemFirst, size_t count) { // First, we need to make sure we have enough room to enqueue all of the elements; // this means pre-allocating blocks and putting them in the block index (but only if @@ -2100,7 +2179,7 @@ class ConcurrentQueue block = block->next; } - if (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new ((T*)nullptr) T(details::deref_noexcept(itemFirst)))) { + MOODYCAMEL_CONSTEXPR_IF (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (static_cast(nullptr)) T(details::deref_noexcept(itemFirst)))) { blockIndex.load(std::memory_order_relaxed)->front.store((pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release); } } @@ -2115,11 +2194,11 @@ class ConcurrentQueue this->tailBlock = firstAllocatedBlock; } while (true) { - auto stopIndex = (currentTailIndex & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); + index_t stopIndex = (currentTailIndex & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); if (details::circular_less_than(newTailIndex, stopIndex)) { stopIndex = newTailIndex; } - if (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new ((T*)nullptr) T(details::deref_noexcept(itemFirst)))) { + MOODYCAMEL_CONSTEXPR_IF (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (static_cast(nullptr)) T(details::deref_noexcept(itemFirst)))) { while (currentTailIndex != stopIndex) { new ((*this->tailBlock)[currentTailIndex++]) T(*itemFirst++); } @@ -2134,7 +2213,7 @@ class ConcurrentQueue // may only define a (noexcept) move constructor, and so calls to the // cctor will not compile, even if they are in an if branch that will never // be executed - new ((*this->tailBlock)[currentTailIndex]) T(details::nomove_if<(bool)!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new ((T*)nullptr) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst)); + new ((*this->tailBlock)[currentTailIndex]) T(details::nomove_if(nullptr)) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst)); ++currentTailIndex; ++itemFirst; } @@ -2181,8 +2260,9 @@ class ConcurrentQueue this->tailBlock = this->tailBlock->next; } - if (!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new ((T*)nullptr) T(details::deref_noexcept(itemFirst))) && firstAllocatedBlock != nullptr) { - blockIndex.load(std::memory_order_relaxed)->front.store((pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release); + MOODYCAMEL_CONSTEXPR_IF (!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (static_cast(nullptr)) T(details::deref_noexcept(itemFirst)))) { + if (firstAllocatedBlock != nullptr) + blockIndex.load(std::memory_order_relaxed)->front.store((pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release); } this->tailIndex.store(newTailIndex, std::memory_order_release); @@ -2199,7 +2279,7 @@ class ConcurrentQueue desiredCount = desiredCount < max ? desiredCount : max; std::atomic_thread_fence(std::memory_order_acquire); - auto myDequeueCount = this->dequeueOptimisticCount.fetch_add(desiredCount, std::memory_order_relaxed);; + auto myDequeueCount = this->dequeueOptimisticCount.fetch_add(desiredCount, std::memory_order_relaxed); tail = this->tailIndex.load(std::memory_order_acquire); auto actualCount = static_cast(tail - (myDequeueCount - overcommit)); @@ -2226,7 +2306,7 @@ class ConcurrentQueue auto index = firstIndex; do { auto firstIndexInBlock = index; - auto endIndex = (index & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); + index_t endIndex = (index & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); endIndex = details::circular_less_than(firstIndex + static_cast(actualCount), endIndex) ? firstIndex + static_cast(actualCount) : endIndex; auto block = localBlockIndex->entries[indexIndex].block; if (MOODYCAMEL_NOEXCEPT_ASSIGN(T, T&&, details::deref_noexcept(itemFirst) = std::move((*(*block)[index])))) { @@ -2460,8 +2540,8 @@ class ConcurrentQueue newBlock->owner = this; #endif newBlock->ConcurrentQueue::Block::template reset_empty(); - - if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new ((T*)nullptr) T(std::forward(element)))) { + + MOODYCAMEL_CONSTEXPR_IF (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (static_cast(nullptr)) T(std::forward(element)))) { // May throw, try to insert now before we publish the fact that we have this new block MOODYCAMEL_TRY { new ((*newBlock)[currentTailIndex]) T(std::forward(element)); @@ -2479,7 +2559,7 @@ class ConcurrentQueue this->tailBlock = newBlock; - if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new ((T*)nullptr) T(std::forward(element)))) { + MOODYCAMEL_CONSTEXPR_IF (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (static_cast(nullptr)) T(std::forward(element)))) { this->tailIndex.store(newTailIndex, std::memory_order_release); return true; } @@ -2563,6 +2643,10 @@ class ConcurrentQueue return false; } +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4706) // assignment within conditional expression +#endif template bool enqueue_bulk(It itemFirst, size_t count) { @@ -2598,6 +2682,7 @@ class ConcurrentQueue auto head = this->headIndex.load(std::memory_order_relaxed); assert(!details::circular_less_than(currentTailIndex, head)); bool full = !details::circular_less_than(head, currentTailIndex + BLOCK_SIZE) || (MAX_SUBQUEUE_SIZE != details::const_numeric_max::value && (MAX_SUBQUEUE_SIZE == 0 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head)); + if (full || !(indexInserted = insert_block_index_entry(idxEntry, currentTailIndex)) || (newBlock = this->parent->ConcurrentQueue::template requisition_block()) == nullptr) { // Index allocation or block allocation failed; revert any other allocations // and index insertions done so far for this operation @@ -2648,11 +2733,11 @@ class ConcurrentQueue this->tailBlock = firstAllocatedBlock; } while (true) { - auto stopIndex = (currentTailIndex & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); + index_t stopIndex = (currentTailIndex & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); if (details::circular_less_than(newTailIndex, stopIndex)) { stopIndex = newTailIndex; } - if (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new ((T*)nullptr) T(details::deref_noexcept(itemFirst)))) { + MOODYCAMEL_CONSTEXPR_IF (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (static_cast(nullptr)) T(details::deref_noexcept(itemFirst)))) { while (currentTailIndex != stopIndex) { new ((*this->tailBlock)[currentTailIndex++]) T(*itemFirst++); } @@ -2660,7 +2745,7 @@ class ConcurrentQueue else { MOODYCAMEL_TRY { while (currentTailIndex != stopIndex) { - new ((*this->tailBlock)[currentTailIndex]) T(details::nomove_if<(bool)!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new ((T*)nullptr) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst)); + new ((*this->tailBlock)[currentTailIndex]) T(details::nomove_if(nullptr)) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst)); ++currentTailIndex; ++itemFirst; } @@ -2712,6 +2797,9 @@ class ConcurrentQueue this->tailIndex.store(newTailIndex, std::memory_order_release); return true; } +#ifdef _MSC_VER +#pragma warning(pop) +#endif template size_t dequeue_bulk(It& itemFirst, size_t max) @@ -2743,7 +2831,7 @@ class ConcurrentQueue auto indexIndex = get_block_index_index_for_index(index, localBlockIndex); do { auto blockStartIndex = index; - auto endIndex = (index & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); + index_t endIndex = (index & ~static_cast(BLOCK_SIZE - 1)) + static_cast(BLOCK_SIZE); endIndex = details::circular_less_than(firstIndex + static_cast(actualCount), endIndex) ? firstIndex + static_cast(actualCount) : endIndex; auto entry = localBlockIndex->index[indexIndex]; @@ -2839,9 +2927,16 @@ class ConcurrentQueue { auto localBlockIndex = blockIndex.load(std::memory_order_relaxed); // We're the only writer thread, relaxed is OK if (localBlockIndex == nullptr) { - return false; // this can happen if new_block_index failed in the constructor + // Retry if the initial index allocation failed in the constructor. + MOODYCAMEL_CONSTEXPR_IF (allocMode == CannotAlloc) { + return false; + } + else if (!new_block_index()) { + return false; + } + localBlockIndex = blockIndex.load(std::memory_order_relaxed); } - auto newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1) & (localBlockIndex->capacity - 1); + size_t newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1) & (localBlockIndex->capacity - 1); idxEntry = localBlockIndex->index[newTail]; if (idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE || idxEntry->value.load(std::memory_order_relaxed) == nullptr) { @@ -2858,13 +2953,15 @@ class ConcurrentQueue else if (!new_block_index()) { return false; } - localBlockIndex = blockIndex.load(std::memory_order_relaxed); - newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1) & (localBlockIndex->capacity - 1); - idxEntry = localBlockIndex->index[newTail]; - assert(idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE); - idxEntry->key.store(blockStartIndex, std::memory_order_relaxed); - localBlockIndex->tail.store(newTail, std::memory_order_release); - return true; + else { + localBlockIndex = blockIndex.load(std::memory_order_relaxed); + newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1) & (localBlockIndex->capacity - 1); + idxEntry = localBlockIndex->index[newTail]; + assert(idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE); + idxEntry->key.store(blockStartIndex, std::memory_order_relaxed); + localBlockIndex->tail.store(newTail, std::memory_order_release); + return true; + } } inline void rewind_block_index_tail() @@ -3004,7 +3101,12 @@ class ConcurrentQueue #ifdef MCDBGQ_TRACKMEM block->owner = nullptr; #endif - freeList.add(block); + if (!Traits::RECYCLE_ALLOCATED_BLOCKS && block->dynamicallyAllocated) { + destroy(block); + } + else { + freeList.add(block); + } } inline void add_blocks_to_free_list(Block* block) @@ -3155,12 +3257,6 @@ class ConcurrentQueue ////////////////////////////////// ProducerBase* recycle_or_create_producer(bool isExplicit) - { - bool recycled; - return recycle_or_create_producer(isExplicit, recycled); - } - - ProducerBase* recycle_or_create_producer(bool isExplicit, bool& recycled) { #ifdef MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH debug::DebugLock lock(implicitProdMutex); @@ -3171,13 +3267,11 @@ class ConcurrentQueue bool expected = true; if (ptr->inactive.compare_exchange_strong(expected, /* desired */ false, std::memory_order_acquire, std::memory_order_relaxed)) { // We caught one! It's been marked as activated, the caller can have it - recycled = true; return ptr; } } } - - recycled = false; + return add_producer(isExplicit ? static_cast(create(this)) : create(this)); } @@ -3348,7 +3442,7 @@ class ConcurrentQueue // Look for the id in this hash auto index = hashedId; while (true) { // Not an infinite loop because at least one slot is free in the hash table - index &= hash->capacity - 1; + index &= hash->capacity - 1u; auto probedKey = hash->entries[index].key.load(std::memory_order_relaxed); if (probedKey == id) { @@ -3361,15 +3455,14 @@ class ConcurrentQueue if (hash != mainHash) { index = hashedId; while (true) { - index &= mainHash->capacity - 1; - probedKey = mainHash->entries[index].key.load(std::memory_order_relaxed); + index &= mainHash->capacity - 1u; auto empty = details::invalid_thread_id; #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED auto reusable = details::invalid_thread_id2; - if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed, std::memory_order_relaxed)) || - (probedKey == reusable && mainHash->entries[index].key.compare_exchange_strong(reusable, id, std::memory_order_acquire, std::memory_order_acquire))) { + if (mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_seq_cst, std::memory_order_relaxed) || + mainHash->entries[index].key.compare_exchange_strong(reusable, id, std::memory_order_seq_cst, std::memory_order_relaxed)) { #else - if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed, std::memory_order_relaxed))) { + if (mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_seq_cst, std::memory_order_relaxed)) { #endif mainHash->entries[index].value = value; break; @@ -3398,7 +3491,7 @@ class ConcurrentQueue // locked block). mainHash = implicitProducerHash.load(std::memory_order_acquire); if (newCount >= (mainHash->capacity >> 1)) { - auto newCapacity = mainHash->capacity << 1; + size_t newCapacity = mainHash->capacity << 1; while (newCount >= (newCapacity >> 1)) { newCapacity <<= 1; } @@ -3411,7 +3504,7 @@ class ConcurrentQueue } auto newHash = new (raw) ImplicitProducerHash; - newHash->capacity = newCapacity; + newHash->capacity = static_cast(newCapacity); newHash->entries = reinterpret_cast(details::align_for(raw + sizeof(ImplicitProducerHash))); for (size_t i = 0; i != newCapacity; ++i) { new (newHash->entries + i) ImplicitProducerKVP; @@ -3431,15 +3524,11 @@ class ConcurrentQueue // to finish being allocated by another thread (and if we just finished allocating above, the condition will // always be true) if (newCount < (mainHash->capacity >> 1) + (mainHash->capacity >> 2)) { - bool recycled; - auto producer = static_cast(recycle_or_create_producer(false, recycled)); + auto producer = static_cast(recycle_or_create_producer(false)); if (producer == nullptr) { implicitProducerHashCount.fetch_sub(1, std::memory_order_relaxed); return nullptr; } - if (recycled) { - implicitProducerHashCount.fetch_sub(1, std::memory_order_relaxed); - } #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED producer->threadExitListener.callback = &ConcurrentQueue::implicit_producer_thread_exited_callback; @@ -3449,17 +3538,17 @@ class ConcurrentQueue auto index = hashedId; while (true) { - index &= mainHash->capacity - 1; - auto probedKey = mainHash->entries[index].key.load(std::memory_order_relaxed); - + index &= mainHash->capacity - 1u; auto empty = details::invalid_thread_id; #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED auto reusable = details::invalid_thread_id2; - if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed, std::memory_order_relaxed)) || - (probedKey == reusable && mainHash->entries[index].key.compare_exchange_strong(reusable, id, std::memory_order_acquire, std::memory_order_acquire))) { -#else - if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed, std::memory_order_relaxed))) { + if (mainHash->entries[index].key.compare_exchange_strong(reusable, id, std::memory_order_seq_cst, std::memory_order_relaxed)) { + implicitProducerHashCount.fetch_sub(1, std::memory_order_relaxed); // already counted as a used slot + mainHash->entries[index].value = producer; + break; + } #endif + if (mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_seq_cst, std::memory_order_relaxed)) { mainHash->entries[index].value = producer; break; } @@ -3478,9 +3567,6 @@ class ConcurrentQueue #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED void implicit_producer_thread_exited(ImplicitProducer* producer) { - // Remove from thread exit listeners - details::ThreadExitNotifier::unsubscribe(&producer->threadExitListener); - // Remove from hash #ifdef MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH debug::DebugLock lock(implicitProdMutex); @@ -3496,10 +3582,9 @@ class ConcurrentQueue for (; hash != nullptr; hash = hash->prev) { auto index = hashedId; do { - index &= hash->capacity - 1; - probedKey = hash->entries[index].key.load(std::memory_order_relaxed); - if (probedKey == id) { - hash->entries[index].key.store(details::invalid_thread_id2, std::memory_order_release); + index &= hash->capacity - 1u; + probedKey = id; + if (hash->entries[index].key.compare_exchange_strong(probedKey, details::invalid_thread_id2, std::memory_order_seq_cst, std::memory_order_relaxed)) { break; } ++index; @@ -3525,23 +3610,26 @@ class ConcurrentQueue template static inline void* aligned_malloc(size_t size) { - if (std::alignment_of::value <= std::alignment_of::value) + MOODYCAMEL_CONSTEXPR_IF (std::alignment_of::value <= std::alignment_of::value) return (Traits::malloc)(size); - size_t alignment = std::alignment_of::value; - void* raw = (Traits::malloc)(size + alignment - 1 + sizeof(void*)); - if (!raw) - return nullptr; - char* ptr = details::align_for(reinterpret_cast(raw) + sizeof(void*)); - *(reinterpret_cast(ptr) - 1) = raw; - return ptr; + else { + size_t alignment = std::alignment_of::value; + void* raw = (Traits::malloc)(size + alignment - 1 + sizeof(void*)); + if (!raw) + return nullptr; + char* ptr = details::align_for(reinterpret_cast(raw) + sizeof(void*)); + *(reinterpret_cast(ptr) - 1) = raw; + return ptr; + } } template static inline void aligned_free(void* ptr) { - if (std::alignment_of::value <= std::alignment_of::value) + MOODYCAMEL_CONSTEXPR_IF (std::alignment_of::value <= std::alignment_of::value) return (Traits::free)(ptr); - (Traits::free)(ptr ? *(reinterpret_cast(ptr) - 1) : nullptr); + else + (Traits::free)(ptr ? *(reinterpret_cast(ptr) - 1) : nullptr); } template @@ -3647,7 +3735,7 @@ ConsumerToken::ConsumerToken(ConcurrentQueue& queue) : itemsConsumedFromCurrent(0), currentProducer(nullptr), desiredProducer(nullptr) { initialOffset = queue.nextExplicitConsumerId.fetch_add(1, std::memory_order_release); - lastKnownGlobalOffset = uint32_t(-1); + lastKnownGlobalOffset = static_cast(-1); } template @@ -3655,7 +3743,7 @@ ConsumerToken::ConsumerToken(BlockingConcurrentQueue& queue) : itemsConsumedFromCurrent(0), currentProducer(nullptr), desiredProducer(nullptr) { initialOffset = reinterpret_cast*>(&queue)->nextExplicitConsumerId.fetch_add(1, std::memory_order_release); - lastKnownGlobalOffset = uint32_t(-1); + lastKnownGlobalOffset = static_cast(-1); } template @@ -3682,3 +3770,7 @@ inline void swap(typename ConcurrentQueue::ImplicitProducerKVP& a, ty } +#if defined(_MSC_VER) && (!defined(_HAS_CXX17) || !_HAS_CXX17) +#pragma warning(pop) +#endif + diff --git a/src/duckdb/third_party/concurrentqueue/lightweightsemaphore.h b/src/duckdb/third_party/concurrentqueue/lightweightsemaphore.h index a0875a398..e9baa70e6 100644 --- a/src/duckdb/third_party/concurrentqueue/lightweightsemaphore.h +++ b/src/duckdb/third_party/concurrentqueue/lightweightsemaphore.h @@ -5,21 +5,15 @@ #pragma once -#include // For std::size_t #include -#include +#include // assert +#include // For EINTR +#include // For std::size_t +#include // For std::uint64_t +#include // For clock_gettime +#include #include // For std::make_signed -// VS2012 doesn't support deleted functions. -// In this case, we declare the function normally but don't define it. -#ifndef MOODYCAMEL_DELETE_FUNCTION -#if defined(_MSC_VER) && _MSC_VER < 1800 -#define MOODYCAMEL_DELETE_FUNCTION -#else -#define MOODYCAMEL_DELETE_FUNCTION = delete -#endif -#endif - #if defined(_WIN32) // Avoid including windows.h in a header; we only need a handful of // items, so we'll redeclare them here (this is relatively safe since @@ -35,12 +29,24 @@ extern "C" { } #elif defined(__MACH__) #include -#elif defined(__unix__) -#include -#include #elif defined(__MVS__) #include -#include +#elif defined(__unix__) +#include + +#if defined(__GLIBC_PREREQ) && defined(_GNU_SOURCE) +#if __GLIBC_PREREQ(2,30) +#define MOODYCAMEL_LIGHTWEIGHTSEMAPHORE_MONOTONIC +#endif +#endif +#endif + +#ifndef MOODYCAMEL_DELETE_FUNCTION +#if __cplusplus >= 201103L || _MSC_VER >= 1900 +#define MOODYCAMEL_DELETE_FUNCTION = delete +#else +#define MOODYCAMEL_DELETE_FUNCTION +#endif #endif namespace duckdb_moodycamel @@ -154,7 +160,7 @@ class Semaphore { mach_timespec_t ts; ts.tv_sec = static_cast(timeout_usecs / 1000000); - ts.tv_nsec = (timeout_usecs % 1000000) * 1000; + ts.tv_nsec = static_cast((timeout_usecs % 1000000) * 1000); // added in OSX 10.10: https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/modules/Darwin.html kern_return_t rc = semaphore_timedwait(m_sema, ts); @@ -176,7 +182,7 @@ class Semaphore }; #elif defined(__unix__) || defined(__MVS__) //--------------------------------------------------------- -// Semaphore (POSIX, Linux, zOS aka MVS) +// Semaphore (POSIX, Linux, zOS) //--------------------------------------------------------- class Semaphore { @@ -190,7 +196,7 @@ class Semaphore Semaphore(int initialCount = 0) { assert(initialCount >= 0); - int rc = sem_init(&m_sema, 0, initialCount); + int rc = sem_init(&m_sema, 0, static_cast(initialCount)); assert(rc == 0); (void)rc; } @@ -224,23 +230,19 @@ class Semaphore struct timespec ts; const int usecs_in_1_sec = 1000000; const int nsecs_in_1_sec = 1000000000; - - // sem_timedwait needs an absolute time - // hence we need to first obtain the current time - // and then add the maximum time we want to wait - // we want to avoid clock_gettime because of linking issues - // chrono -> timespec conversion from here: https://embeddedartistry.com/blog/2019/01/31/converting-between-timespec-stdchrono/ +#ifdef MOODYCAMEL_LIGHTWEIGHTSEMAPHORE_MONOTONIC + clock_gettime(CLOCK_MONOTONIC, &ts); +#else + // Preserve the portable realtime-clock fallback used by DuckDB. auto current_time = std::chrono::system_clock::now(); - auto secs = std::chrono::time_point_cast(current_time); - auto ns = std::chrono::time_point_cast(current_time) - std::chrono::time_point_cast(secs); - - ts.tv_sec = secs.time_since_epoch().count(); - ts.tv_nsec = ns.count(); - - // now add the time we want to wait - ts.tv_sec += usecs / usecs_in_1_sec; - ts.tv_nsec += (usecs % usecs_in_1_sec) * 1000; - + auto secs = std::chrono::time_point_cast(current_time); + auto ns = std::chrono::time_point_cast(current_time) - + std::chrono::time_point_cast(secs); + ts.tv_sec = static_cast(secs.time_since_epoch().count()); + ts.tv_nsec = static_cast(ns.count()); +#endif + ts.tv_sec += static_cast(usecs / usecs_in_1_sec); + ts.tv_nsec += static_cast(usecs % usecs_in_1_sec) * 1000; // sem_timedwait bombs if you have more than 1e9 in tv_nsec // so we have to clean things up before passing it in if (ts.tv_nsec >= nsecs_in_1_sec) { @@ -250,7 +252,11 @@ class Semaphore int rc; do { +#ifdef MOODYCAMEL_LIGHTWEIGHTSEMAPHORE_MONOTONIC + rc = sem_clockwait(&m_sema, CLOCK_MONOTONIC, &ts); +#else rc = sem_timedwait(&m_sema, &ts); +#endif } while (rc == -1 && errno == EINTR); return rc == 0; } @@ -285,15 +291,15 @@ class LightweightSemaphore private: std::atomic m_count; + // Keep the spinning count separate from the OS semaphore without over-alignment. + char m_padding[128 - sizeof(std::atomic)]; details::Semaphore m_sema; + int m_maxSpins; bool waitWithPartialSpinning(std::int64_t timeout_usecs = -1) { ssize_t oldCount; - // Is there a better way to set the initial spin count? - // If we lower it to 1000, testBenaphore becomes 15x slower on my Core i7-5930K Windows PC, - // as threads start hitting the kernel semaphore. - int spin = 10000; + int spin = m_maxSpins; while (--spin >= 0) { oldCount = m_count.load(std::memory_order_relaxed); @@ -305,8 +311,11 @@ class LightweightSemaphore if (oldCount > 0) return true; if (timeout_usecs < 0) - return m_sema.wait(); - if (m_sema.timed_wait((std::uint64_t)timeout_usecs)) + { + if (m_sema.wait()) + return true; + } + if (timeout_usecs > 0 && m_sema.timed_wait(static_cast(timeout_usecs))) return true; // At this point, we've timed out waiting for the semaphore, but the // count is still decremented indicating we may still be waiting on @@ -327,7 +336,7 @@ class LightweightSemaphore { assert(max > 0); ssize_t oldCount; - int spin = 10000; + int spin = m_maxSpins; while (--spin >= 0) { oldCount = m_count.load(std::memory_order_relaxed); @@ -342,12 +351,7 @@ class LightweightSemaphore oldCount = m_count.fetch_sub(1, std::memory_order_acquire); if (oldCount <= 0) { - if (timeout_usecs < 0) - { - if (!m_sema.wait()) - return 0; - } - else if (!m_sema.timed_wait((std::uint64_t)timeout_usecs)) + if ((timeout_usecs == 0) || (timeout_usecs < 0 && !m_sema.wait()) || (timeout_usecs > 0 && !m_sema.timed_wait(static_cast(timeout_usecs)))) { while (true) { @@ -365,9 +369,11 @@ class LightweightSemaphore } public: - LightweightSemaphore(ssize_t initialCount = 0) : m_count(initialCount) + LightweightSemaphore(ssize_t initialCount = 0, int maxSpins = 10000) : m_count(initialCount), m_maxSpins(maxSpins) { + (void)m_padding; assert(initialCount >= 0); + assert(maxSpins >= 0); } bool tryWait() @@ -429,14 +435,14 @@ class LightweightSemaphore ssize_t toRelease = -oldCount < count ? -oldCount : count; if (toRelease > 0) { - m_sema.signal((int)toRelease); + m_sema.signal(static_cast(toRelease)); } } - ssize_t availableApprox() const + std::size_t availableApprox() const { ssize_t count = m_count.load(std::memory_order_relaxed); - return count > 0 ? count : 0; + return count > 0 ? static_cast(count) : 0; } }; diff --git a/src/duckdb/third_party/jemalloc/src/jemalloc_cpp.cpp b/src/duckdb/third_party/jemalloc/src/jemalloc_cpp.cpp index aedccfa55..adfa7176a 100644 --- a/src/duckdb/third_party/jemalloc/src/jemalloc_cpp.cpp +++ b/src/duckdb/third_party/jemalloc/src/jemalloc_cpp.cpp @@ -97,7 +97,7 @@ handleOOM(std::size_t size, bool nothrow) { } if (ptr == nullptr && !nothrow) - std::__throw_bad_alloc(); + throw std::bad_alloc(); return ptr; } diff --git a/src/duckdb/ub_src_execution.cpp b/src/duckdb/ub_src_execution.cpp index 8159c07dc..2578200ba 100644 --- a/src/duckdb/ub_src_execution.cpp +++ b/src/duckdb/ub_src_execution.cpp @@ -20,6 +20,8 @@ #include "src/execution/perfect_aggregate_hashtable.cpp" +#include "src/execution/perfect_hash_join_table.cpp" + #include "src/execution/physical_operator.cpp" #include "src/execution/physical_plan_generator.cpp" diff --git a/src/duckdb/ub_src_execution_operator_helper.cpp b/src/duckdb/ub_src_execution_operator_helper.cpp index 42a29cf47..b32224430 100644 --- a/src/duckdb/ub_src_execution_operator_helper.cpp +++ b/src/duckdb/ub_src_execution_operator_helper.cpp @@ -6,8 +6,6 @@ #include "src/execution/operator/helper/physical_disconnect.cpp" -#include "src/execution/operator/helper/physical_execute.cpp" - #include "src/execution/operator/helper/physical_explain_analyze.cpp" #include "src/execution/operator/helper/physical_external_resource.cpp" diff --git a/src/duckdb/ub_src_execution_operator_join.cpp b/src/duckdb/ub_src_execution_operator_join.cpp index ed0c6c1dc..f971faf76 100644 --- a/src/duckdb/ub_src_execution_operator_join.cpp +++ b/src/duckdb/ub_src_execution_operator_join.cpp @@ -1,7 +1,5 @@ #include "src/execution/operator/join/outer_join_marker.cpp" -#include "src/execution/operator/join/perfect_hash_join_executor.cpp" - #include "src/execution/operator/join/physical_asof_join.cpp" #include "src/execution/operator/join/physical_blockwise_nl_join.cpp" diff --git a/src/duckdb/ub_src_execution_physical_plan.cpp b/src/duckdb/ub_src_execution_physical_plan.cpp index 1161c0dae..b179d1ff6 100644 --- a/src/duckdb/ub_src_execution_physical_plan.cpp +++ b/src/duckdb/ub_src_execution_physical_plan.cpp @@ -48,8 +48,6 @@ #include "src/execution/physical_plan/plan_empty_result.cpp" -#include "src/execution/physical_plan/plan_execute.cpp" - #include "src/execution/physical_plan/plan_explain.cpp" #include "src/execution/physical_plan/plan_export.cpp" diff --git a/src/duckdb/ub_src_logging.cpp b/src/duckdb/ub_src_logging.cpp index db3a318e3..45a901da6 100644 --- a/src/duckdb/ub_src_logging.cpp +++ b/src/duckdb/ub_src_logging.cpp @@ -1,6 +1,6 @@ #include "src/logging/log_manager.cpp" -#include "src/logging/log_storage.cpp" +#include "src/logging/log_sink.cpp" #include "src/logging/log_types.cpp" diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index 1167bd01a..68664b8eb 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -38,6 +38,8 @@ #include "src/optimizer/disjunctive_join_rewriter.cpp" +#include "src/optimizer/duplicate_eliminated_domain_optimizer.cpp" + #include "src/optimizer/empty_result_pullup.cpp" #include "src/optimizer/expression_heuristics.cpp" @@ -56,6 +58,8 @@ #include "src/optimizer/in_clause_rewriter.cpp" +#include "src/optimizer/join_build_properties.cpp" + #include "src/optimizer/join_elimination.cpp" #include "src/optimizer/join_filter_pushdown_optimizer.cpp" @@ -82,6 +86,8 @@ #include "src/optimizer/projection_pullup.cpp" +#include "src/optimizer/recursive_join_planning.cpp" + #include "src/optimizer/regex_range_filter.cpp" #include "src/optimizer/remote_pushdown_optimizer.cpp" diff --git a/src/duckdb/ub_src_optimizer_join_order.cpp b/src/duckdb/ub_src_optimizer_join_order.cpp index 4c7f3234c..ad09a8c90 100644 --- a/src/duckdb/ub_src_optimizer_join_order.cpp +++ b/src/duckdb/ub_src_optimizer_join_order.cpp @@ -10,6 +10,8 @@ #include "src/optimizer/join_order/join_order_optimizer.cpp" +#include "src/optimizer/join_order/join_order_source_stats.cpp" + #include "src/optimizer/join_order/join_predicate.cpp" #include "src/optimizer/join_order/join_relation_set.cpp" diff --git a/src/duckdb/ub_src_optimizer_statistics_operator.cpp b/src/duckdb/ub_src_optimizer_statistics_operator.cpp index 907c334f8..6abaf5179 100644 --- a/src/duckdb/ub_src_optimizer_statistics_operator.cpp +++ b/src/duckdb/ub_src_optimizer_statistics_operator.cpp @@ -20,5 +20,7 @@ #include "src/optimizer/statistics/operator/propagate_set_operation.cpp" +#include "src/optimizer/statistics/operator/propagate_unnest.cpp" + #include "src/optimizer/statistics/operator/propagate_window.cpp" diff --git a/src/duckdb/ub_src_parser_parsed_data.cpp b/src/duckdb/ub_src_parser_parsed_data.cpp index 2bbd7f779..dc2fca713 100644 --- a/src/duckdb/ub_src_parser_parsed_data.cpp +++ b/src/duckdb/ub_src_parser_parsed_data.cpp @@ -2,6 +2,8 @@ #include "src/parser/parsed_data/alter_info.cpp" +#include "src/parser/parsed_data/alter_macro_info.cpp" + #include "src/parser/parsed_data/alter_scalar_function_info.cpp" #include "src/parser/parsed_data/alter_schema_info.cpp"