diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index a1e1e1143..60b431b27 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -49,7 +49,7 @@ struct KahanAvgState { void Combine(const KahanAvgState &other) { this->count += other.count; KahanAddInternal(other.value, this->value, this->err); - KahanAddInternal(-other.err, this->value, this->err); + this->err += other.err; } }; @@ -229,6 +229,92 @@ struct TimestampAverageOperation : public DiscreteAverageOperation { } }; +//! The average of timestamps in nanosecond resolution - mirrors TimestampAverageOperation, but +//! interprets the state value as a nanosecond timestamp so infinity is the ns infinity +template +struct TimestampNSAverageOperation : public DiscreteAverageOperation { + static constexpr uint64_t INFINITE_COUNT = NumericLimits::Maximum(); + static constexpr uint64_t POSITIVE_INFINITY = 1; + static constexpr uint64_t NEGATIVE_INFINITY = 2; + static constexpr uint64_t BOTH_INFINITIES = POSITIVE_INFINITY | NEGATIVE_INFINITY; + + template + static void AddInfinities(STATE &state, uint64_t infinities) { + if (state.count != INFINITE_COUNT) { + state.count = INFINITE_COUNT; + state.value = hugeint_t(0); + } + state.value.lower |= infinities; + } + + static uint64_t GetInfinity(int64_t input) { + return input > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY; + } + + template + static void Combine(const STATE &source, STATE &target, AggregateInputData &) { + if (source.count == INFINITE_COUNT) { + AddInfinities(target, source.value.lower); + } else if (source.count != 0 && target.count != INFINITE_COUNT) { + if (target.count == 0) { + // an empty target holds no sum + target.value = hugeint_t(0); + } + if (!TryAddOperator::Operation(target.count, source.count, target.count) || + target.count == INFINITE_COUNT) { + throw OutOfRangeException("Overflow in aggregate state combine"); + } + CombineSumStateValue(target.value, source.value); + } + } + + template + static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) { + if (source.count == INFINITE_COUNT) { + if (count > 0) { + AddInfinities(target, source.value.lower); + } + } else if (target.count != INFINITE_COUNT) { + DiscreteAverageOperation::RepeatedCombine(source, target, input, count); + if (target.count == INFINITE_COUNT) { + throw OutOfRangeException("Overflow in repeated aggregate state combine"); + } + } + } + + template + static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { + if (DUCKDB_UNLIKELY(!NS_TIMESTAMP(input).IsFinite())) { + AddInfinities(state, GetInfinity(input)); + } else if (state.count != INFINITE_COUNT) { + DiscreteAverageOperation::Operation(state, input, unary_input); + } + } + + template + static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input, + idx_t count) { + if (DUCKDB_UNLIKELY(!NS_TIMESTAMP(input).IsFinite())) { + AddInfinities(state, GetInfinity(input)); + } else if (state.count != INFINITE_COUNT) { + DiscreteAverageOperation::ConstantOperation(state, input, unary_input, count); + } + } + + template + static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) { + if (state.count != INFINITE_COUNT) { + DiscreteAverageOperation::Finalize(state, target, finalize_data); + } else if (state.value == hugeint_t(POSITIVE_INFINITY)) { + target = NS_TIMESTAMP::infinity().value; + } else if (state.value == hugeint_t(NEGATIVE_INFINITY)) { + target = NS_TIMESTAMP::ninfinity().value; + } else { + finalize_data.ReturnNull(); + } + } +}; + //! A state with the maximum count holds only infinities, reject imported ones that hold other values void ValidateTimestampAverageStates(const_data_ptr_t states, idx_t count, idx_t stride) { for (idx_t i = 0; i < count; i++) { @@ -271,6 +357,27 @@ AggregateStateLayout TimeAverageStateLayout(AggregateLayoutInput &input) { return layout; } +//! The average of TIME_NS values is within a day - reject imported states that average outside of it +void ValidateTimeNSAverageStates(const_data_ptr_t states, idx_t count, idx_t stride) { + for (idx_t i = 0; i < count; i++) { + const auto state = Load>(states + i * stride); + if (state.count == 0) { + continue; + } + const auto max_value = hugeint_t(0, state.count) * hugeint_t(Interval::NANOS_PER_DAY); + if (state.value < 0 || state.value > max_value) { + throw InvalidInputException("Invalid avg state - the average of %s over %llu values is not a valid time", + state.value.ToString(), state.count); + } + } +} + +AggregateStateLayout TimeNSAverageStateLayout(AggregateLayoutInput &input) { + auto layout = AggregateFunction::StructStateLayout>(input); + layout.validate_state = ValidateTimeNSAverageStates; + return layout; +} + struct HugeintAverageOperation : public BaseSumOperation { template static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) { @@ -310,7 +417,7 @@ struct KahanAverageOperation : public BaseSumOperation(state.count); } } }; @@ -441,6 +548,35 @@ unique_ptr BindDecimalAvg(BindAggregateFunctionInput &input) { Hugeint::Cast(Hugeint::POWERS_OF_TEN[DecimalType::GetScale(decimal_type)])); } +AggregateFunction GetTimestampAverage() { + auto timestamp_avg = + AggregateFunction::UnaryAggregate, int64_t, int64_t, TimestampAverageOperation>( + LogicalType::TIMESTAMP, LogicalType::TIMESTAMP); + timestamp_avg.GetSignature().GetParameter(0).SetName("x"); + timestamp_avg.SetStructStateExport(TimestampAverageStateLayout); + return timestamp_avg; +} + +//! Averages the argument as a TIMESTAMP, whose range holds every ordinary date of the lower precisions +unique_ptr BindWidenedTimestampAvg(BindAggregateFunctionInput &input) { + auto &function = input.GetBoundFunction(); + function.ReplaceImplementation(GetTimestampAverage()); + function.SetName("avg"); + function.GetArguments()[0] = LogicalType::TIMESTAMP; + function.SetReturnType(LogicalType::TIMESTAMP); + return nullptr; +} + +//! Without an overload of their own, TIMESTAMP_S, TIMESTAMP_MS and DATE would widen to TIMESTAMP_NS, the cheapest +//! implicit cast, whose range is far smaller than theirs +AggregateFunction GetWidenedTimestampAverage(const LogicalType &type) { + // stub function, the bind sets the TIMESTAMP implementation and the argument type it casts to + AggregateFunction fun({}, LogicalType::TIMESTAMP, nullptr, nullptr, nullptr, nullptr, nullptr, + FunctionNullHandling::DEFAULT_NULL_HANDLING, nullptr, BindWidenedTimestampAvg); + fun.GetSignature().AddParameter("x", type); + return fun; +} + } // namespace AggregateFunctionSet AvgFun::GetFunctions() { @@ -461,12 +597,10 @@ AggregateFunctionSet AvgFun::GetFunctions() { numeric_avg.GetSignature().GetParameter(0).SetName("x"); avg.AddFunction(numeric_avg); - auto timestamp_avg = - AggregateFunction::UnaryAggregate, int64_t, int64_t, TimestampAverageOperation>( - LogicalType::TIMESTAMP, LogicalType::TIMESTAMP); - timestamp_avg.GetSignature().GetParameter(0).SetName("x"); - timestamp_avg.SetStructStateExport(TimestampAverageStateLayout); - avg.AddFunction(timestamp_avg); + avg.AddFunction(GetTimestampAverage()); + for (auto &type : {LogicalType::TIMESTAMP_S, LogicalType::TIMESTAMP_MS, LogicalType::DATE}) { + avg.AddFunction(GetWidenedTimestampAverage(type)); + } auto timestamp_tz_avg = AggregateFunction::UnaryAggregate, int64_t, int64_t, TimestampAverageOperation>( @@ -488,6 +622,27 @@ AggregateFunctionSet AvgFun::GetFunctions() { time_tz_avg.SetStructStateExport(TimeAverageStateLayout); avg.AddFunction(time_tz_avg); + auto timestamp_ns_avg = AggregateFunction::UnaryAggregate, int64_t, int64_t, + TimestampNSAverageOperation>( + LogicalType::TIMESTAMP_NS, LogicalType::TIMESTAMP_NS); + timestamp_ns_avg.GetSignature().GetParameter(0).SetName("x"); + timestamp_ns_avg.SetStructStateExport(TimestampAverageStateLayout); + avg.AddFunction(timestamp_ns_avg); + + auto timestamp_tz_ns_avg = AggregateFunction::UnaryAggregate, int64_t, int64_t, + TimestampNSAverageOperation>( + LogicalType::TIMESTAMP_TZ_NS, LogicalType::TIMESTAMP_TZ_NS); + timestamp_tz_ns_avg.GetSignature().GetParameter(0).SetName("x"); + timestamp_tz_ns_avg.SetStructStateExport(TimestampAverageStateLayout); + avg.AddFunction(timestamp_tz_ns_avg); + + auto time_ns_avg = + AggregateFunction::UnaryAggregate, int64_t, int64_t, DiscreteAverageOperation>( + LogicalType::TIME_NS, LogicalType::TIME_NS); + time_ns_avg.GetSignature().GetParameter(0).SetName("x"); + time_ns_avg.SetStructStateExport(TimeNSAverageStateLayout); + avg.AddFunction(time_ns_avg); + return avg; } diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index 0ec027396..36ef2f3d2 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -218,7 +218,7 @@ struct KahanSumOperation : public BaseSumOperation( type, type); } - if (type.id() == LogicalTypeId::TIMESTAMP || type.id() == LogicalTypeId::TIMESTAMP_TZ) { + if (type.id() == LogicalTypeId::TIMESTAMP || type.id() == LogicalTypeId::TIMESTAMP_TZ || + type.id() == LogicalTypeId::TIMESTAMP_NS || type.id() == LogicalTypeId::TIMESTAMP_TZ_NS) { + // every timestamp precision stores an int64 with the same two infinities, which the coding keeps infinite return AggregateFunction::UnaryAggregate(type, type); } @@ -466,10 +468,10 @@ AggregateFunction ApproxQuantileDecimalFunction(const LogicalType &type) { return function; } -//! Specialises the (stub) DECIMAL function to the implementation over the DECIMAL's physical type. The implementation -//! only declares the input argument, so the quantile argument that BindApproxQuantile folded into the bind data is -//! restored afterwards. -void ReplaceApproxQuantileDecimal(BoundAggregateFunction &function, const AggregateFunction &implementation) { +//! Specialises a stub function, the DECIMAL ones to the implementation over the DECIMAL's physical type and the +//! TIMESTAMP_S and TIMESTAMP_MS ones to the TIMESTAMP implementation. The implementation only declares the input +//! argument, so the quantile argument that BindApproxQuantile folded into the bind data is restored afterwards. +void ReplaceApproxQuantileImplementation(BoundAggregateFunction &function, const AggregateFunction &implementation) { auto declared_arguments = function.GetArguments(); function.ReplaceImplementation(implementation); for (idx_t i = function.GetArguments().size(); i < declared_arguments.size(); i++) { @@ -482,7 +484,7 @@ unique_ptr BindApproxQuantileDecimal(BindAggregateFunctionInput &i auto &arguments = input.GetArguments(); auto decimal_type = arguments[0]->GetReturnType(); auto bind_data = BindApproxQuantile(input); - ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalFunction(decimal_type)); + ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(decimal_type)); return bind_data; } @@ -609,7 +611,7 @@ unique_ptr BindApproxQuantileDecimalList(BindAggregateFunctionInpu auto &arguments = input.GetArguments(); auto decimal_type = arguments[0]->GetReturnType(); auto bind_data = BindApproxQuantile(input); - ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalListFunction(decimal_type)); + ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(decimal_type)); return bind_data; } @@ -631,9 +633,9 @@ unique_ptr ApproxQuantileDecimalDeserialize(Deserializer &deserial auto bind_data = ApproximateQuantileBindData::Deserialize(deserializer, function); auto &return_type = deserializer.Get(); if (return_type.id() == LogicalTypeId::LIST) { - ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalListFunction(function.GetArguments()[0])); + ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(function.GetArguments()[0])); } else { - ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalFunction(function.GetArguments()[0])); + ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(function.GetArguments()[0])); } return bind_data; } @@ -648,6 +650,37 @@ AggregateFunction GetApproxQuantileDecimal() { return fun; } +//! The TIMESTAMP implementation, which TIMESTAMP_S and TIMESTAMP_MS arguments are widened to +AggregateFunction ApproxQuantileTimestampFunction() { + auto function = GetApproximateQuantileAggregateFunction(LogicalType::TIMESTAMP); + function.SetName("approx_quantile"); + function.SetSerializeCallback(ApproximateQuantileBindData::Serialize); + function.SetDeserializeCallback(ApproximateQuantileBindData::Deserialize); + function.SetStateExportCallbacks(ApproxQuantileGetStateType, ApproxQuantileExportState, ApproxQuantileImportState); + return function; +} + +unique_ptr BindApproxQuantileWidenedTimestamp(BindAggregateFunctionInput &input) { + auto &function = input.GetBoundFunction(); + auto bind_data = BindApproxQuantile(input); + ReplaceApproxQuantileImplementation(function, ApproxQuantileTimestampFunction()); + function.GetArguments()[0] = LogicalType::TIMESTAMP; + function.SetReturnType(LogicalType::TIMESTAMP); + return bind_data; +} + +//! Without an overload of their own, TIMESTAMP_S and TIMESTAMP_MS would widen to TIMESTAMP_NS, the cheapest implicit +//! cast, whose range is far smaller than theirs +AggregateFunction GetApproxQuantileWidenedTimestamp(const LogicalType &type) { + // stub function, the bind sets the TIMESTAMP implementation and the argument type it casts to + AggregateFunction fun({}, LogicalType::TIMESTAMP, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + BindApproxQuantileWidenedTimestamp); + fun.GetSignature().AddParameter("x", type).AddParameter("pos", LogicalType::FLOAT); + fun.SetSerializeCallback(ApproximateQuantileBindData::Serialize); + fun.SetDeserializeCallback(ApproximateQuantileBindData::Deserialize); + return fun; +} + AggregateFunction GetApproxQuantileDecimalList() { // stub function - the actual function is set during bind or deserialize AggregateFunction fun({}, LogicalType::LIST(LogicalTypeId::DECIMAL), nullptr, nullptr, nullptr, nullptr, nullptr, @@ -673,9 +706,14 @@ AggregateFunctionSet ApproxQuantileFun::GetFunctions() { approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::DATE)); approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME)); + approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME_NS)); approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME_TZ)); approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP)); + approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_NS)); approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_TZ)); + approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_TZ_NS)); + approx_quantile.AddFunction(GetApproxQuantileWidenedTimestamp(LogicalType::TIMESTAMP_S)); + approx_quantile.AddFunction(GetApproxQuantileWidenedTimestamp(LogicalType::TIMESTAMP_MS)); // List variants approx_quantile.AddFunction(GetApproxQuantileDecimalList()); diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp index 18afe93f8..c393067da 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp @@ -547,7 +547,7 @@ AggregateFunction GetContinuousQuantileTemplated(const LogicalType &type) { } case LogicalTypeId::DATE: { auto fun = OP::template GetFunction(type, LogicalType::TIMESTAMP); - fun.SetFallible(); // interpolation casts to TIMESTAMP, which throws for dates outside of the timestamp range + fun.SetFallible(); // the TIMESTAMP cast throws for out-of-range dates, interpolation for the infinities return fun; } case LogicalTypeId::TIMESTAMP: @@ -555,8 +555,11 @@ AggregateFunction GetContinuousQuantileTemplated(const LogicalType &type) { case LogicalTypeId::TIMESTAMP_TZ_NS: case LogicalTypeId::TIMESTAMP_SEC: case LogicalTypeId::TIMESTAMP_MS: - case LogicalTypeId::TIMESTAMP_NS: - return OP::template GetFunction(type, type); + case LogicalTypeId::TIMESTAMP_NS: { + auto fun = OP::template GetFunction(type, type); + fun.SetFallible(); // interpolation throws for the infinities + return fun; + } case LogicalTypeId::TIME: return OP::template GetFunction(type, type); case LogicalTypeId::TIME_TZ: diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp index e25e76580..b57809456 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp @@ -323,7 +323,8 @@ double CheckReservoirQuantile(const Value &quantile_val) { unique_ptr BindReservoirQuantile(BindAggregateFunctionInput &input) { Value quantile_val = input.GetConstant(1); vector quantiles; - if (quantile_val.type().id() != LogicalTypeId::LIST) { + // a NULL list is rejected like a NULL quantile + if (quantile_val.IsNull() || quantile_val.type().id() != LogicalTypeId::LIST) { quantiles.push_back(CheckReservoirQuantile(quantile_val)); } else { for (const auto &element_val : ListValue::GetChildren(quantile_val)) { diff --git a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp index 3158a924a..078ea887c 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp @@ -318,7 +318,16 @@ void HistogramBinFinalizeFunction(Vector &state_vector, AggregateFinalizeInputDa if (state.counts->back() > 0 && supports_other_bucket) { // add overflow bucket ("others") // set bin boundary to NULL for overflow bucket - keys.SetValue(current_offset, OtherBucketValue(keys.GetType())); + auto other_value = OtherBucketValue(keys.GetType()); + for (idx_t bin_idx = list_entry.offset; bin_idx < current_offset; bin_idx++) { + if (Value::NotDistinctFrom(keys.GetValue(bin_idx), other_value)) { + throw InvalidInputException( + "Histogram bin %s collides with the key of the \"other values\" bucket, " + "which has entries - use a different bin value", + other_value.ToSQLString()); + } + } + keys.SetValue(current_offset, other_value); count_entries[current_offset] = state.counts->back(); current_offset++; } @@ -392,7 +401,8 @@ unique_ptr HistogramBinBindFunction(BindAggregateFunctionInput &in } } - function.ReplaceImplementation(GetHistogramBinFunction(arguments[0]->GetReturnType())); + // the template signature resolved both parameters to the deduced bin type + function.ReplaceImplementation(GetHistogramBinFunction(function.GetArguments()[0])); return nullptr; } @@ -402,8 +412,8 @@ AggregateFunction HistogramFun::BinnedHistogramFunction() { AggregateFunction function("histogram", {}, LogicalTypeId::MAP, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, HistogramBinBindFunction, nullptr); function.GetSignature() - .AddParameter("arg", LogicalType::ANY) - .AddParameter("bins", LogicalType::LIST(LogicalType::ANY)); + .AddParameter("arg", LogicalType::TEMPLATE("T")) + .AddParameter("bins", LogicalType::LIST(LogicalType::TEMPLATE("T"))); return function; } @@ -411,8 +421,8 @@ AggregateFunction HistogramExactFun::GetFunction() { AggregateFunction function("histogram_exact", {}, LogicalTypeId::MAP, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, HistogramBinBindFunction, nullptr); function.GetSignature() - .AddParameter("arg", LogicalType::ANY) - .AddParameter("bins", LogicalType::LIST(LogicalType::ANY)); + .AddParameter("arg", LogicalType::TEMPLATE("T")) + .AddParameter("bins", LogicalType::LIST(LogicalType::TEMPLATE("T"))); return function; } 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 1986896fa..59cc898d3 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 @@ -12,6 +12,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" +#include "duckdb/common/types/value.hpp" #include "duckdb/function/aggregate_state.hpp" #include "duckdb/function/aggregate_state_layout.hpp" #include "duckdb/common/operator/cast_operators.hpp" @@ -66,13 +67,21 @@ struct RepeatedStateValue { } }; +//! Neumaier summation: the exact rounding error of each addition (TwoSum) is accumulated in err +//! The compensated sum is summed - err static inline void KahanAddInternal(double input, double &summed, double &err) { - double diff = input - err; - double newval = summed + diff; - err = (newval - summed) - diff; + double newval = summed + input; + double input_part = newval - summed; + double rounding = (summed - (newval - input_part)) + (input - input_part); + err -= rounding; summed = newval; } +static inline double KahanFinalize(double summed, double err) { + // once the sum overflows the error term is meaningless (inf - inf) + return Value::IsFinite(summed) ? summed - err : summed; +} + template static inline void CombineSumStateValue(T &target, const T &source) { if constexpr (std::is_same::value) { @@ -101,7 +110,7 @@ struct KahanSumState { void Combine(const KahanSumState &other) { this->is_set = other.is_set || this->is_set; KahanAddInternal(other.value, this->value, this->err); - KahanAddInternal(-other.err, this->value, this->err); + this->err += other.err; } }; @@ -278,7 +287,7 @@ inline LogicalType BindDecimalArgument(ClientContext &context, unique_ptr + static auto TryDatePartOperation(T input, TR &result, int) + -> decltype(OP::template TryOperation(input, result)) { + return OP::template TryOperation(input, result); + } + template + static bool TryDatePartOperation(T input, TR &result, long) { + result = OP::template Operation(input); + return true; + } + + template + static inline TR Truncate(const TA &input) { + if (!input.IsFinite()) { + return TR(input.value); + } + const auto scaling = TA::PRECISION / TR::PRECISION; + TR result; + int64_t frac; + Timestamp::SplitTime(input.value, scaling, result.value, frac); + return result; + } + template static unique_ptr PropagateDatePartStatistics(vector &child_stats, const LogicalType &stats_type = LogicalType::BIGINT) { @@ -162,8 +187,12 @@ struct DatePart { if (!min.IsFinite() || !max.IsFinite()) { return nullptr; } - TR min_part = OP::template Operation(min); - TR max_part = OP::template Operation(max); + TR min_part; + TR max_part; + if (!TryDatePartOperation(min, min_part, 0) || !TryDatePartOperation(max, max_part, 0)) { + // the bounds are not representable (e.g. epoch_ns overflow): the error is raised per row during execution + return nullptr; + } auto result = NumericStats::CreateEmpty(stats_type); NumericStats::SetMin(result, Value(min_part)); NumericStats::SetMax(result, Value(max_part)); @@ -475,6 +504,13 @@ struct DatePart { return Timestamp::GetEpochNanoSeconds(input); } + //! Returns false instead of throwing when the result does not fit (specialized for the types that can overflow) + template + static inline bool TryOperation(TA input, TR &result) { + result = Operation(input); + return true; + } + template static unique_ptr PropagateStatistics(ClientContext &context, FunctionStatisticsInput &input) { return PropagateDatePartStatistics(input.child_stats); @@ -484,7 +520,14 @@ struct DatePart { struct EpochMicrosecondsOperator { template static inline TR Operation(TA input) { - return Timestamp::GetEpochMicroSeconds(input); + return Timestamp::GetEpochMicroSeconds(Truncate(input)); + } + + //! Returns false instead of throwing when the result does not fit (specialized for the types that can overflow) + template + static inline bool TryOperation(TA input, TR &result) { + result = Operation(input); + return true; } template @@ -707,7 +750,7 @@ struct DatePart { struct JulianDayOperator { template static inline TR Operation(TA input) { - return Timestamp::GetJulianDay(input); + return Timestamp::GetJulianDay(Truncate(input)); } template @@ -911,6 +954,11 @@ int64_t DatePart::YearOperator::Operation(timestamp_t input) { return YearOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::YearOperator::Operation(timestamp_ns_t input) { + return YearOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::YearOperator::Operation(interval_t input) { return input.months / Interval::MONTHS_PER_YEAR; @@ -936,6 +984,11 @@ int64_t DatePart::MonthOperator::Operation(timestamp_t input) { return MonthOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::MonthOperator::Operation(timestamp_ns_t input) { + return MonthOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::MonthOperator::Operation(interval_t input) { return input.months % Interval::MONTHS_PER_YEAR; @@ -961,6 +1014,11 @@ int64_t DatePart::DayOperator::Operation(timestamp_t input) { return DayOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::DayOperator::Operation(timestamp_ns_t input) { + return DayOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::DayOperator::Operation(interval_t input) { return input.days; @@ -1031,6 +1089,11 @@ int64_t DatePart::QuarterOperator::Operation(timestamp_t input) { return QuarterOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::QuarterOperator::Operation(timestamp_ns_t input) { + return QuarterOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::QuarterOperator::Operation(interval_t input) { return MonthOperator::Operation(input) / Interval::MONTHS_PER_QUARTER + 1; @@ -1056,6 +1119,11 @@ int64_t DatePart::DayOfWeekOperator::Operation(timestamp_t input) { return DayOfWeekOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::DayOfWeekOperator::Operation(timestamp_ns_t input) { + return DayOfWeekOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::DayOfWeekOperator::Operation(interval_t input) { throw NotImplementedException("interval units \"dow\" not recognized"); @@ -1081,6 +1149,11 @@ int64_t DatePart::ISODayOfWeekOperator::Operation(timestamp_t input) { return ISODayOfWeekOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::ISODayOfWeekOperator::Operation(timestamp_ns_t input) { + return ISODayOfWeekOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::ISODayOfWeekOperator::Operation(interval_t input) { throw NotImplementedException("interval units \"isodow\" not recognized"); @@ -1106,6 +1179,11 @@ int64_t DatePart::DayOfYearOperator::Operation(timestamp_t input) { return DayOfYearOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::DayOfYearOperator::Operation(timestamp_ns_t input) { + return DayOfYearOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::DayOfYearOperator::Operation(interval_t input) { throw NotImplementedException("interval units \"doy\" not recognized"); @@ -1131,6 +1209,11 @@ int64_t DatePart::WeekOperator::Operation(timestamp_t input) { return WeekOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::WeekOperator::Operation(timestamp_ns_t input) { + return WeekOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::WeekOperator::Operation(interval_t input) { throw NotImplementedException("interval units \"week\" not recognized"); @@ -1156,6 +1239,11 @@ int64_t DatePart::ISOYearOperator::Operation(timestamp_t input) { return ISOYearOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::ISOYearOperator::Operation(timestamp_ns_t input) { + return ISOYearOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::ISOYearOperator::Operation(interval_t input) { throw NotImplementedException("interval units \"isoyear\" not recognized"); @@ -1181,6 +1269,11 @@ int64_t DatePart::YearWeekOperator::Operation(timestamp_t input) { return YearWeekOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::YearWeekOperator::Operation(timestamp_ns_t input) { + return YearWeekOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::YearWeekOperator::Operation(interval_t input) { const auto yyyy = YearOperator::Operation(input); @@ -1203,16 +1296,41 @@ int64_t DatePart::YearWeekOperator::Operation(dtime_tz_t input) { return YearWeekOperator::Operation(input.time()); } +template <> +bool DatePart::EpochNanosecondsOperator::TryOperation(timestamp_t input, int64_t &result) { + D_ASSERT(input.IsFinite()); + return Timestamp::TryGetEpochNanoSeconds(input, result); +} + +template <> +bool DatePart::EpochNanosecondsOperator::TryOperation(date_t input, int64_t &result) { + D_ASSERT(input.IsFinite()); + return TryMultiplyOperator::Operation(input.days, Interval::MICROS_PER_DAY * 1000, + result); +} + template <> int64_t DatePart::EpochNanosecondsOperator::Operation(timestamp_t input) { + int64_t result; + if (!TryOperation(input, result)) { + throw ConversionException("Could not convert Timestamp(US) to Timestamp(NS)"); + } + return result; +} + +template <> +int64_t DatePart::EpochNanosecondsOperator::Operation(timestamp_tz_ns_t input) { D_ASSERT(input.IsFinite()); - return Timestamp::GetEpochNanoSeconds(input); + return Timestamp::GetEpochNanoSeconds(timestamp_ns_t(input.value)); } template <> int64_t DatePart::EpochNanosecondsOperator::Operation(date_t input) { - D_ASSERT(input.IsFinite()); - return Date::EpochNanoseconds(input); + int64_t result; + if (!TryOperation(input, result)) { + throw ConversionException("Could not convert DATE (%s) to nanoseconds", Date::ToString(input)); + } + return result; } template <> @@ -1235,9 +1353,18 @@ int64_t DatePart::EpochNanosecondsOperator::Operation(dtime_tz_t input) { return DatePart::EpochNanosecondsOperator::Operation(input.time()); } +template <> +bool DatePart::EpochMicrosecondsOperator::TryOperation(date_t input, int64_t &result) { + return TryMultiplyOperator::Operation(input.days, Interval::MICROS_PER_DAY, result); +} + template <> int64_t DatePart::EpochMicrosecondsOperator::Operation(date_t input) { - return Date::EpochMicroseconds(input); + int64_t result; + if (!TryOperation(input, result)) { + throw ConversionException("Could not convert DATE (%s) to microseconds", Date::ToString(input)); + } + return result; } template <> @@ -1313,6 +1440,11 @@ int64_t DatePart::MicrosecondsOperator::Operation(timestamp_t input) { return time.value % Interval::MICROS_PER_MINUTE; } +template <> +int64_t DatePart::MicrosecondsOperator::Operation(timestamp_ns_t input) { + return Operation(Truncate(input)); +} + template <> int64_t DatePart::MicrosecondsOperator::Operation(interval_t input) { // remove everything but the second & microsecond part @@ -1341,6 +1473,11 @@ int64_t DatePart::MillisecondsOperator::Operation(timestamp_t input) { return MicrosecondsOperator::Operation(input) / Interval::MICROS_PER_MSEC; } +template <> +int64_t DatePart::MillisecondsOperator::Operation(timestamp_ns_t input) { + return Operation(Truncate(input)); +} + template <> int64_t DatePart::MillisecondsOperator::Operation(interval_t input) { return MicrosecondsOperator::Operation(input) / Interval::MICROS_PER_MSEC; @@ -1367,6 +1504,11 @@ int64_t DatePart::SecondsOperator::Operation(timestamp_t input) { return MicrosecondsOperator::Operation(input) / Interval::MICROS_PER_SEC; } +template <> +int64_t DatePart::SecondsOperator::Operation(timestamp_ns_t input) { + return Operation(Truncate(input)); +} + template <> int64_t DatePart::SecondsOperator::Operation(interval_t input) { return MicrosecondsOperator::Operation(input) / Interval::MICROS_PER_SEC; @@ -1395,6 +1537,11 @@ int64_t DatePart::MinutesOperator::Operation(timestamp_t input) { return (time.value % Interval::MICROS_PER_HOUR) / Interval::MICROS_PER_MINUTE; } +template <> +int64_t DatePart::MinutesOperator::Operation(timestamp_ns_t input) { + return Operation(Truncate(input)); +} + template <> int64_t DatePart::MinutesOperator::Operation(interval_t input) { // remove the hour part, and truncate to minutes @@ -1423,6 +1570,11 @@ int64_t DatePart::HoursOperator::Operation(timestamp_t input) { return Timestamp::GetTime(input).value / Interval::MICROS_PER_HOUR; } +template <> +int64_t DatePart::HoursOperator::Operation(timestamp_ns_t input) { + return Operation(Truncate(input)); +} + template <> int64_t DatePart::HoursOperator::Operation(interval_t input) { return input.micros / Interval::MICROS_PER_HOUR; @@ -1453,6 +1605,11 @@ int64_t DatePart::DayParentOperator::Operation(timestamp_t input) { return Timestamp::GetDate(input).days; } +template <> +int64_t DatePart::DayParentOperator::Operation(timestamp_ns_t input) { + return Timestamp::GetDateNS(input).days; +} + // a time-of-day value always lies within a single day template <> int64_t DatePart::DayParentOperator::Operation(dtime_t input) { @@ -1495,6 +1652,11 @@ double DatePart::EpochOperator::Operation(timestamp_t input) { return double(Timestamp::GetEpochMicroSeconds(input)) / double(Interval::MICROS_PER_SEC); } +template <> +double DatePart::EpochOperator::Operation(timestamp_ns_t input) { + return EpochOperator::Operation(Truncate(input)); +} + template <> double DatePart::EpochOperator::Operation(interval_t input) { int64_t interval_years = input.months / Interval::MONTHS_PER_YEAR; @@ -1547,6 +1709,11 @@ int64_t DatePart::EraOperator::Operation(timestamp_t input) { return EraOperator::Operation(Timestamp::GetDate(input)); } +template <> +int64_t DatePart::EraOperator::Operation(timestamp_ns_t input) { + return EraOperator::Operation(Timestamp::GetDateNS(input)); +} + template <> int64_t DatePart::EraOperator::Operation(interval_t input) { throw NotImplementedException("interval units \"era\" not recognized"); @@ -1839,6 +2006,12 @@ void DatePart::StructOperator::Operation(bigint_vec &bigint_values, double_vec & } } +template <> +void DatePart::StructOperator::Operation(bigint_vec &bigint_values, double_vec &double_values, const timestamp_ns_t &ns, + const idx_t idx, const part_mask_t mask) { + Operation(bigint_values, double_values, Truncate(ns), idx, mask); +} + template <> void DatePart::StructOperator::Operation(bigint_vec &bigint_values, double_vec &double_values, const interval_t &input, const idx_t idx, const part_mask_t mask) { @@ -1999,9 +2172,11 @@ static scalar_function_t DatePartUnaryCallback(LogicalTypeId type) { case LogicalType::TIMESTAMP: case LogicalType::TIMESTAMP_S: case LogicalType::TIMESTAMP_MS: - case LogicalType::TIMESTAMP_NS: result = DatePart::UnaryFunction; break; + case LogicalType::TIMESTAMP_NS: + result = DatePart::UnaryFunction; + break; case LogicalType::DATE: result = DatePart::UnaryFunction; break; @@ -2213,10 +2388,11 @@ ScalarFunctionSet GetDatePartFunction() { } ScalarFunctionSet GetGenericTimePartFunction(const LogicalType &result_type, scalar_function_t date_func, - scalar_function_t ts_func, scalar_function_t interval_func, - scalar_function_t time_func, scalar_function_t time_ns_func, - scalar_function_t timetz_func, function_statistics_t date_stats, - function_statistics_t ts_stats, function_statistics_t time_stats, + scalar_function_t ts_func, scalar_function_t ts_ns_func, + scalar_function_t interval_func, scalar_function_t time_func, + scalar_function_t time_ns_func, scalar_function_t timetz_func, + function_statistics_t date_stats, function_statistics_t ts_stats, + function_statistics_t ts_ns_stats, function_statistics_t time_stats, function_statistics_t time_ns_stats, function_statistics_t timetz_stats, const Identifier ¶m_name = "ts") { ScalarFunctionSet operator_set; @@ -2226,6 +2402,9 @@ ScalarFunctionSet GetGenericTimePartFunction(const LogicalType &result_type, sca ScalarFunction ts_fun({}, result_type, std::move(ts_func), nullptr, ts_stats); ts_fun.GetSignature().AddParameter(param_name, LogicalType::TIMESTAMP); operator_set.AddFunction(ts_fun); + ScalarFunction ts_ns_fun({}, result_type, std::move(ts_ns_func), nullptr, ts_ns_stats); + ts_ns_fun.GetSignature().AddParameter(param_name, LogicalType::TIMESTAMP_NS); + operator_set.AddFunction(ts_ns_fun); ScalarFunction interval_fun({}, result_type, std::move(interval_func)); interval_fun.GetSignature().AddParameter(param_name, LogicalType::INTERVAL); operator_set.AddFunction(interval_fun); @@ -2246,9 +2425,10 @@ ScalarFunctionSet GetTimePartFunction(const LogicalType &result_type = LogicalTy const Identifier ¶m_name = "ts") { return GetGenericTimePartFunction( result_type, DatePart::UnaryFunction, DatePart::UnaryFunction, - ScalarFunction::UnaryFunction, ScalarFunction::UnaryFunction, - ScalarFunction::UnaryFunction, ScalarFunction::UnaryFunction, - OP::template PropagateStatistics, OP::template PropagateStatistics, + DatePart::UnaryFunction, ScalarFunction::UnaryFunction, + ScalarFunction::UnaryFunction, ScalarFunction::UnaryFunction, + ScalarFunction::UnaryFunction, OP::template PropagateStatistics, + OP::template PropagateStatistics, StatisticsPropagator::PropagateFiniteMonotoneBounds, OP::template PropagateStatistics, OP::template PropagateStatistics, OP::template PropagateStatistics, param_name); } @@ -2581,23 +2761,23 @@ ScalarFunctionSet EpochNsFun::GetFunctions() { using OP = DatePart::EpochNanosecondsOperator; auto operator_set = GetTimePartFunction(LogicalType::BIGINT, "temporal"); - // TIMESTAMP WITH TIME ZONE has the same representation as TIMESTAMP so no need to defer to ICU + // TIMESTAMP(NS) WITH TIME ZONE has the same representation as TIMESTAMP(NS) so no need to defer to ICU auto tstz_func = DatePart::UnaryFunction; auto tstz_stats = OP::template PropagateStatistics; ScalarFunction tstz_fun({}, LogicalType::BIGINT, tstz_func, nullptr, tstz_stats); tstz_fun.GetSignature().AddParameter("temporal", LogicalType::TIMESTAMP_TZ); operator_set.AddFunction(tstz_fun); + auto tsns_func = DatePart::UnaryFunction; auto tsns_stats = StatisticsPropagator::PropagateFiniteMonotoneBounds; - ScalarFunction tsns_fun({}, LogicalType::BIGINT, tsns_func, nullptr, tsns_stats); - tsns_fun.GetSignature().AddParameter("temporal", LogicalType::TIMESTAMP_NS); - operator_set.AddFunction(tsns_fun); ScalarFunction tstz_ns_fun({}, LogicalType::BIGINT, tsns_func, nullptr, tsns_stats); tstz_ns_fun.GetSignature().AddParameter("temporal", LogicalType::TIMESTAMP_TZ_NS); operator_set.AddFunction(tstz_ns_fun); + operator_set.SetUnaryArgProperties(ArgProperties().NonDecreasing()); // these overflow at the representable extremes, so the failure must be reportable operator_set.SetFallible(); + return operator_set; } @@ -2658,9 +2838,6 @@ ScalarFunctionSet NanosecondsFun::GetFunctions() { auto ns_func = DatePart::UnaryFunction; auto ns_stats = OP::template PropagateStatistics; - ScalarFunction ns_fun({}, result_type, ns_func, nullptr, ns_stats); - ns_fun.GetSignature().AddParameter("tsns", LogicalType::TIMESTAMP_NS); - operator_set.AddFunction(ns_fun); ScalarFunction tz_ns_fun({}, result_type, ns_func, nullptr, ns_stats); tz_ns_fun.GetSignature().AddParameter("tsns", LogicalType::TIMESTAMP_TZ_NS); operator_set.AddFunction(tz_ns_fun); @@ -2792,6 +2969,9 @@ ScalarFunctionSet DatePartFun::GetFunctions() { ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::DATE)); date_part.AddFunction(NamePartTsArguments( ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::TIMESTAMP)); + date_part.AddFunction( + NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), + LogicalType::TIMESTAMP_NS)); date_part.AddFunction(NamePartTsArguments( ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::TIME)); date_part.AddFunction(NamePartTsArguments( @@ -2804,6 +2984,7 @@ ScalarFunctionSet DatePartFun::GetFunctions() { // struct variants date_part.AddFunction(StructDatePart::GetFunction(LogicalType::DATE)); date_part.AddFunction(StructDatePart::GetFunction(LogicalType::TIMESTAMP)); + date_part.AddFunction(StructDatePart::GetFunction(LogicalType::TIMESTAMP_NS)); date_part.AddFunction(StructDatePart::GetFunction(LogicalType::TIME)); date_part.AddFunction(StructDatePart::GetFunction(LogicalType::TIME_NS)); date_part.AddFunction(StructDatePart::GetFunction(LogicalType::INTERVAL)); diff --git a/src/duckdb/extension/core_functions/scalar/generic/can_implicitly_cast.cpp b/src/duckdb/extension/core_functions/scalar/generic/can_implicitly_cast.cpp index 63922be56..d31be6e70 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/can_implicitly_cast.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/can_implicitly_cast.cpp @@ -13,19 +13,15 @@ bool CanCastImplicitly(ClientContext &context, const LogicalType &source, const } void CanCastImplicitlyFunction(DataChunk &args, ExpressionState &state, Vector &result) { - auto &context = state.GetContext(); - bool can_cast_implicitly = CanCastImplicitly(context, args.data[0].GetType(), args.data[1].GetType()); - auto v = Value::BOOLEAN(can_cast_implicitly); - result.Reference(v, count_t(args.size())); + throw InternalException("can_cast_implicitly cannot be executed directly"); } unique_ptr BindCanCastImplicitlyExpression(FunctionBindExpressionInput &input) { auto &source_type = input.children[0]->GetReturnType(); auto &target_type = input.children[1]->GetReturnType(); - if (source_type.id() == LogicalTypeId::UNKNOWN || source_type.id() == LogicalTypeId::SQLNULL || - target_type.id() == LogicalTypeId::UNKNOWN || target_type.id() == LogicalTypeId::SQLNULL) { + if (source_type.id() == LogicalTypeId::UNKNOWN || target_type.id() == LogicalTypeId::UNKNOWN) { // parameter - unknown return type - return nullptr; + throw ParameterNotResolvedException(); } // emit a constant expression return make_uniq( diff --git a/src/duckdb/extension/core_functions/scalar/generic/hash.cpp b/src/duckdb/extension/core_functions/scalar/generic/hash.cpp index 31021ba40..d5280d4ec 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/hash.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/hash.cpp @@ -11,6 +11,8 @@ ScalarFunction HashFun::GetFunction() { hash_fun.GetSignature().AddParameter("value", LogicalType::ANY); hash_fun.GetSignature().AddArgs("args", LogicalType::ANY); hash_fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + // hash the arguments after their combinable collations + hash_fun.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS); return hash_fun; } diff --git a/src/duckdb/extension/core_functions/scalar/list/flatten.cpp b/src/duckdb/extension/core_functions/scalar/list/flatten.cpp index e2fcac5c7..4ad99c75d 100644 --- a/src/duckdb/extension/core_functions/scalar/list/flatten.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/flatten.cpp @@ -135,6 +135,23 @@ unique_ptr ListFlattenStats(ClientContext &context, FunctionStat auto &list_child_stats = ListStats::GetChildStats(child_stats[0]); auto child_copy = list_child_stats.Copy(); child_copy.CopyValidity(child_stats[0]); + // the result length is the sum of the inner lengths, NULL inner lists add no elements + auto outer_min = ListStats::MinListLength(child_stats[0]); + auto outer_max = ListStats::MaxListLength(child_stats[0]); + auto inner_min = ListStats::MinListLength(list_child_stats); + auto inner_max = ListStats::MaxListLength(list_child_stats); + optional_idx min_length(0); + if (outer_min.IsValid() && inner_min.IsValid() && !list_child_stats.CanHaveNull() && + (inner_min.GetIndex() == 0 || outer_min.GetIndex() <= NumericLimits::Maximum() / inner_min.GetIndex())) { + min_length = outer_min.GetIndex() * inner_min.GetIndex(); + } + optional_idx max_length; + if (outer_max.IsValid() && inner_max.IsValid() && + (inner_max.GetIndex() == 0 || outer_max.GetIndex() <= NumericLimits::Maximum() / inner_max.GetIndex())) { + max_length = outer_max.GetIndex() * inner_max.GetIndex(); + } + ListStats::ResetTotalListLength(child_copy); + ListStats::SetLengthBounds(child_copy, min_length, max_length); return child_copy.ToUnique(); } diff --git a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp index bd2fcd435..6313dac67 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp @@ -80,6 +80,11 @@ ListSortBindData::ListSortBindData(OrderType order_type_p, OrderByNullType null_ vector orders; orders.emplace_back(OrderType::ASCENDING, OrderByNullType::ORDER_DEFAULT, std::move(idx_col_expr)); orders.emplace_back(order_type, null_order, std::move(sort_key_p)); + if (is_grade_up) { + // break ties on the original position, so equal elements are graded in a deterministic order + auto position_expr = make_uniq_base(LogicalType::UINTEGER, 2U); + orders.emplace_back(OrderType::ASCENDING, OrderByNullType::ORDER_DEFAULT, std::move(position_expr)); + } sort = shared_ptr(new Sort(context, orders, {LogicalType::USMALLINT, child_type, LogicalType::UINTEGER}, {2})); } @@ -281,12 +286,11 @@ static void ListSortFunction(DataChunk &args, ExpressionState &state, Vector &re // construct the selection vector with the new order from the result vectors auto row_count = result_chunk.size(); - Vector result_vector(Vector::Ref(result_chunk.data[0])); - - auto result_data = FlatVector::GetData(result_vector); + auto result_values = result_chunk.data[0].Values(); for (idx_t i = 0; i < row_count; i++) { - sel_sorted.set_index(sel_sorted_idx, result_data[i]); - D_ASSERT(result_data[i] < lists_size); + auto sorted_idx = result_values[i].GetValue(); + sel_sorted.set_index(sel_sorted_idx, sorted_idx); + D_ASSERT(sorted_idx < lists_size); sel_sorted_idx++; } } @@ -314,20 +318,11 @@ static void ListSortFunction(DataChunk &args, ExpressionState &state, Vector &re static unique_ptr ListSortBind(ClientContext &context, BoundScalarFunction &bound_function, vector> &arguments, OrderType &order, OrderByNullType &null_order) { - LogicalType child_type; - if (arguments[0]->GetReturnType() == LogicalTypeId::UNKNOWN) { - bound_function.GetArguments()[0] = LogicalTypeId::UNKNOWN; - bound_function.SetReturnType(LogicalType::SQLNULL); - child_type = bound_function.GetReturnType(); - return make_uniq(order, null_order, false, bound_function.GetReturnType(), child_type, - context); - } - arguments[0] = BoundCastExpression::AddArrayCastToList(context, std::move(arguments[0])); if (arguments[0]->GetReturnType().id() != LogicalTypeId::LIST) { throw BinderException("list_sort can only operate on LISTs"); } - child_type = ListType::GetChildType(arguments[0]->GetReturnType()); + auto child_type = ListType::GetChildType(arguments[0]->GetReturnType()); bound_function.GetArguments()[0] = arguments[0]->GetReturnType(); bound_function.SetReturnType(arguments[0]->GetReturnType()); @@ -361,13 +356,6 @@ static unique_ptr ListGradeUpBind(BindScalarFunctionInput &input) order = config.ResolveOrder(context, order); null_order = config.ResolveNullOrder(context, order, null_order); - if (arguments[0]->GetReturnType().id() == LogicalTypeId::UNKNOWN) { - bound_function.GetArguments()[0] = LogicalTypeId::UNKNOWN; - bound_function.SetReturnType(LogicalType::SQLNULL); - return make_uniq(order, null_order, true, bound_function.GetReturnType(), - bound_function.GetReturnType(), context); - } - arguments[0] = BoundCastExpression::AddArrayCastToList(context, std::move(arguments[0])); if (arguments[0]->GetReturnType().id() != LogicalTypeId::LIST) { throw BinderException("list_grade_up can only operate on LISTs"); diff --git a/src/duckdb/extension/core_functions/scalar/list/list_transform.cpp b/src/duckdb/extension/core_functions/scalar/list/list_transform.cpp index f70eddc26..e7eaa2eee 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_transform.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_transform.cpp @@ -3,6 +3,9 @@ #include "duckdb/function/lambda_functions.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_lambda_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" namespace duckdb { @@ -30,6 +33,65 @@ static LogicalType ListTransformBindLambda(ClientContext &context, const vector< return LambdaFunctions::BindBinaryChildren(function_child_types, parameter_idx); } +//! Whether the expression is the element, or a monotone function of it whose bounds come only from those of the element +static bool IsMonotoneInElement(const Expression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_REF) { + return true; + } + if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { + return false; + } + auto &func = expr.Cast(); + auto &children = func.GetChildren(); + if (children.size() != 1 || func.Function().HasStatisticsCallback()) { + return false; + } + auto monotonicity = func.Function().GetArgProperties(0).monotonicity; + if (!IsMonotonicIncreasing(monotonicity) && !IsMonotonicDecreasing(monotonicity)) { + return false; + } + return IsMonotoneInElement(*children[0]); +} + +//! The elements of the result have the statistics of the lambda applied to the elements of the list +static unique_ptr ListTransformStats(ClientContext &context, FunctionStatisticsInput &input) { + // only a lambda that reads the element alone, without its index or other columns + if (!input.bind_data || input.child_stats.size() != 2) { + return nullptr; + } + auto &bind_data = input.bind_data->Cast(); + auto &list_stats = input.child_stats[0]; + if (!bind_data.lambda_expr || bind_data.has_index || list_stats.GetStatsType() != StatisticsType::LIST_STATS) { + return nullptr; + } + // statistics can let the optimizer skip the call, which must not hide errors or side effects of the list or lambda + auto &list_expr = *input.expr.GetChildren()[0]; + // only the list of a scan column in a table filter: the statistics of any other list can stem from a producer + // with side effects that the optimizer removes once the statistics fold its use + if (list_expr.GetExpressionClass() != ExpressionClass::BOUND_REF) { + return nullptr; + } + if (list_expr.IsVolatile() || list_expr.CanThrow() || bind_data.lambda_expr->IsVolatile() || + bind_data.lambda_expr->CanThrow()) { + return nullptr; + } + // the statistics of the list argument may not show that its producer has side effects or can throw, so derive + // nothing that does not follow from the statistics of the elements + if (!IsMonotoneInElement(*bind_data.lambda_expr)) { + return nullptr; + } + auto &element_stats = ListStats::GetChildStats(list_stats); + auto lambda_stats = ExpressionFilter::TryGetExpressionStatistics( + context, *bind_data.lambda_expr, array_ptr(&element_stats, 1)); + if (!lambda_stats) { + return nullptr; + } + auto result = ListStats::CreateUnknown(input.expr.GetReturnType()); + result.CopyValidity(list_stats); + ListStats::SetChildStats(result, std::move(lambda_stats)); + return result.ToUnique(); +} + ScalarFunction ListTransformFun::GetFunction() { ScalarFunction fun({}, LogicalType::LIST(LogicalType::ANY), LambdaFunctions::ListTransformFunction, ListTransformBind, nullptr, nullptr); @@ -41,6 +103,7 @@ ScalarFunction ListTransformFun::GetFunction() { fun.SetSerializeCallback(ListLambdaBindData::Serialize); fun.SetDeserializeCallback(ListLambdaBindData::Deserialize); fun.SetBindLambdaCallback(ListTransformBindLambda); + fun.SetStatisticsCallback(ListTransformStats); // the lambda expression that is executed for every element can throw fun.SetFallible(); 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 53256134b..4fb2e9a7c 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_value.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_value.cpp @@ -279,6 +279,7 @@ unique_ptr ListValueStats(ClientContext &context, FunctionStatis auto &child_stats = input.child_stats; auto &expr = input.expr; auto list_stats = ListStats::CreateEmpty(expr.GetReturnType()); + ListStats::SetLengthBounds(list_stats, child_stats.size(), child_stats.size()); auto &list_child_stats = ListStats::GetChildStats(list_stats); for (idx_t i = 0; i < child_stats.size(); i++) { list_child_stats.Merge(child_stats[i]); diff --git a/src/duckdb/extension/core_functions/scalar/map/map_keys_values.cpp b/src/duckdb/extension/core_functions/scalar/map/map_keys_values.cpp index e7f71d391..c7489f8c2 100644 --- a/src/duckdb/extension/core_functions/scalar/map/map_keys_values.cpp +++ b/src/duckdb/extension/core_functions/scalar/map/map_keys_values.cpp @@ -52,6 +52,7 @@ static unique_ptr MapValuesStats(ClientContext &, FunctionStatis } auto result = ListStats::CreateEmpty(input.expr.GetReturnType()); result.CopyValidity(input.child_stats[0]); + ListStats::SetLengthData(result, ListStats::GetLengthData(input.child_stats[0])); ListStats::GetChildStats(result).Copy(StructStats::GetChildStats(entry_stats, 1)); return result.ToUnique(); } diff --git a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp index 150967fcd..e8de8c22d 100644 --- a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp +++ b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp @@ -546,7 +546,7 @@ static void GenericRoundFunctionDecimalResolveTypes(ResolveScalarFunctionTypesIn namespace { struct CeilDecimalOperator { template - static void Operation(DataChunk &input, uint8_t scale, Vector &result) { + static void Operation(DataChunk &input, uint32_t scale, Vector &result) { T power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[scale]); UnaryExecutor::Execute(input.data[0], result, [&](T input) { if (input <= 0) { @@ -604,7 +604,7 @@ struct FloorOperator { struct FloorDecimalOperator { template - static void Operation(DataChunk &input, uint8_t scale, Vector &result) { + static void Operation(DataChunk &input, uint32_t scale, Vector &result) { T power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[scale]); UnaryExecutor::Execute(input.data[0], result, [&](T input) { if (input < 0) { @@ -655,12 +655,12 @@ ScalarFunctionSet FloorFun::GetFunctions() { namespace { struct RoundPrecisionFunctionData : public FunctionData { - RoundPrecisionFunctionData(int32_t target_scale, uint8_t source_width, bool check_overflow) + RoundPrecisionFunctionData(int32_t target_scale, uint32_t source_width, bool check_overflow) : target_scale(target_scale), source_width(source_width), check_overflow(check_overflow) { } int32_t target_scale; - uint8_t source_width; + uint32_t source_width; bool check_overflow; unique_ptr Copy() const override { @@ -688,7 +688,7 @@ unique_ptr ResolveDecimalRoundPrecision(BoundScalarFunction &bound // but ONLY if the round value is positive // if it is negative the scale becomes zero // i.e. ROUND(DECIMAL(18,3), -1) -> DECIMAL(18,0) - uint8_t target_scale; + uint32_t target_scale; auto width = DecimalType::GetWidth(decimal_type); auto scale = DecimalType::GetScale(decimal_type); auto result_width = width; @@ -727,7 +727,7 @@ unique_ptr ResolveDecimalRoundPrecision(BoundScalarFunction &bound bound_function.SetFunctionCallback(ScalarFunction::NopFunction); target_scale = scale; } else { - target_scale = NumericCast(round_value); + target_scale = NumericCast(round_value); switch (decimal_type.InternalType()) { case PhysicalType::INT16: bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); @@ -796,7 +796,7 @@ struct TruncOperator { struct TruncDecimalOperator { template - static void Operation(DataChunk &input, uint8_t scale, Vector &result) { + static void Operation(DataChunk &input, uint32_t scale, Vector &result) { T power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[scale]); UnaryExecutor::Execute(input.data[0], result, [&](T input) { // Always floor @@ -813,9 +813,8 @@ struct TruncDecimalNegativePrecisionOperator { auto source_scale = DecimalType::GetScale(func_expr.GetChildren()[0]->GetReturnType()); auto width = DecimalType::GetWidth(func_expr.GetChildren()[0]->GetReturnType()); if (info.target_scale <= -int32_t(width - source_scale)) { - // scale too big for width - result.SetVectorType(VectorType::CONSTANT_VECTOR); - result.SetValue(0, Value::INTEGER(0)); + // scale too big for width: every value truncates to zero, NULL stays NULL + UnaryExecutor::Execute(input.data[0], result, [](T) { return T(0); }); return; } T divide_power_of_ten = @@ -978,7 +977,7 @@ struct RoundHalfAwayFromZero { static constexpr const char *Name = "ROUND"; static double Nearest(double value) { - return std::round(value); + return RoundToNearestAwayFromZero(value); } template static bool RoundsAway(T) { @@ -998,6 +997,18 @@ struct RoundHalfToEven { } }; +//! The error of the rounded product, computed with Dekker's algorithm because fma is not exact on every platform +static double ProductError(double a, double b, double product) { + constexpr double SPLITTER = 134217729.0; // 2^27 + 1 + double a_scaled = SPLITTER * a; + double a_high = a_scaled - (a_scaled - a); + double a_low = a - a_high; + double b_scaled = SPLITTER * b; + double b_high = b_scaled - (b_scaled - b); + double b_low = b - b_high; + return ((a_high * b_high - product) + a_high * b_low + a_low * b_high) + a_low * b_low; +} + template struct RoundOperatorPrecision { template @@ -1016,7 +1027,20 @@ struct RoundOperatorPrecision { } } else { double modifier = std::pow(10, TA(precision)); - rounded_value = ROUND_POLICY::Nearest(input * modifier) / modifier; + double scaled = input * modifier; + double nearest; + // the product can round onto a midpoint that the input itself is not on, as 2.675 * 100 becomes 267.5 + // while the stored 2.675 is below it, so the exact product decides (10^22 is the largest exact modifier) + double error = 0; + if (precision > 0 && precision <= 22 && std::fabs(scaled - std::trunc(scaled)) == 0.5) { + error = ProductError(double(input), modifier, scaled); + } + if (error != 0) { + nearest = error < 0 ? std::floor(scaled) : std::ceil(scaled); + } else { + nearest = ROUND_POLICY::Nearest(scaled); + } + rounded_value = nearest / modifier; if (std::isinf(rounded_value) || std::isnan(rounded_value)) { return input; } @@ -1028,7 +1052,7 @@ struct RoundOperatorPrecision { struct RoundOperator { template static inline TR Operation(TA input) { - double rounded_value = round(input); + double rounded_value = RoundToNearestAwayFromZero(static_cast(input)); if (std::isinf(rounded_value) || std::isnan(rounded_value)) { return input; } @@ -1038,7 +1062,7 @@ struct RoundOperator { struct RoundDecimalOperator { template - static void Operation(DataChunk &input, uint8_t scale, Vector &result) { + static void Operation(DataChunk &input, uint32_t scale, Vector &result) { T power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[scale]); T addition = power_of_ten / 2; // regular round rounds towards the nearest number @@ -1110,9 +1134,8 @@ struct DecimalRoundNegativePrecisionOperator { auto &info = func_expr.BindInfo()->Cast(); auto source_scale = DecimalType::GetScale(func_expr.GetChildren()[0]->GetReturnType()); if (info.target_scale < -int32_t(info.source_width - source_scale)) { - // scale too big for width - result.SetVectorType(VectorType::CONSTANT_VECTOR); - result.SetValue(0, Value::INTEGER(0)); + // scale too big for width: every value rounds to zero, NULL stays NULL + UnaryExecutor::Execute(input.data[0], result, [](T) { return T(0); }); return; } T divide_power_of_ten = diff --git a/src/duckdb/extension/core_functions/scalar/random/random.cpp b/src/duckdb/extension/core_functions/scalar/random/random.cpp index cb66ffa60..4c2f1e52f 100644 --- a/src/duckdb/extension/core_functions/scalar/random/random.cpp +++ b/src/duckdb/extension/core_functions/scalar/random/random.cpp @@ -79,7 +79,7 @@ unique_ptr RandomInitLocalState(ExpressionState &state, cons FunctionData *bind_data) { auto &random_engine = RandomEngine::Get(state.GetContext()); lock_guard guard(random_engine.lock); - return make_uniq(random_engine.NextRandomInteger64()); + return make_uniq(random_engine.NextSeed()); } void GenerateUUIDv4Function(DataChunk &args, ExpressionState &state, Vector &result) { diff --git a/src/duckdb/extension/core_functions/scalar/random/setseed.cpp b/src/duckdb/extension/core_functions/scalar/random/setseed.cpp index ef2012e8d..b41dab90f 100644 --- a/src/duckdb/extension/core_functions/scalar/random/setseed.cpp +++ b/src/duckdb/extension/core_functions/scalar/random/setseed.cpp @@ -42,6 +42,7 @@ void SetSeedFunction(DataChunk &args, ExpressionState &state, Vector &result) { throw InvalidInputException("SETSEED accepts seed values between -1.0 and 1.0, inclusive"); } auto norm_seed = LossyNumericCast((input_seeds[i] + 1.0) * half_max); + lock_guard guard(random_engine.lock); random_engine.SetSeed(norm_seed); } 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 ff12e6a00..3b3c84693 100644 --- a/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp @@ -10,7 +10,7 @@ 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(ClientContext &context, const T *source_str, idx_t source_len, +static idx_t DamerauLevenshteinDistance(optional_ptr 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; @@ -47,7 +47,9 @@ static idx_t DamerauLevenshteinDistance(ClientContext &context, const T *source_ } // loop through string indices - these are offset by 2 from distance indices for (idx_t source_idx = 0; source_idx < source_len; source_idx++) { - context.InterruptCheck(); + if (context) { + 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; @@ -84,7 +86,8 @@ static idx_t DamerauLevenshteinDistance(ClientContext &context, const T *source_ } //! The distance between the characters of the strings - not their bytes -static idx_t DamerauLevenshteinDistance(ClientContext &context, const string_t &source, const string_t &target) { +static idx_t DamerauLevenshteinDistance(optional_ptr 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()); @@ -95,7 +98,8 @@ static idx_t DamerauLevenshteinDistance(ClientContext &context, const string_t & target_chars.size()); } -static int64_t DamerauLevenshteinScalarFunction(ClientContext &context, const string_t source, const string_t target) { +static int64_t DamerauLevenshteinScalarFunction(optional_ptr context, const string_t source, + const string_t target) { return (int64_t)DamerauLevenshteinDistance(context, source, target); } @@ -103,7 +107,8 @@ static void DamerauLevenshteinFunction(DataChunk &args, ExpressionState &state, const auto &source_vec = args.data[0]; const auto &target_vec = args.data[1]; - auto &context = state.GetContext(); + // the client context only serves interrupt checks, and index keys are computed without one + optional_ptr context = state.HasContext() ? &state.GetContext() : nullptr; 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/hex.cpp b/src/duckdb/extension/core_functions/scalar/string/hex.cpp index d5c51cab3..cfad8ba69 100644 --- a/src/duckdb/extension/core_functions/scalar/string/hex.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/hex.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/bignum.hpp" #include "duckdb/common/bit_utils.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -64,6 +65,43 @@ static void WriteHugeIntBinBytes(T x, char *&output, idx_t buffer_size) { } } +//! A BIGNUM has no fixed width, so a negative value prints as a sign and its magnitude rather than two's complement. +template +static string_t WriteBignumDigits(const bignum_t &input, StringHeap &heap) { + constexpr uint8_t DIGITS_PER_BYTE = 8 / BITS_PER_DIGIT; + constexpr uint8_t DIGIT_MASK = (1 << BITS_PER_DIGIT) - 1; + + const BignumIntermediate value(input); + const idx_t start = value.GetStartDataPos(); + if (start == value.size) { + auto target = heap.EmptyString(1); + *target.GetDataWriteable() = '0'; + target.Finalize(); + return target; + } + + idx_t leading_bits = 32 - CountZeros::Leading(value.GetAbsoluteByte(NumericCast(start))); + idx_t leading_digits = (leading_bits + BITS_PER_DIGIT - 1) / BITS_PER_DIGIT; + idx_t result_size = (value.is_negative ? 1 : 0) + leading_digits + (value.size - start - 1) * DIGITS_PER_BYTE; + + auto target = heap.EmptyString(result_size); + auto output = target.GetDataWriteable(); + if (value.is_negative) { + *output++ = '-'; + } + for (idx_t i = start; i < value.size; i++) { + auto byte = value.GetAbsoluteByte(NumericCast(i)); + idx_t digits = i == start ? leading_digits : DIGITS_PER_BYTE; + for (idx_t d = digits; d >= 1; d--) { + auto digit = static_cast((byte >> ((d - 1) * BITS_PER_DIGIT)) & DIGIT_MASK); + *output++ = Blob::HEX_TABLE[digit]; + } + } + + target.Finalize(); + return target; +} + struct HexStrOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { @@ -167,6 +205,13 @@ struct HexUhugeIntOperator { } }; +struct HexBignumOperator { + template + static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { + return WriteBignumDigits<4>(input, heap); + } +}; + template static void ToHexFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 1); @@ -276,6 +321,13 @@ struct BinaryUhugeIntOperator { } }; +struct BinaryBignumOperator { + template + static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { + return WriteBignumDigits<1>(input, heap); + } +}; + struct FromHexOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { @@ -389,7 +441,7 @@ ScalarFunctionSet HexFun::GetFunctions() { AddHexParam(string_fun, LogicalType::VARCHAR, "string"); to_hex.AddFunction(string_fun); - ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToHexFunction); + ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToHexFunction); AddHexParam(bignum_fun, LogicalType::BIGNUM, "value"); to_hex.AddFunction(bignum_fun); @@ -430,7 +482,7 @@ ScalarFunctionSet BinFun::GetFunctions() { AddHexParam(string_fun, LogicalType::VARCHAR, "string"); to_binary.AddFunction(string_fun); - ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToBinaryFunction); + ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToBinaryFunction); AddHexParam(bignum_fun, LogicalType::BIGNUM, "value"); to_binary.AddFunction(bignum_fun); diff --git a/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp b/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp index 546baad19..dca9e2575 100644 --- a/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp @@ -15,7 +15,7 @@ namespace duckdb { // (too muach memory usage) template -static idx_t LevenshteinDistance(ClientContext &context, const T *txt_str, idx_t txt_len, const T *tgt_str, +static idx_t LevenshteinDistance(optional_ptr 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) { @@ -39,7 +39,9 @@ static idx_t LevenshteinDistance(ClientContext &context, const T *txt_str, idx_t } for (idx_t pos_txt = 0; pos_txt < txt_len; pos_txt++) { - context.InterruptCheck(); + if (context) { + context->InterruptCheck(); + } // calculate distances1 (current raw distances) from the previous row distances1[0] = pos_txt + 1; @@ -64,7 +66,7 @@ static idx_t LevenshteinDistance(ClientContext &context, const T *txt_str, idx_t } //! The distance between the characters of the strings - not their bytes -static idx_t LevenshteinDistance(ClientContext &context, const string_t &txt, const string_t &tgt) { +static idx_t LevenshteinDistance(optional_ptr 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()); } @@ -73,7 +75,7 @@ static idx_t LevenshteinDistance(ClientContext &context, const string_t &txt, co return LevenshteinDistance(context, txt_chars.data(), txt_chars.size(), tgt_chars.data(), tgt_chars.size()); } -static int64_t LevenshteinScalarFunction(ClientContext &context, const string_t str, string_t tgt) { +static int64_t LevenshteinScalarFunction(optional_ptr context, const string_t str, string_t tgt) { return (int64_t)LevenshteinDistance(context, str, tgt); } @@ -81,7 +83,8 @@ static void LevenshteinFunction(DataChunk &args, ExpressionState &state, Vector const auto &str_vec = args.data[0]; const auto &tgt_vec = args.data[1]; - auto &context = state.GetContext(); + // the client context only serves interrupt checks, and index keys are computed without one + optional_ptr context = state.HasContext() ? &state.GetContext() : nullptr; BinaryExecutor::Execute(str_vec, tgt_vec, result, [&](string_t str, string_t tgt) { return LevenshteinScalarFunction(context, str, tgt); }); diff --git a/src/duckdb/extension/icu/collation/collation_normalizer.cpp b/src/duckdb/extension/icu/collation/collation_normalizer.cpp index e354a96cd..628e89dc7 100644 --- a/src/duckdb/extension/icu/collation/collation_normalizer.cpp +++ b/src/duckdb/extension/icu/collation/collation_normalizer.cpp @@ -1,12 +1,11 @@ #include "collation_normalizer.hpp" #include "collation_data.hpp" +#include "duckdb/common/exception.hpp" namespace duckdb { namespace collation { -static constexpr uint32_t REPLACEMENT_CHARACTER = 0xFFFD; - //! No character below these limits has a combining class or a canonical decomposition, //! which the tables are checked against static constexpr uint32_t FIRST_COMBINING_MARK = 0x300; @@ -48,14 +47,10 @@ uint32_t Normalizer::Decode(const char *data, idx_t size, vector &resu codepoint = lead & 0x07; length = 4; } else { - result.push_back(REPLACEMENT_CHARACTER); - pos++; - continue; + throw DataCorruptionException("Invalid UTF-8 in collation input"); } if (pos + length > size) { - result.push_back(REPLACEMENT_CHARACTER); - pos++; - continue; + throw DataCorruptionException("Invalid UTF-8 in collation input"); } bool valid = true; for (idx_t i = 1; i < length; i++) { @@ -67,9 +62,7 @@ uint32_t Normalizer::Decode(const char *data, idx_t size, vector &resu codepoint = (codepoint << 6) | (trail & 0x3F); } if (!valid || codepoint > 0x10FFFF) { - result.push_back(REPLACEMENT_CHARACTER); - pos++; - continue; + throw DataCorruptionException("Invalid UTF-8 in collation input"); } if (codepoint >= 0x80) { // ASCII characters never carry a combining class and never decompose diff --git a/src/duckdb/extension/icu/datetime/tz_loader.cpp b/src/duckdb/extension/icu/datetime/tz_loader.cpp index 1adb4fce5..3baeff2f1 100644 --- a/src/duckdb/extension/icu/datetime/tz_loader.cpp +++ b/src/duckdb/extension/icu/datetime/tz_loader.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector.hpp" #include "zstd.h" +#include "zstd_errors.h" namespace duckdb { namespace datetime { @@ -101,7 +102,13 @@ static unique_ptr Decompress() { block->bytes = unique_ptr(new uint8_t[TZ_UNCOMPRESSED_SIZE]); const auto size = duckdb_zstd::ZSTD_decompress(block->bytes.get(), TZ_UNCOMPRESSED_SIZE, TZ_COMPRESSED, TZ_COMPRESSED_SIZE); - if (duckdb_zstd::ZSTD_isError(size) || size != TZ_UNCOMPRESSED_SIZE) { + if (duckdb_zstd::ZSTD_isError(size)) { + if (duckdb_zstd::ZSTD_getErrorCode(size) == duckdb_zstd::ZSTD_error_memory_allocation) { + throw OutOfMemoryException("Could not allocate memory to decompress the time zone data"); + } + throw InternalException("Failed to decompress the time zone data"); + } + if (size != TZ_UNCOMPRESSED_SIZE) { throw InternalException("Failed to decompress the time zone data"); } diff --git a/src/duckdb/extension/icu/icu-dateadd.cpp b/src/duckdb/extension/icu/icu-dateadd.cpp index 0085d1c20..9a697edab 100644 --- a/src/duckdb/extension/icu/icu-dateadd.cpp +++ b/src/duckdb/extension/icu/icu-dateadd.cpp @@ -125,12 +125,39 @@ timestamp_tz_t ICUCalendarAdd::Operation(interval_t interval, timestamp_tz_t tim return Operation(timestamp, interval, calendar); } +template <> +timestamp_tz_ns_t ICUCalendarAdd::Operation(timestamp_tz_ns_t ns, interval_t interval, TZCalendar &calendar) { + if (!ns.IsFinite()) { + return ns; + } + timestamp_tz_t us; + int64_t nanos; + const auto precision = ns.PRECISION / us.PRECISION; + Timestamp::SplitTime(ns.value, precision, us.value, nanos); + us = Operation(us, interval, calendar); + if (!Timestamp::TryCombineUnits(us.value, nanos, precision, ns.value)) { + throw OutOfRangeException("Cannot add interval to timestamp_tz_ns"); + } + return ns; +} + +template <> +timestamp_tz_ns_t ICUCalendarAdd::Operation(interval_t interval, timestamp_tz_ns_t timestamp, TZCalendar &calendar) { + return Operation(timestamp, interval, calendar); +} + template <> timestamp_tz_t ICUCalendarSub::Operation(timestamp_tz_t timestamp, interval_t interval, TZCalendar &calendar) { const auto negated = Interval::Invert(interval); return ICUCalendarAdd::template Operation(timestamp, negated, calendar); } +template <> +timestamp_tz_ns_t ICUCalendarSub::Operation(timestamp_tz_ns_t ns, interval_t interval, TZCalendar &calendar) { + const auto negated = Interval::Invert(interval); + return ICUCalendarAdd::template Operation(ns, negated, calendar); +} + template <> interval_t ICUCalendarSub::Operation(timestamp_tz_t end_date, timestamp_tz_t start_date, TZCalendar &calendar_p) { if (!end_date.IsFinite() || !start_date.IsFinite()) { @@ -249,24 +276,33 @@ struct ICUDateAdd : public ICUDateFunc { ICUBindIntervalMonths); } - template - static ScalarFunction GetDateAddFunction(const LogicalTypeId &left_type, const LogicalTypeId &right_type) { - return GetBinaryDateFunction(left_type, right_type, LogicalType::TIMESTAMP_TZ); + template + static ScalarFunction GetDateAddFunction(const LogicalTypeId &left_type, const LogicalTypeId &right_type, + const LogicalTypeId &result_type) { + return GetBinaryDateFunction(left_type, right_type, result_type); } - static void AddDateAddOperators(const Identifier &name, ExtensionLoader &loader) { + template + static void AddDateAddFunctions(ScalarFunctionSet &set, const LogicalTypeId &type) { // temporal + interval - ScalarFunctionSet set {name}; - auto tstz_interval_fun = GetDateAddFunction( - LogicalType::TIMESTAMP_TZ, LogicalType::INTERVAL); + auto tstz_interval_fun = + GetDateAddFunction(type, LogicalType::INTERVAL, type); tstz_interval_fun.GetSignature().GetParameter(0).SetName("left"); tstz_interval_fun.GetSignature().GetParameter(1).SetName("right"); set.AddFunction(tstz_interval_fun); - auto interval_tstz_fun = GetDateAddFunction( - LogicalType::INTERVAL, LogicalType::TIMESTAMP_TZ); + + // interval + temporal + auto interval_tstz_fun = + GetDateAddFunction(LogicalType::INTERVAL, type, type); interval_tstz_fun.GetSignature().GetParameter(0).SetName("left"); interval_tstz_fun.GetSignature().GetParameter(1).SetName("right"); set.AddFunction(interval_tstz_fun); + } + + static void AddDateAddOperators(const Identifier &name, ExtensionLoader &loader) { + ScalarFunctionSet set {name}; + AddDateAddFunctions(set, LogicalType::TIMESTAMP_TZ); + AddDateAddFunctions(set, LogicalType::TIMESTAMP_TZ_NS); // throws for dates that overflow the timestamp range set.SetFallible(); set.SetStability(FunctionStability::CONSISTENT_WITHIN_QUERY); @@ -283,14 +319,20 @@ struct ICUDateAdd : public ICUDateFunc { return GetBinaryDateFunction(left_type, right_type, LogicalType::INTERVAL); } - static void AddDateSubOperators(const Identifier &name, ExtensionLoader &loader) { + template + static void AddDateSubFunction(ScalarFunctionSet &set, const LogicalTypeId &type) { // temporal - interval - ScalarFunctionSet set {name}; - auto tstz_interval_fun = GetDateAddFunction( - LogicalType::TIMESTAMP_TZ, LogicalType::INTERVAL); + auto tstz_interval_fun = + GetDateAddFunction(type, LogicalType::INTERVAL, type); tstz_interval_fun.GetSignature().GetParameter(0).SetName("left"); tstz_interval_fun.GetSignature().GetParameter(1).SetName("right"); set.AddFunction(tstz_interval_fun); + } + + static void AddDateSubOperators(const Identifier &name, ExtensionLoader &loader) { + ScalarFunctionSet set {name}; + AddDateSubFunction(set, LogicalType::TIMESTAMP_TZ); + AddDateSubFunction(set, LogicalType::TIMESTAMP_TZ_NS); // temporal - temporal auto tstz_tstz_fun = GetBinaryAgeFunction( diff --git a/src/duckdb/extension/icu/icu-table-range.cpp b/src/duckdb/extension/icu/icu-table-range.cpp index 560db9780..643ebba22 100644 --- a/src/duckdb/extension/icu/icu-table-range.cpp +++ b/src/duckdb/extension/icu/icu-table-range.cpp @@ -203,7 +203,7 @@ struct ICUTableRange { return nullptr; } auto &bind_data = bind_data_p->Cast(); - return make_uniq(bind_data.cardinality, bind_data.cardinality); + return make_uniq(bind_data.cardinality); } template diff --git a/src/duckdb/extension/icu/icu-timebucket.cpp b/src/duckdb/extension/icu/icu-timebucket.cpp index 74148f5ea..07db44975 100644 --- a/src/duckdb/extension/icu/icu-timebucket.cpp +++ b/src/duckdb/extension/icu/icu-timebucket.cpp @@ -387,6 +387,7 @@ struct ICUTimeBucket : public ICUDateFunc { } }; + template static void ICUTimeBucketFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 2); @@ -407,26 +408,30 @@ struct ICUTimeBucket : public ICUDateFunc { BucketWidthType bucket_width_type = ClassifyBucketWidth(bucket_width); switch (bucket_width_type) { case BucketWidthType::CONVERTIBLE_TO_MICROS: - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return WidthConvertibleToMicrosBinaryOperator::Operation(bucket_width, ts, calendar); }); break; case BucketWidthType::CONVERTIBLE_TO_DAYS: - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return WidthConvertibleToDaysBinaryOperator::Operation(bucket_width, ts, calendar); }); break; case BucketWidthType::CONVERTIBLE_TO_MONTHS: - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return WidthConvertibleToMonthsBinaryOperator::Operation(bucket_width, ts, calendar); }); break; case BucketWidthType::UNCLASSIFIED: - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return BinaryOperator::Operation(bucket_width, ts, calendar); }); break; @@ -434,13 +439,15 @@ struct ICUTimeBucket : public ICUDateFunc { throw NotImplementedException("Bucket type not implemented for ICU TIME_BUCKET"); } } else { - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return BinaryOperator::Operation(bucket_width, ts, calendar); }); } } + template static void ICUTimeBucketOffsetFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 3); @@ -462,33 +469,37 @@ struct ICUTimeBucket : public ICUDateFunc { BucketWidthType bucket_width_type = ClassifyBucketWidth(bucket_width); switch (bucket_width_type) { case BucketWidthType::CONVERTIBLE_TO_MICROS: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, offset_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, interval_t offset) { + [&](interval_t bucket_width, TB tb, interval_t offset) { + const auto ts = TruncCast(tb); return OffsetWidthConvertibleToMicrosTernaryOperator::Operation(bucket_width, ts, offset, calendar); }); break; case BucketWidthType::CONVERTIBLE_TO_DAYS: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, offset_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, interval_t offset) { + [&](interval_t bucket_width, TB tb, interval_t offset) { + const auto ts = TruncCast(tb); return OffsetWidthConvertibleToDaysTernaryOperator::Operation(bucket_width, ts, offset, calendar); }); break; case BucketWidthType::CONVERTIBLE_TO_MONTHS: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, offset_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, interval_t offset) { + [&](interval_t bucket_width, TB tb, interval_t offset) { + const auto ts = TruncCast(tb); return OffsetWidthConvertibleToMonthsTernaryOperator::Operation(bucket_width, ts, offset, calendar); }); break; case BucketWidthType::UNCLASSIFIED: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, offset_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, interval_t offset) { + [&](interval_t bucket_width, TB tb, interval_t offset) { + const auto ts = TruncCast(tb); return OffsetTernaryOperator::Operation(bucket_width, ts, offset, calendar); }); break; @@ -504,6 +515,7 @@ struct ICUTimeBucket : public ICUDateFunc { } } + template static void ICUTimeBucketOriginFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 3); @@ -527,34 +539,37 @@ struct ICUTimeBucket : public ICUDateFunc { BucketWidthType bucket_width_type = ClassifyBucketWidth(bucket_width); switch (bucket_width_type) { case BucketWidthType::CONVERTIBLE_TO_MICROS: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, origin_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, timestamp_tz_t origin) { + [&](interval_t bucket_width, TB tb, timestamp_tz_t origin) { + const auto ts = TruncCast(tb); return OriginWidthConvertibleToMicrosTernaryOperator::Operation(bucket_width, ts, origin, calendar); }); break; case BucketWidthType::CONVERTIBLE_TO_DAYS: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, origin_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, timestamp_tz_t origin) { + [&](interval_t bucket_width, TB tb, timestamp_tz_t origin) { + const auto ts = TruncCast(tb); return OriginWidthConvertibleToDaysTernaryOperator::Operation(bucket_width, ts, origin, calendar); }); break; case BucketWidthType::CONVERTIBLE_TO_MONTHS: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, origin_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, timestamp_tz_t origin) { + [&](interval_t bucket_width, TB tb, timestamp_tz_t origin) { + const auto ts = TruncCast(tb); return OriginWidthConvertibleToMonthsTernaryOperator::Operation(bucket_width, ts, origin, calendar); }); break; case BucketWidthType::UNCLASSIFIED: - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, origin_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, - timestamp_tz_t origin) -> optional { + [&](interval_t bucket_width, TB tb, timestamp_tz_t origin) -> optional { + const auto ts = TruncCast(tb); return OriginTernaryOperator::Operation(bucket_width, ts, origin, calendar); }); break; @@ -563,14 +578,16 @@ struct ICUTimeBucket : public ICUDateFunc { } } } else { - TernaryExecutor::Execute( + TernaryExecutor::Execute( bucket_width_arg, ts_arg, origin_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, timestamp_tz_t origin) -> optional { + [&](interval_t bucket_width, TB tb, timestamp_tz_t origin) -> optional { + const auto ts = TruncCast(tb); return OriginTernaryOperator::Operation(bucket_width, ts, origin, calendar); }); } } + template static void ICUTimeBucketTimeZoneFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 3); @@ -596,8 +613,9 @@ struct ICUTimeBucket : public ICUDateFunc { case BucketWidthType::CONVERTIBLE_TO_MICROS: origin = ICUDateFunc::FromNaive(calendar.GetCalendar(), Timestamp::FromEpochMicroSeconds(DEFAULT_ORIGIN_MICROS_1)); - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return TimeZoneWidthConvertibleToMicrosBinaryOperator::Operation(bucket_width, ts, origin, calendar); }); @@ -605,8 +623,9 @@ struct ICUTimeBucket : public ICUDateFunc { case BucketWidthType::CONVERTIBLE_TO_DAYS: origin = ICUDateFunc::FromNaive(calendar.GetCalendar(), Timestamp::FromEpochMicroSeconds(DEFAULT_ORIGIN_MICROS_1)); - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return TimeZoneWidthConvertibleToDaysBinaryOperator::Operation(bucket_width, ts, origin, calendar); }); @@ -614,16 +633,17 @@ struct ICUTimeBucket : public ICUDateFunc { case BucketWidthType::CONVERTIBLE_TO_MONTHS: origin = ICUDateFunc::FromNaive(calendar.GetCalendar(), Timestamp::FromEpochMicroSeconds(DEFAULT_ORIGIN_MICROS_2)); - BinaryExecutor::Execute( - bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts) { + BinaryExecutor::Execute( + bucket_width_arg, ts_arg, result, [&](interval_t bucket_width, TB tb) { + const auto ts = TruncCast(tb); return TimeZoneWidthConvertibleToMonthsBinaryOperator::Operation(bucket_width, ts, origin, calendar); }); break; case BucketWidthType::UNCLASSIFIED: - TernaryExecutor::Execute( - bucket_width_arg, ts_arg, tz_arg, result, - [&](interval_t bucket_width, timestamp_tz_t ts, string_t tz) { + TernaryExecutor::Execute( + bucket_width_arg, ts_arg, tz_arg, result, [&](interval_t bucket_width, TB tb, string_t tz) { + const auto ts = TruncCast(tb); return TimeZoneTernaryOperator::Operation(bucket_width, ts, tz, calendar, cache); }); break; @@ -631,38 +651,65 @@ struct ICUTimeBucket : public ICUDateFunc { throw NotImplementedException("Bucket type not implemented for ICU TIME_BUCKET"); } } else { - TernaryExecutor::Execute( - bucket_width_arg, ts_arg, tz_arg, result, [&](interval_t bucket_width, timestamp_tz_t ts, string_t tz) { + TernaryExecutor::Execute( + bucket_width_arg, ts_arg, tz_arg, result, [&](interval_t bucket_width, TB tb, string_t tz) { + const auto ts = TruncCast(tb); return TimeZoneTernaryOperator::Operation(bucket_width, ts, tz, calendar, cache); }); } } - static void AddTimeBucketFunction(ExtensionLoader &loader) { - ScalarFunctionSet set("time_bucket"); - ScalarFunction base_fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketFunction, Bind); - base_fun.GetSignature() - .AddParameter("bucket_width", LogicalType::INTERVAL) - .AddParameter("timestamp", LogicalType::TIMESTAMP_TZ); - set.AddFunction(base_fun); - ScalarFunction offset_fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketOffsetFunction, Bind); - offset_fun.GetSignature() + template + static ScalarFunction GetTimeBucketFunction(const LogicalTypeId &type) { + ScalarFunction fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketFunction, Bind); + fun.GetSignature().AddParameter("bucket_width", LogicalType::INTERVAL).AddParameter("timestamp", type); + return fun; + } + + template + static ScalarFunction GetTimeBucketOffsetFunction(const LogicalTypeId &type) { + ScalarFunction fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketOffsetFunction, Bind); + fun.GetSignature() .AddParameter("bucket_width", LogicalType::INTERVAL) - .AddParameter("timestamp", LogicalType::TIMESTAMP_TZ) + .AddParameter("timestamp", type) .AddParameter("offset", LogicalType::INTERVAL); - set.AddFunction(offset_fun); - ScalarFunction origin_fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketOriginFunction, Bind); - origin_fun.GetSignature() + return fun; + } + + template + static ScalarFunction GetTimeBucketOriginFunction(const LogicalTypeId &type) { + ScalarFunction fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketOriginFunction, Bind); + fun.GetSignature() .AddParameter("bucket_width", LogicalType::INTERVAL) - .AddParameter("timestamp", LogicalType::TIMESTAMP_TZ) + .AddParameter("timestamp", type) .AddParameter("origin", LogicalType::TIMESTAMP_TZ); - set.AddFunction(origin_fun); - ScalarFunction timezone_fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketTimeZoneFunction, Bind); - timezone_fun.GetSignature() + return fun; + } + + template + static ScalarFunction GetTimeBucketTimeZoneFunction(const LogicalTypeId &type) { + ScalarFunction fun({}, LogicalType::TIMESTAMP_TZ, ICUTimeBucketTimeZoneFunction, Bind); + fun.GetSignature() .AddParameter("bucket_width", LogicalType::INTERVAL) - .AddParameter("timestamp", LogicalType::TIMESTAMP_TZ) + .AddParameter("timestamp", type) .AddParameter("timezone", LogicalType::VARCHAR); - set.AddFunction(timezone_fun); + return fun; + } + + static void AddTimeBucketFunction(ExtensionLoader &loader) { + ScalarFunctionSet set("time_bucket"); + set.AddFunction(GetTimeBucketFunction(LogicalType::TIMESTAMP_TZ)); + set.AddFunction(GetTimeBucketFunction(LogicalType::TIMESTAMP_TZ_NS)); + + set.AddFunction(GetTimeBucketOffsetFunction(LogicalType::TIMESTAMP_TZ)); + set.AddFunction(GetTimeBucketOffsetFunction(LogicalType::TIMESTAMP_TZ_NS)); + + set.AddFunction(GetTimeBucketOriginFunction(LogicalType::TIMESTAMP_TZ)); + set.AddFunction(GetTimeBucketOriginFunction(LogicalType::TIMESTAMP_TZ_NS)); + + set.AddFunction(GetTimeBucketTimeZoneFunction(LogicalType::TIMESTAMP_TZ)); + set.AddFunction(GetTimeBucketTimeZoneFunction(LogicalType::TIMESTAMP_TZ_NS)); + set.ApplyToFunctions([](ScalarFunction &func) { func.SetFallible(); func.SetStability(FunctionStability::CONSISTENT_WITHIN_QUERY); diff --git a/src/duckdb/extension/icu/icu-timezone.cpp b/src/duckdb/extension/icu/icu-timezone.cpp index fd785373c..64dd09167 100644 --- a/src/duckdb/extension/icu/icu-timezone.cpp +++ b/src/duckdb/extension/icu/icu-timezone.cpp @@ -366,6 +366,20 @@ struct ICUToNaiveTimestamp : public ICUDateFunc { return result; } + //! Rounds the local time micros * 1000 + nanos to microseconds, away from zero on ties like the other casts. + //! The nanosecond value is not formed, as it can overflow int64 where the microsecond value does not. + static timestamp_t RoundToMicros(timestamp_t micros, int32_t nanos) { + auto value = micros.value; + if (value == 0) { + value = nanos >= 500 ? 1 : (nanos <= -500 ? -1 : 0); + } else if (value > 0) { + value += nanos >= 0 ? (nanos >= 500 ? 1 : 0) : (nanos < -500 ? -1 : 0); + } else { + value += nanos <= 0 ? (nanos <= -500 ? -1 : 0) : (nanos > 500 ? 1 : 0); + } + return timestamp_t(value); + } + template static bool CastToNaive(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { auto &cast_data = parameters.cast_data->Cast(); @@ -374,6 +388,21 @@ struct ICUToNaiveTimestamp : public ICUDateFunc { bool all_converted = true; UnaryExecutor::Execute(source, result, count, [&](SRC input) -> optional { + if constexpr (std::is_same::value && std::is_same::value) { + if (input.IsFinite()) { + // shift in microseconds: the local time can lie outside the timestamp_ns range + timestamp_t micros_naive; + string micros_error; + const auto nanos = UnsafeNumericCast(input.value % Interval::NANOS_PER_MICRO); + const timestamp_tz_t micros(input.value / Interval::NANOS_PER_MICRO); + if (!TryOperation(calendar.get(), micros, micros_naive, micros_error)) { + HandleCastError::AssignError(micros_error, parameters); + all_converted = false; + return nullopt; + } + return RoundToMicros(micros_naive, nanos); + } + } using NAIVE = timestamp_base_t; // the zone shift itself can fail, and a TRY_CAST must see that as NULL rather than an exception NAIVE naive; @@ -422,6 +451,8 @@ struct ICUToNaiveTimestamp : public ICUDateFunc { } case LogicalTypeId::TIMESTAMP_TZ_NS: switch (target.id()) { + case LogicalType::TIMESTAMP: + return BoundCastInfo(CastToNaive, std::move(cast_data)); case LogicalType::TIMESTAMP_NS: return BoundCastInfo(CastToNaive, std::move(cast_data)); default: @@ -446,6 +477,7 @@ struct ICUToNaiveTimestamp : public ICUDateFunc { AddCast(casts, LogicalType::TIMESTAMP_TZ, LogicalType::TIMESTAMP_NS); AddCast(casts, LogicalType::TIMESTAMP_TZ, LogicalType::TIMESTAMP_S); + AddCast(casts, LogicalType::TIMESTAMP_TZ_NS, LogicalType::TIMESTAMP); AddCast(casts, LogicalType::TIMESTAMP_TZ_NS, LogicalType::TIMESTAMP_NS); } }; diff --git a/src/duckdb/extension/icu/include/icu-datefunc.hpp b/src/duckdb/extension/icu/include/icu-datefunc.hpp index 7f5c2f68b..0ee8876ae 100644 --- a/src/duckdb/extension/icu/include/icu-datefunc.hpp +++ b/src/duckdb/extension/icu/include/icu-datefunc.hpp @@ -47,7 +47,7 @@ struct ICUDateFunc { template static inline DST TruncCast(const SRC &src) { DST dst; - if (SRC::PRECISION == DST::PRECISION) { + if (SRC::PRECISION == DST::PRECISION || !src.IsFinite()) { dst.value = src.value; } else { // Truncate towards -infinity, not epoch. diff --git a/src/duckdb/extension/json/include/json_reader.hpp b/src/duckdb/extension/json/include/json_reader.hpp index 0e7017022..e1d0c365a 100644 --- a/src/duckdb/extension/json/include/json_reader.hpp +++ b/src/duckdb/extension/json/include/json_reader.hpp @@ -43,6 +43,8 @@ struct JSONBufferHandle { const idx_t buffer_size; //! The start position in the buffer idx_t buffer_start; + //! The start of the line copied in from the previous buffer, set once it is copied + atomic remainder_start; }; struct JSONFileHandle { @@ -220,8 +222,10 @@ class JSONReader { JSONFileHandle &GetFileHandle() const; public: - //! Get a new buffer index (must hold the lock) + //! Get a new buffer index (grabs the lock) idx_t GetBufferIndex(); + //! The index the next buffer will receive (grabs the lock) + idx_t GetNextBufferIndex(); //! Set line count for a buffer that is done (grabs the lock) void SetBufferLineOrObjectCount(JSONBufferHandle &handle, idx_t count); //! Records a parse error in the specified buffer 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 99158b992..00fdba96c 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp @@ -147,8 +147,8 @@ static void JsonSerializePlanFunction(DataChunk &args, ExpressionState &state, V ColumnBindingResolver resolver; LogicalPlanVerifier::Verify(context, *plan); - resolver.VisitOperator(*plan); plan->ResolveOperatorTypes(); + resolver.VisitOperator(*plan); string operator_name; if (!OperatorSupportsSerialization(*plan, operator_name)) { diff --git a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp index eab0ce04b..e4b270295 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp @@ -8,6 +8,7 @@ #include "json_functions.hpp" #include "json_serializer.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/literal.hpp" namespace duckdb { @@ -194,6 +195,10 @@ static vector> DeserializeSelectStatement(string_t i throw ParserException("Error parsing json: no statements"); } + DeserializationPolicy policy; + policy.Disallow(LogicalTypeId::POINTER); + policy.Disallow(LiteralKind::POINTER); + vector> result; idx_t idx; @@ -201,6 +206,7 @@ static vector> DeserializeSelectStatement(string_t i yyjson_val *stmt_json; yyjson_arr_foreach(statements, idx, max, stmt_json) { JsonDeserializer deserializer(stmt_json, doc); + deserializer.SetPolicy(policy); auto stmt = SelectStatement::Deserialize(deserializer); if (!stmt->node) { throw ParserException("Error parsing json: no select node found in json"); @@ -281,7 +287,6 @@ PragmaFunctionSet JSONFunctions::GetExecuteJsonSerializedSqlPragmaFunction() { struct ExecuteSqlTableFunction { struct BindData : public TableFunctionData { shared_ptr plan; - unique_ptr result; unique_ptr con; bool SupportStatementCache() const override { @@ -289,6 +294,16 @@ struct ExecuteSqlTableFunction { } }; + // The result is scan state, not bind state: a scan can be initialized multiple times (e.g. per recursive + // CTE iteration) and must produce the full result each time. + struct State : public GlobalTableFunctionState { + unique_ptr result; + }; + + static unique_ptr Init(ClientContext &context, TableFunctionInitInput &input) { + return make_uniq(); + } + static unique_ptr Bind(ClientContext &context, TableFunctionBindInput &input, vector &return_types, vector &names) { JSONFunctionLocalState local_state(context); @@ -315,11 +330,12 @@ struct ExecuteSqlTableFunction { } static void Function(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { - auto &data = data_p.bind_data->CastNoConst(); - if (!data.result) { - data.result = data.plan->Execute(); + auto &data = data_p.bind_data->Cast(); + auto &state = data_p.global_state->Cast(); + if (!state.result) { + state.result = data.plan->ExecuteOrThrow(); } - auto result_chunk = data.result->Fetch(); + auto result_chunk = state.result->Fetch(); if (!result_chunk) { return; } @@ -330,7 +346,7 @@ struct ExecuteSqlTableFunction { TableFunctionSet JSONFunctions::GetExecuteJsonSerializedSqlFunction() { TableFunction func("json_execute_serialized_sql", FunctionSignature().AddPositionalOnly("serialized_sql", LogicalType::VARCHAR), - ExecuteSqlTableFunction::Function, ExecuteSqlTableFunction::Bind); + ExecuteSqlTableFunction::Function, ExecuteSqlTableFunction::Bind, ExecuteSqlTableFunction::Init); return TableFunctionSet(func); } diff --git a/src/duckdb/extension/json/json_functions/json_table_in_out.cpp b/src/duckdb/extension/json/json_functions/json_table_in_out.cpp index 26e1848b6..633147f80 100644 --- a/src/duckdb/extension/json/json_functions/json_table_in_out.cpp +++ b/src/duckdb/extension/json/json_functions/json_table_in_out.cpp @@ -191,6 +191,9 @@ struct JSONTableInOutLocalState : LocalTableFunctionState { idx_t len; yyjson_doc *doc; bool initialized; + //! The input row currently being processed, and its document (for the "json" virtual column) + idx_t input_row = 0; + string json_doc; idx_t total_count; vector recursion_nodes; @@ -312,11 +315,11 @@ static void InitializeLocalState(JSONTableInOutLocalState &lstate, DataChunk &in // Parse path, default to root if not given Value path_value("$"); if (input.data.size() > 1) { - const auto &path_vector = input.data[1]; - if (ConstantVector::IsNull(path_vector)) { + const auto path_values = input.data[1].Values(); + if (!path_values[lstate.input_row].IsValid()) { return; } - path_value = ConstantVector::GetData(path_vector)[0]; + path_value = path_values[lstate.input_row].GetValue(); } if (JSONReadFunctionData::CheckPath(path_value, lstate.path, lstate.len) == JSONCommon::JSONPathType::WILDCARD) { @@ -328,11 +331,15 @@ static void InitializeLocalState(JSONTableInOutLocalState &lstate, DataChunk &in } // Parse document and get the value at the supplied path - const auto &input_vector = input.data[0]; - if (ConstantVector::IsNull(input_vector)) { + const auto input_values = input.data[0].Values(); + if (!input_values[lstate.input_row].IsValid()) { return; } - const auto &input_data = ConstantVector::GetData(input_vector)[0]; + const auto input_data = input_values[lstate.input_row].GetValue(); + if (lstate.gstate.json_column_index.IsValid()) { + // Copy the document only when the "json" virtual column is selected + lstate.json_doc = input_data.GetString(); + } lstate.doc = JSONCommon::ReadDocument(input_data, JSONCommon::READ_FLAG, lstate.alc); const auto root = JSONCommon::GetUnsafe(lstate.doc->root, lstate.path.c_str(), lstate.len); @@ -383,6 +390,9 @@ static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFuncti JSONTableInOutResult result(gstate, output); if (!lstate.initialized) { + if (lstate.input_row >= input.size()) { + return OperatorResultType::NEED_MORE_INPUT; + } InitializeLocalState(lstate, input, result); lstate.initialized = true; } @@ -424,7 +434,9 @@ static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFuncti // Set constant virtual columns ("json", "root", and "empty") if (gstate.json_column_index.IsValid()) { auto &json_vector = output.data[gstate.json_column_index.GetIndex()]; - json_vector.Reference(input.data[0]); + json_vector.SetVectorType(VectorType::CONSTANT_VECTOR); + ConstantVector::GetData(json_vector)[0] = string_t(lstate.json_doc.c_str(), lstate.json_doc.size()); + FlatVector::SetSize(json_vector, count_t(result.count)); } if (gstate.root_column_index.IsValid()) { auto &root_vector = output.data[gstate.root_column_index.GetIndex()]; @@ -449,6 +461,12 @@ static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFuncti lstate.produced_rows = 0; lstate.json_allocator.Reset(); lstate.initialized = false; + lstate.input_row++; + if (lstate.input_row < input.size()) { + // start on the next input row with the next output chunk + return OperatorResultType::HAVE_MORE_OUTPUT; + } + lstate.input_row = 0; return OperatorResultType::NEED_MORE_INPUT; } return OperatorResultType::HAVE_MORE_OUTPUT; diff --git a/src/duckdb/extension/json/json_functions/json_transform.cpp b/src/duckdb/extension/json/json_functions/json_transform.cpp index d6cb8da9d..dca676a8a 100644 --- a/src/duckdb/extension/json/json_functions/json_transform.cpp +++ b/src/duckdb/extension/json/json_functions/json_transform.cpp @@ -9,6 +9,7 @@ #include "duckdb/common/enum_util.hpp" #include "duckdb/common/error_data.hpp" +#include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/operator/decimal_cast_operators.hpp" #include "duckdb/common/operator/string_cast.hpp" #include "duckdb/common/serializer/deserializer.hpp" @@ -154,7 +155,7 @@ static inline bool GetValueNumerical(yyjson_val *val, T &result, JSONTransformOp } template -static inline bool GetValueDecimal(yyjson_val *val, T &result, uint8_t w, uint8_t s, JSONTransformOptions &options) { +static inline bool GetValueDecimal(yyjson_val *val, T &result, uint32_t w, uint32_t s, JSONTransformOptions &options) { D_ASSERT(unsafe_yyjson_get_tag(val) != (YYJSON_TYPE_NULL | YYJSON_SUBTYPE_NONE)); bool success; switch (unsafe_yyjson_get_tag(val)) { @@ -251,7 +252,7 @@ static bool TransformNumerical(yyjson_val *vals[], Vector &result, const idx_t c } template -static bool TransformDecimal(yyjson_val *vals[], Vector &result, const idx_t count, uint8_t width, uint8_t scale, +static bool TransformDecimal(yyjson_val *vals[], Vector &result, const idx_t count, uint32_t width, uint32_t scale, JSONTransformOptions &options) { auto data = FlatVector::GetDataMutable(result); auto &validity = FlatVector::ValidityMutable(result); @@ -323,6 +324,36 @@ static bool TransformFromString(yyjson_val *vals[], Vector &result, const idx_t return success; } +//! BLOB reads as the existing VARCHAR rendering, except JSON strings go through the VARCHAR -> BLOB cast so their +//! \xNN escapes decode into bytes. Rendering non-strings through that cast would misread ordinary JSON escapes +//! (e.g. \n is not a valid BLOB escape), so their rendered text is written directly as bytes instead. +static bool TransformToBlob(yyjson_val *vals[], yyjson_alc *alc, Vector &result, const idx_t count, + JSONTransformOptions &options) { + auto data = FlatVector::GetDataMutable(result); + auto &validity = FlatVector::ValidityMutable(result); + JSONRawNumberWriter raw_writer(alc); + + CastParameters parameters(options.strict_cast, &options.error_message); + bool success = true; + for (idx_t i = 0; i < count; i++) { + const auto &val = vals[i]; + if (!val || unsafe_yyjson_is_null(val)) { + validity.SetInvalid(i); + } else if (unsafe_yyjson_is_str(val)) { + if (!TryCastToBlob::Operation(GetString(val), data[i], result, parameters)) { + validity.SetInvalid(i); + if (success && options.strict_cast) { + options.object_index = i; + success = false; + } + } + } else if (!GetValueString(val, alc, data[i], result, options.numbers_as_raw ? &raw_writer : nullptr)) { + validity.SetInvalid(i); + } + } + return success; +} + //! GEOMETRY accepts both WKT strings and GeoJSON geometry fragments. A JSON object is never valid WKT, so the two //! are unambiguous and no option is needed to tell them apart. static bool TransformGeometry(yyjson_val *vals[], Vector &result, const idx_t count, JSONTransformOptions &options) { @@ -953,8 +984,7 @@ static bool TransformObjectToMap(yyjson_val *objects[], yyjson_alc *alc, Vector // Transform keys if (!JSONTransform::Transform(keys, alc, MapVector::GetKeys(result), list_size, options, nullptr)) { - throw ConversionException( - StringUtil::Format("%s. Cannot default to NULL, because map keys cannot be NULL", options.error_message)); + success = false; } // Transform values @@ -1167,8 +1197,9 @@ bool JSONTransform::Transform(yyjson_val *vals[], yyjson_alc *alc, Vector &resul case LogicalTypeId::GEOMETRY: return TransformGeometry(vals, result, count, options); case LogicalTypeId::VARCHAR: - case LogicalTypeId::BLOB: return TransformToString(vals, alc, result, count, options); + case LogicalTypeId::BLOB: + return TransformToBlob(vals, alc, result, count, options); case LogicalTypeId::STRUCT: return TransformObjectInternal(vals, alc, result, count, options, column_index); case LogicalTypeId::TUPLE: diff --git a/src/duckdb/extension/json/json_functions/read_json.cpp b/src/duckdb/extension/json/json_functions/read_json.cpp index f6caf6422..f4d8cad03 100644 --- a/src/duckdb/extension/json/json_functions/read_json.cpp +++ b/src/duckdb/extension/json/json_functions/read_json.cpp @@ -70,7 +70,7 @@ class JSONSchemaTask : public BaseExecutorTask { auto &context = auto_detect_state.context; auto &files = auto_detect_state.files; auto &json_data = auto_detect_state.json_data; - auto json_reader = make_shared_ptr(context, json_data.options, files[file_idx].path); + auto json_reader = make_shared_ptr(context, json_data.options, files[file_idx]); if (auto_detect_state.sampled_readers[file_idx]) { throw InternalException("Reader for file %llu was already created", file_idx); } diff --git a/src/duckdb/extension/json/json_functions/read_single_json_file.cpp b/src/duckdb/extension/json/json_functions/read_single_json_file.cpp index ddba342ab..e22d3c5d8 100644 --- a/src/duckdb/extension/json/json_functions/read_single_json_file.cpp +++ b/src/duckdb/extension/json/json_functions/read_single_json_file.cpp @@ -347,8 +347,9 @@ TableFunction JSONFunctions::GetJSONTableFunction(Identifier name, shared_ptr function_info) { diff --git a/src/duckdb/extension/json/json_reader.cpp b/src/duckdb/extension/json/json_reader.cpp index 804e5b47c..def1a669e 100644 --- a/src/duckdb/extension/json/json_reader.cpp +++ b/src/duckdb/extension/json/json_reader.cpp @@ -16,7 +16,7 @@ namespace duckdb { JSONBufferHandle::JSONBufferHandle(JSONReader &reader, idx_t buffer_index_p, idx_t readers_p, AllocatedData buffer_p, idx_t buffer_size_p, idx_t buffer_start_p) : reader(reader), buffer_index(buffer_index_p), readers(readers_p), buffer(std::move(buffer_p)), - buffer_size(buffer_size_p), buffer_start(buffer_start_p) { + buffer_size(buffer_size_p), buffer_start(buffer_start_p), remainder_start(DConstants::INVALID_INDEX) { } JSONFileHandle::JSONFileHandle(QueryContext context_p, unique_ptr file_handle_p, Allocator &allocator_p) @@ -107,7 +107,7 @@ bool JSONFileHandle::GetPositionAndSize(idx_t &position, idx_t &size, idx_t requ read_position += size; requested_reads++; - if (size == 0) { + if (Remaining() == 0) { last_read_requested = true; } @@ -316,10 +316,16 @@ AllocatedData JSONReader::RemoveBuffer(JSONBufferHandle &handle) { } idx_t JSONReader::GetBufferIndex() { + lock_guard guard(lock); buffer_line_or_object_counts.push_back(-1); return next_buffer_index++; } +idx_t JSONReader::GetNextBufferIndex() { + lock_guard guard(lock); + return next_buffer_index; +} + void JSONReader::SetBufferLineOrObjectCount(JSONBufferHandle &handle, idx_t count) { lock_guard guard(lock); D_ASSERT(buffer_map.find(handle.buffer_index) != buffer_map.end()); @@ -941,12 +947,25 @@ bool JSONReader::CopyRemainderFromPreviousBuffer(JSONReaderScanState &scan_state } // First we find the newline in the previous block + auto prev_buffer_data = char_ptr_cast(previous_buffer_handle->buffer.get()); idx_t prev_buffer_size = previous_buffer_handle->buffer_size - previous_buffer_handle->buffer_start; - auto prev_buffer_ptr = char_ptr_cast(previous_buffer_handle->buffer.get()) + previous_buffer_handle->buffer_size; + auto prev_buffer_ptr = prev_buffer_data + previous_buffer_handle->buffer_size; // the first buffer of a file that is only a byte order mark holds nothing past it - auto prev_object_start = - prev_buffer_size == 0 ? prev_buffer_ptr : PreviousNewline(prev_buffer_ptr, prev_buffer_size); - auto prev_object_size = NumericCast(prev_buffer_ptr - prev_object_start); + const char *prev_newline = prev_buffer_size == 0 ? nullptr : PreviousNewline(prev_buffer_ptr, prev_buffer_size); + idx_t prev_object_offset; + if (prev_newline && *prev_newline == '\n') { + prev_object_offset = NumericCast(prev_newline - prev_buffer_data) + 1; + } else { + // The previous block has no newline, so wait until it has copied its own remainder + while ((prev_object_offset = previous_buffer_handle->remainder_start.load()) == DConstants::INVALID_INDEX) { + if (HasThrown()) { + return false; + } + } + } + SkipWhitespace(prev_buffer_data, prev_object_offset, previous_buffer_handle->buffer_size); + auto prev_object_start = prev_buffer_data + prev_object_offset; + auto prev_object_size = previous_buffer_handle->buffer_size - prev_object_offset; D_ASSERT(scan_state.buffer_offset == options.maximum_object_size); if (prev_object_size > scan_state.buffer_offset) { @@ -955,16 +974,13 @@ bool JSONReader::CopyRemainderFromPreviousBuffer(JSONReaderScanState &scan_state // Now copy the data to our reconstruct buffer memcpy(scan_state.buffer_ptr + scan_state.buffer_offset - prev_object_size, prev_object_start, prev_object_size); - // Just a newline, or nothing. A single byte without a newline before it is a value, such as a 1 at the end of a - // file. This is checked before the previous buffer is released - const bool no_remainder = prev_object_size == 0 || (prev_object_size == 1 && *prev_object_start == '\n'); - // We copied the object, so we are no longer reading the previous buffer if (--previous_buffer_handle->readers == 0) { RemoveBuffer(*previous_buffer_handle); } - if (no_remainder) { + // Nothing but whitespace was left in the previous buffer + if (prev_object_size == 0) { return false; } scan_state.buffer_offset -= prev_object_size; @@ -1129,18 +1145,16 @@ void JSONReader::FinalizeBuffer(JSONReaderScanState &scan_state) { } // we read something - // skip over the array start if required - if (!scan_state.is_last) { - if (scan_state.buffer_index.GetIndex() == 0) { - // the file starts at the buffer offset, which leaves room for the end of a previous buffer when the file - // is read in parallel - idx_t bom_size = 0; - StringUtil::SkipBOM(scan_state.buffer_ptr + scan_state.buffer_offset, - scan_state.buffer_size - scan_state.buffer_offset, bom_size); - scan_state.buffer_offset += bom_size; - if (GetFormat() == JSONFormat::ARRAY) { - SkipOverArrayStart(scan_state); - } + // skip over the BOM and the array start if required + if (scan_state.buffer_index.GetIndex() == 0 && scan_state.buffer_size >= scan_state.buffer_offset) { + // the file starts at the buffer offset, which leaves room for the end of a previous buffer when the file + // is read in parallel + idx_t bom_size = 0; + StringUtil::SkipBOM(scan_state.buffer_ptr + scan_state.buffer_offset, + scan_state.buffer_size - scan_state.buffer_offset, bom_size); + scan_state.buffer_offset += bom_size; + if (GetFormat() == JSONFormat::ARRAY) { + SkipOverArrayStart(scan_state); } } // then finalize the buffer @@ -1187,6 +1201,7 @@ void JSONReader::FinalizeBufferInternal(JSONReaderScanState &scan_state, Allocat if (scan_state.buffer_index.GetIndex() != 0) { CopyRemainderFromPreviousBuffer(scan_state); } + scan_state.current_buffer_handle->remainder_start = scan_state.buffer_offset; } scan_state.prev_buffer_remainder = 0; @@ -1231,7 +1246,7 @@ void JSONReader::PrepareForReadInternal(JSONReaderScanState &scan_state) { bool JSONReader::PrepareBufferForRead(JSONReaderScanState &scan_state) { if (auto_detect_data.IsSet()) { // we have auto-detected data - re-use the buffer - if (next_buffer_index != 0 || auto_detect_data_size == 0 || scan_state.prev_buffer_remainder != 0) { + if (GetNextBufferIndex() != 0 || auto_detect_data_size == 0 || scan_state.prev_buffer_remainder != 0) { throw InternalException("Invalid re-use of auto-detect data in JSON"); } scan_state.buffer_index = GetBufferIndex(); @@ -1263,19 +1278,19 @@ bool JSONReader::PrepareBufferForRead(JSONReaderScanState &scan_state) { bool JSONReader::PrepareBufferSeek(JSONReaderScanState &scan_state) { scan_state.request_size = scan_state.buffer_capacity / 2 - scan_state.prev_buffer_remainder - YYJSON_PADDING_SIZE; - if (!IsOpen()) { + if (!HasFileHandle()) { return false; } auto &file_handle = GetFileHandle(); - - if (file_handle.LastReadRequested()) { + // the last read may close the handle concurrently, so check this before IsOpen() + if (file_handle.LastReadRequested() || !IsOpen()) { return false; } if (!file_handle.GetPositionAndSize(scan_state.read_position, scan_state.read_size, scan_state.request_size)) { return false; // We weren't able to read } scan_state.buffer_index = GetBufferIndex(); - scan_state.is_last = scan_state.read_size == 0; + scan_state.is_last = file_handle.LastReadRequested(); scan_state.needs_to_read = true; scan_state.buffer_size = 0; return true; @@ -1298,7 +1313,7 @@ void JSONReader::ReadNextBufferSeek(JSONReaderScanState &scan_state) { scan_state.thread_local_filehandle->GetPath() != raw_handle.GetPath()) { FileOpenFlags flags = FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_DIRECT_IO; flags.SetCachingMode(CachingMode::CACHE_REMOTE_ONLY); - scan_state.thread_local_filehandle = scan_state.fs.OpenFile(raw_handle.GetPath(), flags); + scan_state.thread_local_filehandle = scan_state.fs.OpenFile(file, flags); } } else if (scan_state.thread_local_filehandle) { scan_state.thread_local_filehandle = nullptr; diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index ffa419f15..952b2a96b 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -472,7 +472,8 @@ bool ColumnReader::PageIsFilteredOut(PageHeader &page_hdr, optional_ptrCast(); if (stats) { auto prune_result = expr_filter.CheckStatistics(*stats); @@ -602,13 +603,16 @@ void ColumnReader::ResetPage() { void ColumnReader::PreparePageV2(PageHeader &page_hdr) { D_ASSERT(page_hdr.type == PageType::DATA_PAGE_V2); - AllocateBlock(NumericCast(page_hdr.uncompressed_page_size) + 1); + AllocateBlock(NumericCast(page_hdr.uncompressed_page_size)); const auto page_body_size = GetPageBodySize(page_hdr); bool uncompressed = false; if (page_hdr.data_page_header_v2.__isset.is_compressed && !page_hdr.data_page_header_v2.is_compressed) { uncompressed = true; } if (chunk->meta_data.codec == CompressionCodec::UNCOMPRESSED) { + uncompressed = true; + } + if (uncompressed) { if (page_body_size != NumericCast(page_hdr.uncompressed_page_size)) { // LCOV_EXCL_START const auto &file_name = Reader().GetFileName(); @@ -617,9 +621,6 @@ void ColumnReader::PreparePageV2(PageHeader &page_hdr) { page_hdr.uncompressed_page_size, page_body_size); // LCOV_EXCL_STOP } - uncompressed = true; - } - if (uncompressed) { ReadData(block->ptr, page_body_size, page_hdr.type); return; } @@ -701,16 +702,20 @@ uint32_t ColumnReader::GetPageBodySize(const PageHeader &page_hdr) const { return page_body_size; } -void ColumnReader::AllocateBlock(idx_t size) { +void ColumnReader::AllocateBlock(idx_t payload_size) { + const auto allocation_size = payload_size + 1; if (!block) { - block = make_shared_ptr(GetAllocator(), size); + block = make_shared_ptr(GetAllocator(), allocation_size); } else { - block->resize(GetAllocator(), size); + block->resize(GetAllocator(), 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; } void ColumnReader::PreparePage(PageHeader &page_hdr) { - AllocateBlock(NumericCast(page_hdr.uncompressed_page_size) + 1); + AllocateBlock(NumericCast(page_hdr.uncompressed_page_size)); const auto compressed_page_size = GetPageBodySize(page_hdr); if (chunk->meta_data.codec == CompressionCodec::UNCOMPRESSED) { @@ -785,7 +790,12 @@ void ColumnReader::DecompressInternal(CompressionCodec::type codec, const_data_p throw InternalException("Parquet data unexpectedly uncompressed"); case CompressionCodec::GZIP: { MiniZStream s; - s.Decompress(const_char_ptr_cast(src), src_size, char_ptr_cast(dst), dst_size); + auto remaining_size = s.Decompress(const_char_ptr_cast(src), src_size, char_ptr_cast(dst), dst_size); + if (remaining_size != 0) { + throw DataCorruptionException( + "Failed to read file \"%s\": GZIP uncompressed data size mismatch (expected %d, actual: %d)", + Reader().GetFileName(), dst_size, dst_size - remaining_size); + } break; } case CompressionCodec::LZ4: @@ -846,6 +856,11 @@ void ColumnReader::DecompressInternal(CompressionCodec::type codec, const_data_p throw InvalidInputException("Failed to read file \"%s\": Brotli Decompression failure", Reader().GetFileName()); } + if (total_out != dst_size) { + throw DataCorruptionException( + "Failed to read file \"%s\": Brotli uncompressed data size mismatch (expected %d, actual: %d)", + Reader().GetFileName(), dst_size, total_out); + } break; } @@ -1099,7 +1114,11 @@ void ColumnReader::Select(ColumnReaderInput &input, Vector &result, const Select DirectSelect(input, result, sel, approved_tuple_count); return; } - Read(input, result); + const auto rows_read = Read(input, result); + if (rows_read != num_values) { + throw DataCorruptionException("Mismatch in parquet read for column \"%s\", expected %llu rows, got %llu", + Schema().name, num_values, rows_read); + } } void ColumnReader::DirectSelect(ColumnReaderInput &input, Vector &result, const SelectionVector &sel, 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 724e8290d..346da31e3 100644 --- a/src/duckdb/extension/parquet/decoder/byte_stream_split_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/byte_stream_split_decoder.cpp @@ -36,9 +36,7 @@ static idx_t GetValueWidth(const ParquetColumnSchema &schema) { void ByteStreamSplitDecoder::InitializePage() { auto &block = reader.block; - // Subtract 1 from length as the block is allocated with 1 extra byte, - // but the byte stream split encoder needs to know the correct data size. - bss_decoder = make_uniq(block->ptr, block->len - 1, GetValueWidth(reader.Schema())); + bss_decoder = make_uniq(block->ptr, block->len, GetValueWidth(reader.Schema())); block->inc(block->len); } 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 5b4028a59..4dc20134e 100644 --- a/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp @@ -115,12 +115,13 @@ void DeltaByteArrayDecoder::InitializePage() { output += sizeof(uint32_t); } - memcpy(output, prev_value.data(), prefix_len); block.available(suffix_len); - memcpy(output + prefix_len, block.ptr, suffix_len); + if (value_len > 0) { + memcpy(output, prev_value.data(), prefix_len); + memcpy(output + prefix_len, block.ptr, suffix_len); + memcpy(prev_value.data(), output, value_len); + } block.inc(suffix_len); - - memcpy(prev_value.data(), output, value_len); prev_len = value_len; output += value_len; } diff --git a/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp b/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp index c22436765..4a985408c 100644 --- a/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp @@ -125,6 +125,7 @@ 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); diff --git a/src/duckdb/extension/parquet/include/column_reader.hpp b/src/duckdb/extension/parquet/include/column_reader.hpp index 9e701d5b0..66f5564ba 100644 --- a/src/duckdb/extension/parquet/include/column_reader.hpp +++ b/src/duckdb/extension/parquet/include/column_reader.hpp @@ -386,7 +386,7 @@ class ColumnReader { virtual void ResetPage(); private: - void AllocateBlock(idx_t size); + void AllocateBlock(idx_t payload_size); void PrepareRead(optional_ptr filter, optional_ptr filter_state, idx_t rows_to_skip = 0); void PreparePage(PageHeader &page_hdr); diff --git a/src/duckdb/extension/parquet/include/column_writer.hpp b/src/duckdb/extension/parquet/include/column_writer.hpp index 61755d564..d2d88a058 100644 --- a/src/duckdb/extension/parquet/include/column_writer.hpp +++ b/src/duckdb/extension/parquet/include/column_writer.hpp @@ -177,6 +177,10 @@ class ColumnWriter { virtual bool TryExportPreparedShreddingType(ShreddingType &result) const; + virtual bool SupportsBloomFilterFallback() const { + return false; + } + virtual idx_t FinalizeSchema(duckdb_parquet::SchemaElementList &schemas) = 0; //! Create the column writer for a specific type recursively @@ -204,6 +208,11 @@ class ColumnWriter { throw NotImplementedException("Writer does not need analysis"); } + //! Whether Analyze and Write accept constant and dictionary vectors as the top-level column input + virtual bool HandlesCompactVectors() const { + return false; + } + virtual void Prepare(ColumnWriterState &state, ColumnWriterState *parent, Vector &vector, idx_t count, bool vector_can_span_multiple_pages) = 0; @@ -241,6 +250,7 @@ class ColumnWriter { ParquetColumnSchema column_schema; vector schema_path; bool can_have_nulls; + bool bloom_filter_fallback = false; protected: vector> child_writers; diff --git a/src/duckdb/extension/parquet/include/decode_utils.hpp b/src/duckdb/extension/parquet/include/decode_utils.hpp index b85990a11..aa59f7228 100644 --- a/src/duckdb/extension/parquet/include/decode_utils.hpp +++ b/src/duckdb/extension/parquet/include/decode_utils.hpp @@ -42,7 +42,8 @@ class ParquetDecodeUtils { width, sizeof(T) * BITPACK_DLEN); } const auto mask = BITPACK_MASKS[width]; - src.available(count * width / BITPACK_DLEN); // check if buffer has enough space available once + // check once that every byte touched from the current bit position is available + 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; @@ -66,7 +67,8 @@ class ParquetDecodeUtils { static void Skip(ByteBuffer &src, bitpacking_width_t &bitpack_pos, idx_t count, const bitpacking_width_t width) { CheckWidth(width); - src.available(count * width / BITPACK_DLEN); // check if buffer has enough space available once + // check once that every byte touched from the current bit position is available + 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; diff --git a/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp b/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp index 4b6b69fe7..fa6c3d756 100644 --- a/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp +++ b/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp @@ -9,7 +9,6 @@ #pragma once #include "column_reader.hpp" -#include "reader/templated_column_reader.hpp" namespace duckdb { @@ -31,26 +30,30 @@ class ParquetDecimalUtils { auto byte = *(pointer + (size - i - 1)); res_ptr[i] = positive ? byte : byte ^ 0xFF; } + bool invalid = false; // Verify that there are only 0s here - if (size > sizeof(PHYSICAL_TYPE)) { - for (idx_t i = sizeof(PHYSICAL_TYPE); i < size; i++) { - auto byte = *(pointer + (size - i - 1)); - if (!positive) { - byte ^= 0xFF; - } - if (byte != 0) { - throw InvalidInputException("Invalid decimal encoding in Parquet file"); - } + for (idx_t i = sizeof(PHYSICAL_TYPE); i < size; i++) { + auto byte = *(pointer + (size - i - 1)); + if (!positive) { + byte ^= 0xFF; } + invalid |= byte != 0; + } + invalid |= res < 0; + if (invalid) { + ThrowInvalidDecimalEncoding(); } if (!positive) { - res += 1; - return -res; + // Negate before subtracting one to keep the minimum signed value representable. + return -res - 1; } return res; } static unique_ptr CreateReader(const ParquetReader &reader, const ParquetColumnSchema &schema); + +private: + [[noreturn]] static void ThrowInvalidDecimalEncoding(); }; template <> diff --git a/src/duckdb/extension/parquet/include/parquet_geometry.hpp b/src/duckdb/extension/parquet/include/parquet_geometry.hpp index ca770cc54..4c2953eaf 100644 --- a/src/duckdb/extension/parquet/include/parquet_geometry.hpp +++ b/src/duckdb/extension/parquet/include/parquet_geometry.hpp @@ -35,6 +35,7 @@ struct ParquetColumnSchema; class ParquetReader; class ColumnReader; class ClientContext; +class Context; struct GeometryColumnReader { static unique_ptr Create(const ParquetReader &reader, const ParquetColumnSchema &schema, @@ -112,7 +113,7 @@ class GeoParquetFileMetadata { bool IsGeometryColumn(const string &column_name) const; - static bool IsGeoParquetConversionEnabled(const ClientContext &context); + static bool IsGeoParquetConversionEnabled(const Context &context); private: mutex write_lock; diff --git a/src/duckdb/extension/parquet/include/parquet_page_index.hpp b/src/duckdb/extension/parquet/include/parquet_page_index.hpp index f51b70fd9..a836f5447 100644 --- a/src/duckdb/extension/parquet/include/parquet_page_index.hpp +++ b/src/duckdb/extension/parquet/include/parquet_page_index.hpp @@ -27,6 +27,7 @@ class TProtocol; namespace duckdb { class TableFilter; struct ParquetColumnSchema; +struct ParquetOptions; //! A range of rows [begin, end) of a row group that may still contain matching rows struct ParquetPageRowRange { @@ -74,7 +75,8 @@ struct ParquetPageIndexUtils { idx_t row_group_num_rows); //! Evaluates the filter against the bounds of every page: result[page] is false when the page cannot match static void FilterPages(const ParquetColumnSchema &schema, const duckdb_parquet::ColumnIndex &column_index, - const TableFilter &filter, bool can_have_nan, vector &result); + const TableFilter &filter, const ParquetOptions &parquet_options, bool can_have_nan, + vector &result); //! The rows of the pages that may match, as sorted non-overlapping ranges static vector PagesToRowRanges(const duckdb_parquet::OffsetIndex &offset_index, const vector &page_may_match, idx_t row_group_num_rows); diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index 92dd7d8ab..1eb57608e 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -96,6 +96,7 @@ struct CryptoMetaData; struct GlobalTableFunctionState; struct LocalTableFunctionState; struct PartitionStatistics; +struct ReadHead; struct TableFilterState; struct ParquetReaderPrefetchConfig { @@ -322,6 +323,12 @@ struct ParquetOptions { StringColumnReader::Utf8ValidationOption utf8_validation_option = StringColumnReader::Utf8ValidationOption::STRICT_UTF8; ParquetInt96AsOption int96_as = ParquetInt96AsOption::TIMESTAMP; + + //! Whether invalid UTF-8 in a VARCHAR column (not JSON) is changed as it is read, so that the values no longer lie + //! within the statistics and bloom filters of the stored bytes + bool RepairsInvalidUTF8() const { + return utf8_validation_option != StringColumnReader::Utf8ValidationOption::STRICT_UTF8; + } }; struct ParquetOptionsSerialization { @@ -495,7 +502,9 @@ class ParquetReader : public BaseFileReader { uint64_t GetGroupSpan(ParquetReaderScanState &state); FilterPropagateResult CheckRowGroupFilterStatistics(ClientContext &context, ParquetReaderScanState &state, ColumnReader &column_reader, const TableFilter &filter); - bool DynamicFiltersExcludeRowGroup(ClientContext &context, ParquetReaderScanState &state); + FilterPropagateResult CheckRowGroupFilterStatistics(ClientContext &context, idx_t group_index, + ColumnReader &column_reader, const TableFilter &filter); + bool FiltersExcludeRowGroup(ClientContext &context, ParquetReaderScanState &state, bool dynamic_filters_only); void PrepareRowGroupBuffer(ClientContext &context, ParquetReaderScanState &state, idx_t out_col_idx); //! Reads the page index of the row group and works out which rows may match the filters; a page index that //! cannot be read or evaluated is ignored @@ -504,6 +513,13 @@ class ParquetReader : public BaseFileReader { //! Serves the page index of the whole file from one buffer that is read once per reader and shared by every row //! group and thread, when the index fits the transport's accepted column gap; returns false when it does not bool TryAttachPageIndexBuffer(ThriftFileTransport &transport) const; + struct BloomFilterReadPlan; + BloomFilterReadPlan PlanBloomFilterReads(ClientContext &context, ThriftFileTransport &transport, + ColumnReader &column_reader, const TableFilter &filter, bool nested_filter, + idx_t column_chunk_idx); + bool TryAttachBloomFilterReadHead(ClientContext &context, ParquetReaderScanState &state, + ColumnReader &column_reader, const TableFilter &filter, bool nested_filter, + idx_t column_chunk_idx); //! Moves the scan to the next rows of the row group that may match according to the page index, skipping the //! rows in between in every column reader; returns the number of rows to scan next (0 if none are left) idx_t SkipToPageIndexRows(ParquetReaderScanState &state); @@ -560,6 +576,9 @@ class ParquetReader : public BaseFileReader { mutable mutex page_index_buffer_lock; mutable AllocatedData page_index_buffer; mutable bool page_index_buffer_loaded = false; + mutex bloom_filter_read_heads_lock; + //! Per column, unclaimed row groups hold their shared read heads. Plans use the first gap estimate. + unordered_map>> bloom_filter_read_heads; //! Scan handle shared by all scan states of this reader mutable shared_ptr shared_scan_handle; mutable annotated_mutex variant_stats_lock; diff --git a/src/duckdb/extension/parquet/include/parquet_statistics.hpp b/src/duckdb/extension/parquet/include/parquet_statistics.hpp index 974fd0929..adcaa0ea7 100644 --- a/src/duckdb/extension/parquet/include/parquet_statistics.hpp +++ b/src/duckdb/extension/parquet/include/parquet_statistics.hpp @@ -20,6 +20,9 @@ #include "duckdb/common/types/value.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector.hpp" +#include "duckdb/common/mutex.hpp" + +#include namespace duckdb_apache { namespace thrift { @@ -46,6 +49,7 @@ using duckdb_parquet::SchemaElement; struct LogicalType; struct ParquetColumnSchema; +struct ParquetOptions; class ResizeableBuffer; enum class ParquetIntervalBloomFilterVersion : uint8_t { NONE, NORMALIZED_V1 }; @@ -58,12 +62,13 @@ struct ParquetStatisticsUtils { static unique_ptr TransformColumnStatistics(const ParquetColumnSchema &reader, const duckdb_parquet::ColumnChunkList &columns, - bool can_have_nan); + const ParquetOptions &parquet_options); + //! can_have_nan is not taken from the options, as page statistics allow NaN whatever the option says static unique_ptr TransformParquetStatistics(const LogicalType &type, const ParquetColumnSchema &schema, - const duckdb_parquet::Statistics &parquet_stats, bool can_have_nan, - optional_ptr column_chunk = nullptr); + const duckdb_parquet::Statistics &parquet_stats, const ParquetOptions &parquet_options, + bool can_have_nan, optional_ptr column_chunk = nullptr); //! Whether the column can contain NaN values - uses nan_count if present, otherwise the can_have_nan option static bool CanHaveNaN(const duckdb_parquet::Statistics &parquet_stats, bool can_have_nan); @@ -77,6 +82,7 @@ struct ParquetStatisticsUtils { GetBloomFilterHashStrategy(const ParquetColumnSchema &schema, ParquetIntervalBloomFilterVersion interval_bloom_filter_version); + static bool HasBloomFilterConstants(const TableFilter &filter, ParquetBloomFilterHashStrategy hash_strategy); static bool BloomFilterExcludes(const TableFilter &filter, const duckdb_parquet::ColumnMetaData &column_meta_data, duckdb_apache::thrift::protocol::TProtocol &file_proto, Allocator &allocator, const ParquetColumnSchema &schema, ParquetBloomFilterHashStrategy hash_strategy); @@ -89,21 +95,50 @@ struct ParquetStatisticsUtils { const std::string &stats); }; +class ParquetBloomFilterMemory { +public: + static constexpr idx_t DEFAULT_LIMIT = 64ULL * 1024 * 1024; + + ParquetBloomFilterMemory(idx_t limit_p, std::function make_room_p) + : limit(limit_p), make_room(std::move(make_room_p)) { + } + //! When the budget is exhausted, calls make_room once to free buffered filters and retries + bool TryReserve(idx_t bytes); + void Release(idx_t bytes); + +private: + bool TryReserveInternal(idx_t bytes); + +private: + mutex lock; + idx_t used = 0; + idx_t limit; + std::function make_room; +}; + class ParquetBloomFilter { static constexpr const idx_t DEFAULT_BLOCK_COUNT = 32; // 4k filter public: - ParquetBloomFilter(idx_t num_entries, double bloom_filter_false_positive_ratio); ParquetBloomFilter(unique_ptr data_p); + ~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); void FilterInsert(uint64_t x); bool FilterCheck(uint64_t x); - void Shrink(idx_t new_block_count); + void Shrink(Allocator &allocator, idx_t new_block_count); + void FoldToTarget(Allocator &allocator, double target); + void ReleaseReservation(); double OneRatio(); ResizeableBuffer *Get(); private: unique_ptr data; idx_t block_count; + shared_ptr memory; + idx_t reserved_bytes = 0; }; // see https://github.com/apache/parquet-format/blob/master/BloomFilter.md diff --git a/src/duckdb/extension/parquet/include/parquet_writer.hpp b/src/duckdb/extension/parquet/include/parquet_writer.hpp index 7a72a5b0b..1cf2e95cf 100644 --- a/src/duckdb/extension/parquet/include/parquet_writer.hpp +++ b/src/duckdb/extension/parquet/include/parquet_writer.hpp @@ -199,6 +199,8 @@ struct ParquetWriterOptions { bool write_page_index; //! Maximum ratio of false-positives to allow in the written bloom filter double bloom_filter_false_positive_ratio; + //! Per-file budget for fallback filters, including concurrent construction and scratch space + idx_t bloom_filter_fallback_max_bytes = ParquetBloomFilterMemory::DEFAULT_LIMIT; //! For the given 'codec', the compression level to use int64_t compression_level; //! Parquet version to use, higher versions enable more advanced compression modes @@ -272,6 +274,9 @@ class ParquetWriter { double BloomFilterFalsePositiveRatio() const { return options.bloom_filter_false_positive_ratio; } + shared_ptr BloomFilterFallbackMemory() const { + return bloom_filter_fallback_memory; + } int64_t CompressionLevel() const { return options.compression_level; } @@ -322,6 +327,7 @@ class ParquetWriter { private: void GatherWrittenStatistics(); + void FlushBloomFilters(); void InitializeColumnOrders(idx_t unique_columns); void InitializeStatsUnifiers(); void InitializeSchemaFromPreparedRowGroup(const PreparedRowGroup &prepared); @@ -350,6 +356,7 @@ class ParquetWriter { unique_ptr geoparquet_data; vector bloom_filters; + shared_ptr bloom_filter_fallback_memory; vector page_indexes; optional_ptr written_stats; diff --git a/src/duckdb/extension/parquet/include/thrift_tools.hpp b/src/duckdb/extension/parquet/include/thrift_tools.hpp index e901ef324..4412248a6 100644 --- a/src/duckdb/extension/parquet/include/thrift_tools.hpp +++ b/src/duckdb/extension/parquet/include/thrift_tools.hpp @@ -16,6 +16,7 @@ #include "duckdb/storage/external_file_cache/file_buffer_handle_group.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/allocator.hpp" +#include "duckdb/common/mutex.hpp" namespace duckdb { @@ -31,6 +32,7 @@ struct ReadHead { AllocatedData local_buffer; const_data_ptr_t buffer_ptr = nullptr; bool data_isset = false; + mutex fetch_lock; // Sub-ranges whose smaller cached blocks are re-fetched with the gaps around them (see CachingFileHandle::Read) vector> absorb_ranges; @@ -39,18 +41,22 @@ struct ReadHead { } // Materialize [buffer_ptr], should call before access. - // TODO(hjiang): Currently it's only used for `Prefetch` operation, should be able to save one copy. void Materialize(Allocator &allocator) { if (handle_group.GetHandles().size() == 1) { buffer_ptr = handle_group.Ptr(); } else { local_buffer = allocator.Allocate(size); handle_group.CopyTo(local_buffer.get(), size); + handle_group = FileBufferHandleGroup(); buffer_ptr = local_buffer.get(); } } void Fetch(CachingFileHandle &file_handle) { + lock_guard guard(fetch_lock); + if (data_isset) { + return; + } if (GetEnd() > file_handle.GetFileSize()) { throw std::runtime_error("Prefetch registered requested for bytes outside file"); } @@ -236,6 +242,12 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra ra_buffer.AddFilledReadHead(pos, len, data); } + // Attach an immutable, fetched head without registering it for merging. + void AddFetchedReadHead(shared_ptr read_head) { + D_ASSERT(read_head->data_isset); + ra_buffer.read_heads.insert(ra_buffer.read_heads.begin(), std::move(read_head)); + } + // Prefetch a single buffer void Prefetch(idx_t pos, uint64_t len) { RegisterPrefetch(pos, len, false); @@ -280,8 +292,8 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra return location; } - optional_ptr GetReadHead(idx_t pos) { - return ra_buffer.GetReadHead(pos); + optional_ptr GetReadHead(idx_t pos, idx_t len = 1) { + return ra_buffer.GetReadHead(pos, len); } vector> &GetReadHeads() { diff --git a/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp b/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp index 884e7b40b..6e732fe38 100644 --- a/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp +++ b/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp @@ -32,6 +32,7 @@ class EnumColumnWriter : public PrimitiveColumnWriter { EnumColumnWriter(ParquetWriter &writer, ParquetColumnSchema &&column_schema, vector schema_path_p); ~EnumColumnWriter() override = default; + unique_ptr InitializeWriteState(duckdb_parquet::RowGroup &row_group) override; unique_ptr InitializeStatsState() override; void WriteVector(WriteStream &temp_writer, ColumnWriterStatistics *stats_p, ColumnWriterPageState *page_state_p, @@ -57,8 +58,6 @@ class EnumColumnWriter : public PrimitiveColumnWriter { EnumWriterPageState &page_state); uint32_t bit_width; - //! Tracks which enum values have actually been written. - vector seen_enum; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp b/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp index f4bd70fe2..a4f6b1a74 100644 --- a/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp +++ b/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp @@ -12,12 +12,65 @@ #include "parquet_interval.hpp" #include "parquet_timestamp.hpp" #include "zstd/common/xxhash.hpp" +#include "duckdb/common/bswap.hpp" #include "duckdb/common/types/time.hpp" #include "duckdb/common/types/uhugeint.hpp" #include "duckdb/common/types/uuid.hpp" namespace duckdb { +struct ParquetXXHash64Constants { + static constexpr uint64_t PRIME64_1 = 0x9E3779B185EBCA87ULL; + static constexpr uint64_t PRIME64_2 = 0xC2B2AE3D27D4EB4FULL; + static constexpr uint64_t PRIME64_3 = 0x165667B19E3779F9ULL; + static constexpr uint64_t PRIME64_4 = 0x85EBCA77C2B2AE63ULL; + static constexpr uint64_t PRIME64_5 = 0x27D4EB2F165667C5ULL; + + static uint64_t RotateLeft(uint64_t x, uint8_t r) { + return (x << r) | (x >> (64 - r)); + } + + static uint64_t Avalanche(uint64_t h) { + h ^= h >> 33; + h *= PRIME64_2; + h ^= h >> 29; + h *= PRIME64_3; + h ^= h >> 32; + return h; + } +}; + +template +struct ParquetFixedWidthXXHash64 { + template + static uint64_t Hash(const T &value) { + return duckdb_zstd::XXH64(&value, sizeof(value), 0); + } +}; + +template <> +struct ParquetFixedWidthXXHash64 : public ParquetXXHash64Constants { + template + static uint64_t Hash(const T &value) { + uint32_t bits; + memcpy(&bits, &value, sizeof(bits)); + auto h = (PRIME64_5 + sizeof(bits)) ^ (uint64_t(BSwapIfBE(bits)) * PRIME64_1); + return Avalanche(RotateLeft(h, 23) * PRIME64_2 + PRIME64_3); + } +}; + +template <> +struct ParquetFixedWidthXXHash64 : public ParquetXXHash64Constants { + template + static uint64_t Hash(const T &value) { + uint64_t bits; + memcpy(&bits, &value, sizeof(bits)); + auto lane = RotateLeft(BSwapIfBE(bits) * PRIME64_2, 31) * PRIME64_1; + auto h = (PRIME64_5 + sizeof(bits)) ^ lane; + return Avalanche(RotateLeft(h, 27) * PRIME64_1 + PRIME64_4); + } +}; + struct BaseParquetOperator { template static void WriteToStream(const TGT &input, WriteStream &ser) { @@ -31,7 +84,7 @@ struct BaseParquetOperator { template static uint64_t XXHash64(const TGT &target_value) { - return duckdb_zstd::XXH64(&target_value, sizeof(target_value), 0); + return ParquetFixedWidthXXHash64::template Hash(target_value); } template @@ -44,6 +97,11 @@ struct BaseParquetOperator { return nullopt; } + template + static bool CanSeedBloomFilter(const TGT &) { + return true; + } + template static unique_ptr InitializeStats() { return nullptr; @@ -87,6 +145,12 @@ struct FloatingPointOperator : public BaseParquetOperator { return TGT(input); } + //! The dictionary merges NaNs with different payloads, which hash differently + template + static bool CanSeedBloomFilter(const TGT &target_value) { + return !Value::IsNan(target_value); + } + template static unique_ptr InitializeStats() { return make_uniq>(); @@ -261,6 +325,13 @@ struct ParquetIntervalOperator : public BaseParquetOperator { } TGT result; ParquetIntervalUtils::Encode(input, result.bytes); + // the reader loads the days as a signed 32 bit integer + const auto days = Load(result.bytes + sizeof(uint32_t)); + if (days > UnsafeNumericCast(NumericLimits::Maximum())) { + throw OutOfRangeException( + "Cannot write the interval %s to Parquet, as its days plus the whole days of its time exceed %d", + Interval::ToString(input), NumericLimits::Maximum()); + } return result; } diff --git a/src/duckdb/extension/parquet/include/writer/primitive_column_writer.hpp b/src/duckdb/extension/parquet/include/writer/primitive_column_writer.hpp index eab59c0a7..8fb3180f4 100644 --- a/src/duckdb/extension/parquet/include/writer/primitive_column_writer.hpp +++ b/src/duckdb/extension/parquet/include/writer/primitive_column_writer.hpp @@ -101,6 +101,8 @@ class PrimitiveColumnWriter : public ColumnWriter { //! Dictionary pages must be below 2GB. Unlike data pages, there's only one dictionary page. //! For this reason we go with a much higher, but still a conservative upper bound of 1GB; static constexpr const idx_t MAX_UNCOMPRESSED_DICT_PAGE_SIZE = 1073741824ULL; + //! Fallback filters are dropped unless the compressed column chunk is at least this many times larger + static constexpr const idx_t MIN_COMPRESSED_TO_FILTER_RATIO = 2; public: unique_ptr InitializeWriteState(duckdb_parquet::RowGroup &row_group) override; diff --git a/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp b/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp index 54a77c46a..e9845bd81 100644 --- a/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp +++ b/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp @@ -16,27 +16,131 @@ #include "parquet_rle_bp_decoder.hpp" #include "parquet_rle_bp_encoder.hpp" #include "duckdb/common/primitive_dictionary.hpp" +#include "duckdb/common/operator/comparison_operators.hpp" +#include "duckdb/common/types/double_na_equal.hpp" +#include "duckdb/common/vector/dictionary_vector.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" namespace duckdb { -template -static void TemplatedWritePlain(Vector &col, ColumnWriterStatistics *stats, const idx_t chunk_start, - const idx_t chunk_end, const ValidityMask &mask, WriteStream &ser) { - static constexpr bool COPY_DIRECTLY_FROM_VECTOR = ALL_VALID && std::is_same::value && +//! Rows of a flat column +template +class FlatColumnInput { +public: + explicit FlatColumnInput(const Vector &vector) + : data(FlatVector::GetData(vector)), validity(FlatVector::Validity(vector)) { + } + + static constexpr bool CONTIGUOUS = true; + static constexpr bool HAS_ENTRIES = false; + + bool CannotHaveNull() const { + return validity.CannotHaveNull(); + } + bool RowIsValid(idx_t row) const { + return validity.RowIsValid(row); + } + const SRC &Value(idx_t row) const { + return data[row]; + } + const SRC *Data() const { + return data; + } + idx_t Entry(idx_t row) const { + return row; + } + +private: + const SRC *data; + const ValidityMask &validity; +}; + +//! Rows of a constant vector, all reading its single entry +template +class ConstantColumnInput { +public: + explicit ConstantColumnInput(const Vector &vector) + : value(ConstantVector::GetData(vector)), valid(!ConstantVector::IsNull(vector)) { + } + + static constexpr bool CONTIGUOUS = false; + static constexpr bool HAS_ENTRIES = true; + + bool CannotHaveNull() const { + return valid; + } + bool RowIsValid(idx_t row) const { + return valid; + } + const SRC &Value(idx_t row) const { + return *value; + } + const SRC *Data() const { + return nullptr; + } + idx_t Entry(idx_t row) const { + return 0; + } + idx_t EntryCount() const { + return 1; + } + +private: + const SRC *value; + bool valid; +}; + +//! Rows of a dictionary vector, each reading the dictionary entry its selection names +template +class DictionaryColumnInput { +public: + DictionaryColumnInput(const Vector &vector, const VectorIterator &entries) + : entries(entries), sel(DictionaryVector::SelVector(vector)) { + } + + static constexpr bool CONTIGUOUS = false; + static constexpr bool HAS_ENTRIES = true; + + bool CannotHaveNull() const { + return !entries.CanHaveNull(); + } + bool RowIsValid(idx_t row) const { + return entries[Entry(row)].IsValid(); + } + const SRC &Value(idx_t row) const { + return entries[Entry(row)].GetValueUnsafe(); + } + const SRC *Data() const { + return nullptr; + } + idx_t Entry(idx_t row) const { + return sel.get_index(row); + } + idx_t EntryCount() const { + return entries.size(); + } + +private: + const VectorIterator &entries; + const SelectionVector &sel; +}; + +template +static void TemplatedWritePlain(INPUT input, ColumnWriterStatistics *stats, const idx_t chunk_start, + const idx_t chunk_end, WriteStream &ser) { + static constexpr bool COPY_DIRECTLY_FROM_VECTOR = ALL_VALID && INPUT::CONTIGUOUS && std::is_same::value && std::is_arithmetic::value && std::is_same::value; - const auto *const ptr = FlatVector::GetData(col); - TGT local_write[STANDARD_VECTOR_SIZE]; idx_t local_write_count = 0; for (idx_t r = chunk_start; r < chunk_end; r++) { - if (!ALL_VALID && !mask.RowIsValid(r)) { + if (!ALL_VALID && !input.RowIsValid(r)) { continue; } - TGT target_value = OP::template Operation(ptr[r]); + TGT target_value = OP::template Operation(input.Value(r)); OP::template HandleStats(stats, target_value); if (COPY_DIRECTLY_FROM_VECTOR) { @@ -55,7 +159,7 @@ static void TemplatedWritePlain(Vector &col, ColumnWriterStatistics *stats, cons } if (COPY_DIRECTLY_FROM_VECTOR) { - ser.WriteData(const_data_ptr_cast(&ptr[chunk_start]), (chunk_end - chunk_start) * sizeof(TGT)); + ser.WriteData(const_data_ptr_cast(&input.Data()[chunk_start]), (chunk_end - chunk_start) * sizeof(TGT)); return; } @@ -65,6 +169,86 @@ static void TemplatedWritePlain(Vector &col, ColumnWriterStatistics *stats, cons // Else we already wrote to stream } +template +struct SortednessKey { + static constexpr bool TRACKED = std::is_integral::value || std::is_same::value || + std::is_same::value || std::is_same::value; + static const T &Get(const T &value) { + return value; + } +}; + +template <> +struct SortednessKey { + static constexpr bool TRACKED = true; + static const float &Get(const float_na_equal &value) { + return value.val; + } +}; + +template <> +struct SortednessKey { + static constexpr bool TRACKED = true; + static const double &Get(const double_na_equal &value) { + return value.val; + } +}; + +template ::TRACKED> +class SortednessTracker { +public: + void Update(const T &) { + } + void Persist() { + } + bool IsSorted() const { + return false; + } +}; + +template +class SortednessTracker { +public: + void Update(const T &value) { + if (count > 0) { + const auto &left = SortednessKey::Get(previous); + const auto &right = SortednessKey::Get(value); + ascending = ascending && !GreaterThan::Operation(left, right); + descending = descending && !GreaterThan::Operation(right, left); + } + previous = value; + count++; + } + //! Copies the last value out of the vector it points into, which may be freed before the next one + void Persist() { + if (count > 0) { + PersistValue(previous, owned_previous); + } + } + bool IsSorted() const { + return ascending || descending; + } + +private: + template + static void PersistValue(V &, string &) { + } + static void PersistValue(string_t &value, string &owned) { + if (value.IsInlined() || value.GetData() == owned.data()) { + return; + } + owned.assign(value.GetData(), value.GetSize()); + value = string_t(owned.data(), UnsafeNumericCast(owned.size())); + } + +private: + T previous; + string owned_previous; + idx_t count = 0; + bool ascending = true; + bool descending = true; +}; + template class StandardColumnWriterState : public PrimitiveColumnWriterState { public: @@ -79,9 +263,13 @@ class StandardColumnWriterState : public PrimitiveColumnWriterState { ~StandardColumnWriterState() override = default; uint32_t key_bit_width = 0; + idx_t dictionary_values = 0; PrimitiveDictionary dictionary; duckdb_parquet::Encoding::type encoding; + SortednessTracker sortedness; + //! Scratch for the analyze entry shortcut, reused across the row group's vectors + vector inserted_entries; }; template @@ -111,6 +299,8 @@ class StandardWriterPageState : public ColumnWriterPageState { bool dict_written_value; uint32_t dict_bit_width; RleBpEncoder dict_encoder; + //! Scratch for the write entry shortcut, reused across the page's vectors + vector entry_indexes; }; template @@ -124,6 +314,10 @@ class StandardColumnWriter : public PrimitiveColumnWriter { //! Dictionary encoding normally updates the statistics once per distinct dictionary value. //! Floating point statistics include nan_count, which counts every NaN value written, so they are updated per row. static constexpr bool STATS_PER_OCCURRENCE = std::is_same::value; + //! Values the dictionary must have seen before they are used to skip a fallback filter + static constexpr idx_t MIN_PREFIX_VALUES = 1024; + //! Fallback filters are skipped unless the column chunk is estimated to be this many times larger + static constexpr idx_t MIN_COLUMN_TO_FILTER_RATIO = 4; public: unique_ptr InitializeWriteState(duckdb_parquet::RowGroup &row_group) override { @@ -195,38 +389,30 @@ class StandardColumnWriter : public PrimitiveColumnWriter { return true; } + bool HandlesCompactVectors() const override { + return true; + } + void Analyze(ColumnWriterState &state_p, ColumnWriterState *parent, Vector &vector, idx_t count) override { auto &state = state_p.Cast>(); - - auto data_ptr = FlatVector::GetData(vector); - idx_t vector_index = 0; - - const bool check_parent_empty = parent && !parent->is_empty.empty(); - const idx_t parent_index = state.definition_levels.size(); - D_ASSERT(!check_parent_empty || parent_index < parent->is_empty.size()); - - const idx_t vcount = - check_parent_empty ? parent->definition_levels.size() - state.definition_levels.size() : count; - - const auto &validity = FlatVector::Validity(vector); - - if (!check_parent_empty && validity.CannotHaveNull()) { - // Fast path - for (; vector_index < vcount; vector_index++) { - const auto &src_value = data_ptr[vector_index]; - state.dictionary.template Insert(src_value); - } - } else { - for (idx_t i = 0; i < vcount; i++) { - if (check_parent_empty && parent->is_empty[parent_index + i]) { - continue; - } - if (validity.RowIsValid(vector_index)) { - const auto &src_value = data_ptr[vector_index]; - state.dictionary.template Insert(src_value); - } - vector_index++; + switch (vector.GetVectorType()) { + case VectorType::FLAT_VECTOR: + AnalyzeInput(state, parent, FlatColumnInput(vector), count); + break; + case VectorType::CONSTANT_VECTOR: + AnalyzeInput(state, parent, ConstantColumnInput(vector), count); + break; + case VectorType::DICTIONARY_VECTOR: + if (!DictionaryIsLargerThanRows(vector)) { + auto entries = DictionaryVector::Child(vector).Values(); + AnalyzeInput(state, parent, DictionaryColumnInput(vector, entries), count); + break; } + DUCKDB_EXPLICIT_FALLTHROUGH; + default: + vector.Flatten(); + AnalyzeInput(state, parent, FlatColumnInput(vector), count); + break; } } @@ -260,12 +446,23 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } else { state.key_bit_width = RleBpDecoder::ComputeBitWidthFromValueCount(state.dictionary.GetSize()); } + if (state.bloom_filter && state.sortedness.IsSorted()) { + state.bloom_filter.reset(); + } + if (state.bloom_filter) { + state.bloom_filter->FoldToTarget(BufferAllocator::Get(writer.GetContext()), + writer.BloomFilterFalsePositiveRatio()); + } } unique_ptr InitializeStatsState() override { return OP::template InitializeStats(); } + bool SupportsBloomFilterFallback() const override { + return !std::is_same::value && !std::is_same::value; + } + bool HasDictionary(PrimitiveColumnWriterState &state_p) override { auto &state = state_p.Cast>(); return state.encoding == duckdb_parquet::Encoding::RLE_DICTIONARY || @@ -279,11 +476,26 @@ class StandardColumnWriter : public PrimitiveColumnWriter { void WriteVector(WriteStream &temp_writer, ColumnWriterStatistics *stats, ColumnWriterPageState *page_state_p, Vector &input_column, idx_t chunk_start, idx_t chunk_end) override { - const auto &mask = FlatVector::Validity(input_column); - if (mask.CannotHaveNull()) { - WriteVectorInternal(temp_writer, stats, page_state_p, input_column, chunk_start, chunk_end); - } else { - WriteVectorInternal(temp_writer, stats, page_state_p, input_column, chunk_start, chunk_end); + switch (input_column.GetVectorType()) { + case VectorType::FLAT_VECTOR: + WriteInput(temp_writer, stats, page_state_p, FlatColumnInput(input_column), chunk_start, chunk_end); + break; + case VectorType::CONSTANT_VECTOR: + WriteInput(temp_writer, stats, page_state_p, ConstantColumnInput(input_column), chunk_start, + chunk_end); + break; + case VectorType::DICTIONARY_VECTOR: + if (!DictionaryIsLargerThanRows(input_column)) { + auto entries = DictionaryVector::Child(input_column).Values(); + WriteInput(temp_writer, stats, page_state_p, DictionaryColumnInput(input_column, entries), + chunk_start, chunk_end); + break; + } + DUCKDB_EXPLICIT_FALLTHROUGH; + default: + input_column.Flatten(); + WriteInput(temp_writer, stats, page_state_p, FlatColumnInput(input_column), chunk_start, chunk_end); + break; } } @@ -296,7 +508,8 @@ class StandardColumnWriter : public PrimitiveColumnWriter { auto bloom_filter_entries = state.dictionary.GetSize() * OP::template BloomFilterEntriesPerValue(); state.bloom_filter = - make_uniq(bloom_filter_entries, writer.BloomFilterFalsePositiveRatio()); + ParquetBloomFilter::Create(BufferAllocator::Get(writer.GetContext()), bloom_filter_entries, + writer.BloomFilterFalsePositiveRatio()); } // the chunk statistics are the merged page statistics when the page index is written @@ -308,12 +521,7 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } if (state.bloom_filter) { // update the bloom filter - auto hash = OP::template XXHash64(tgt_value); - state.bloom_filter->FilterInsert(hash); - auto extra_hash = OP::template GetExtraBloomFilterHash(src_value, tgt_value); - if (extra_hash) { - state.bloom_filter->FilterInsert(*extra_hash); - } + InsertBloomFilterValue(*state.bloom_filter, src_value, tgt_value); } }); @@ -335,15 +543,270 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } private: - template + static void InsertBloomFilterValue(ParquetBloomFilter &bloom_filter, const SRC &src_value, const TGT &tgt_value) { + bloom_filter.FilterInsert(OP::template XXHash64(tgt_value)); + auto extra_hash = OP::template GetExtraBloomFilterHash(src_value, tgt_value); + if (extra_hash) { + bloom_filter.FilterInsert(*extra_hash); + } + } + + bool TracksSortedness(StandardColumnWriterState &state) const { + return bloom_filter_fallback && state.sortedness.IsSorted() && + (!state.dictionary.IsFull() || state.bloom_filter); + } + + //! The distinct count extrapolation behind the fallback filter decision counts every analyzed value + void CountAnalyzedValue(StandardColumnWriterState &state) { + if (!state.dictionary.IsFull()) { + state.dictionary_values++; + } + } + + void InsertAnalyzedValue(StandardColumnWriterState &state, const SRC &src_value) { + if (!state.dictionary.IsFull()) { + state.dictionary.template Insert(src_value); + if (!state.dictionary.IsFull()) { + return; + } + StartBloomFilterFallback(state); + } + if (state.bloom_filter) { + InsertBloomFilterValue(*state.bloom_filter, src_value, OP::template Operation(src_value)); + } + } + + void AnalyzeValue(StandardColumnWriterState &state, const SRC &src_value) { + CountAnalyzedValue(state); + InsertAnalyzedValue(state, src_value); + } + + //! Extrapolates the distinct count, assuming the values seen so far are drawn uniformly from a fixed set + static idx_t EstimateDistinctValues(idx_t seen_distinct, idx_t seen_values, idx_t total_values) { + if (seen_distinct >= seen_values) { + return total_values; + } + const auto distinct = static_cast(seen_distinct); + const auto values = static_cast(seen_values); + auto expected_distinct = [](double population, double draws) { + return -population * std::expm1(-draws / population); + }; + double low = distinct; + double high = distinct; + while (expected_distinct(high, values) < distinct) { + high *= 2; + } + for (idx_t i = 0; i < 64; i++) { + const auto mid = (low + high) / 2; + if (expected_distinct(mid, values) < distinct) { + low = mid; + } else { + high = mid; + } + } + const auto estimate = expected_distinct(high, static_cast(total_values)); + return MinValue(total_values, LossyNumericCast(std::ceil(estimate))); + } + + bool SkipBloomFilterFallback(StandardColumnWriterState &state) const { + if (state.dictionary_values < MIN_PREFIX_VALUES) { + return false; + } + if (state.sortedness.IsSorted()) { + return true; + } + const auto rows = NumericCast(state.row_group.num_rows); + const auto distinct = EstimateDistinctValues(state.dictionary.GetSize() + 1, state.dictionary_values, rows); + const auto filter_size = ParquetBloomFilter::EstimateSize( + distinct * OP::template BloomFilterEntriesPerValue(), writer.BloomFilterFalsePositiveRatio()); + if (!filter_size.IsValid()) { + return true; + } + const auto value_size = + state.dictionary.GetTargetMemoryStream()->GetPosition() / MaxValue(state.dictionary.GetSize(), 1); + return filter_size.GetIndex() * MIN_COLUMN_TO_FILTER_RATIO > value_size * rows; + } + + void StartBloomFilterFallback(StandardColumnWriterState &state) { + if (!bloom_filter_fallback || SkipBloomFilterFallback(state)) { + return; + } + auto bloom_filter = ParquetBloomFilter::TryCreate( + BufferAllocator::Get(writer.GetContext()), + NumericCast(state.row_group.num_rows) * OP::template BloomFilterEntriesPerValue(), + writer.BloomFilterFalsePositiveRatio(), writer.BloomFilterFallbackMemory()); + if (!bloom_filter) { + return; + } + auto &filter = *bloom_filter; + bool seedable = true; + if (OP::template BloomFilterEntriesPerValue() == 1) { + state.dictionary.IterateTargetValues([&](const TGT &tgt_value) { + seedable = seedable && OP::template CanSeedBloomFilter(tgt_value); + filter.FilterInsert(OP::template XXHash64(tgt_value)); + }); + } else { + state.dictionary.IterateValues([&](const SRC &src_value, const TGT &tgt_value) { + seedable = seedable && OP::template CanSeedBloomFilter(tgt_value); + InsertBloomFilterValue(filter, src_value, tgt_value); + }); + } + state.dictionary.Reset(); + if (seedable) { + state.bloom_filter = std::move(bloom_filter); + } + } + + //! A dictionary with more entries than rows (a shared dictionary from storage) is cheaper to read flattened + static bool DictionaryIsLargerThanRows(const Vector &vector) { + return DictionaryVector::Child(vector).size() > vector.size(); + } + + template + void AnalyzeInput(StandardColumnWriterState &state, ColumnWriterState *parent, INPUT input, + idx_t count) { + idx_t vector_index = 0; + + const bool check_parent_empty = parent && !parent->is_empty.empty(); + const idx_t parent_index = state.definition_levels.size(); + D_ASSERT(!check_parent_empty || parent_index < parent->is_empty.size()); + + const idx_t vcount = + check_parent_empty ? parent->definition_levels.size() - state.definition_levels.size() : count; + + // Sortedness tracking needs the values in row order, so it keeps the per-row path + const bool track_sortedness = TracksSortedness(state); + + if (!check_parent_empty && !track_sortedness && InsertReferencedEntries(state, input, vcount)) { + return; + } + if (!check_parent_empty && input.CannotHaveNull()) { + // Fast path + for (idx_t i = 0; track_sortedness && i < vcount && state.sortedness.IsSorted(); i++) { + state.sortedness.Update(input.Value(i)); + } + for (; vector_index < vcount; vector_index++) { + AnalyzeValue(state, input.Value(vector_index)); + } + } else { + for (idx_t i = 0; i < vcount; i++) { + if (check_parent_empty && parent->is_empty[parent_index + i]) { + continue; + } + if (input.RowIsValid(vector_index)) { + if (track_sortedness) { + state.sortedness.Update(input.Value(vector_index)); + } + AnalyzeValue(state, input.Value(vector_index)); + } + vector_index++; + } + } + if (track_sortedness) { + state.sortedness.Persist(); + } + } + + template ::type = 0> + bool InsertReferencedEntries(StandardColumnWriterState &state, INPUT input, idx_t count) { + return false; + } + + //! Insert each referenced entry once, at the row that first references it. Inserting an entry again is a no-op, + //! so this builds the dictionary that inserting every row builds + template ::type = 0> + bool InsertReferencedEntries(StandardColumnWriterState &state, INPUT input, idx_t count) { + const auto entry_count = input.EntryCount(); + if (entry_count > count) { + // a dictionary larger than the rows costs more to resolve per entry than per row + return false; + } + auto &inserted = state.inserted_entries; + inserted.assign(entry_count, false); + for (idx_t row = 0; row < count; row++) { + if (!input.RowIsValid(row)) { + continue; + } + CountAnalyzedValue(state); + const auto entry = input.Entry(row); + if (inserted[entry]) { + continue; + } + inserted[entry] = true; + InsertAnalyzedValue(state, input.Value(row)); + } + return true; + } + + template + void WriteInput(WriteStream &temp_writer, ColumnWriterStatistics *stats, ColumnWriterPageState *page_state_p, + INPUT input, idx_t chunk_start, idx_t chunk_end) { + if (input.CannotHaveNull()) { + WriteVectorInternal(temp_writer, stats, page_state_p, input, chunk_start, chunk_end); + } else { + WriteVectorInternal(temp_writer, stats, page_state_p, input, chunk_start, chunk_end); + } + } + + //! Write the dictionary index of every valid row, resolving each index through the provided resolver + template + void WriteDictionaryRows(WriteStream &temp_writer, ColumnWriterStatistics *stats, + StandardWriterPageState &page_state, INPUT input, idx_t r, idx_t chunk_end, + RESOLVE resolve) { + // the page index needs the bounds of every page, which the dictionary cannot provide + const bool stats_per_occurrence = STATS_PER_OCCURRENCE || writer.WritePageIndex(); + for (; r < chunk_end; r++) { + if (!ALL_VALID && !input.RowIsValid(r)) { + continue; + } + const auto &src_value = input.Value(r); + if (stats_per_occurrence) { + OP::template HandleStats(stats, OP::template Operation(src_value)); + } + page_state.dict_encoder.WriteValue(temp_writer, resolve(r, src_value)); + } + } + + template ::type = 0> + void WriteDictionaryIndexes(WriteStream &temp_writer, ColumnWriterStatistics *stats, + StandardWriterPageState &page_state, INPUT input, idx_t r, + idx_t chunk_end) { + WriteDictionaryRows( + temp_writer, stats, page_state, input, r, chunk_end, + [&](idx_t, const SRC &src_value) { return page_state.dictionary.GetIndex(src_value); }); + } + + //! Look up the dictionary index of each referenced entry once + template ::type = 0> + void WriteDictionaryIndexes(WriteStream &temp_writer, ColumnWriterStatistics *stats, + StandardWriterPageState &page_state, INPUT input, idx_t r, + idx_t chunk_end) { + const auto entry_count = input.EntryCount(); + if (entry_count > chunk_end - r) { + // a dictionary larger than the rows costs more to resolve per entry than per row + WriteDictionaryRows( + temp_writer, stats, page_state, input, r, chunk_end, + [&](idx_t, const SRC &src_value) { return page_state.dictionary.GetIndex(src_value); }); + return; + } + static constexpr uint32_t UNRESOLVED = NumericLimits::Maximum(); + auto &entry_indexes = page_state.entry_indexes; + entry_indexes.assign(entry_count, UNRESOLVED); + WriteDictionaryRows(temp_writer, stats, page_state, input, r, chunk_end, + [&](idx_t row, const SRC &src_value) { + auto &value_index = entry_indexes[input.Entry(row)]; + if (value_index == UNRESOLVED) { + value_index = page_state.dictionary.GetIndex(src_value); + } + return value_index; + }); + } + + template void WriteVectorInternal(WriteStream &temp_writer, ColumnWriterStatistics *stats, - ColumnWriterPageState *page_state_p, Vector &input_column, idx_t chunk_start, - idx_t chunk_end) { + ColumnWriterPageState *page_state_p, INPUT input, idx_t chunk_start, idx_t chunk_end) { auto &page_state = page_state_p->Cast>(); - const auto &mask = FlatVector::Validity(input_column); - const auto *data_ptr = FlatVector::GetData(input_column); - switch (page_state.encoding) { case duckdb_parquet::Encoding::PLAIN_DICTIONARY: // PLAIN_DICTIONARY can be treated the same as RLE_DICTIONARY @@ -352,7 +815,7 @@ class StandardColumnWriter : public PrimitiveColumnWriter { if (!page_state.dict_written_value) { // find first non-null value for (; r < chunk_end; r++) { - if (!mask.RowIsValid(r)) { + if (!input.RowIsValid(r)) { continue; } // write the bit-width as a one-byte entry and initialize writer @@ -363,19 +826,7 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } } - // the page index needs the bounds of every page, which the dictionary cannot provide - const bool stats_per_occurrence = STATS_PER_OCCURRENCE || writer.WritePageIndex(); - for (; r < chunk_end; r++) { - if (!ALL_VALID && !mask.RowIsValid(r)) { - continue; - } - const auto &src_value = data_ptr[r]; - if (stats_per_occurrence) { - OP::template HandleStats(stats, OP::template Operation(src_value)); - } - const auto value_index = page_state.dictionary.GetIndex(src_value); - page_state.dict_encoder.WriteValue(temp_writer, value_index); - } + WriteDictionaryIndexes(temp_writer, stats, page_state, input, r, chunk_end); break; } case duckdb_parquet::Encoding::DELTA_BINARY_PACKED: { @@ -383,10 +834,10 @@ class StandardColumnWriter : public PrimitiveColumnWriter { if (!page_state.dbp_initialized) { // find first non-null value for (; r < chunk_end; r++) { - if (!mask.RowIsValid(r)) { + if (!input.RowIsValid(r)) { continue; } - const TGT target_value = OP::template Operation(data_ptr[r]); + const TGT target_value = OP::template Operation(input.Value(r)); OP::template HandleStats(stats, target_value); page_state.dbp_encoder.BeginWrite(temp_writer, target_value); page_state.dbp_initialized = true; @@ -396,10 +847,10 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } for (; r < chunk_end; r++) { - if (!ALL_VALID && !mask.RowIsValid(r)) { + if (!ALL_VALID && !input.RowIsValid(r)) { continue; } - const TGT target_value = OP::template Operation(data_ptr[r]); + const TGT target_value = OP::template Operation(input.Value(r)); OP::template HandleStats(stats, target_value); page_state.dbp_encoder.WriteValue(temp_writer, target_value); } @@ -410,10 +861,10 @@ class StandardColumnWriter : public PrimitiveColumnWriter { if (!page_state.dlba_initialized) { // find first non-null value for (; r < chunk_end; r++) { - if (!mask.RowIsValid(r)) { + if (!input.RowIsValid(r)) { continue; } - const TGT target_value = OP::template Operation(data_ptr[r]); + const TGT target_value = OP::template Operation(input.Value(r)); OP::template HandleStats(stats, target_value); page_state.dlba_encoder.BeginWrite(BufferAllocator::Get(writer.GetContext()), temp_writer, target_value); @@ -424,10 +875,10 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } for (; r < chunk_end; r++) { - if (!ALL_VALID && !mask.RowIsValid(r)) { + if (!ALL_VALID && !input.RowIsValid(r)) { continue; } - const TGT target_value = OP::template Operation(data_ptr[r]); + const TGT target_value = OP::template Operation(input.Value(r)); OP::template HandleStats(stats, target_value); page_state.dlba_encoder.WriteValue(temp_writer, target_value); } @@ -439,10 +890,10 @@ class StandardColumnWriter : public PrimitiveColumnWriter { page_state.bss_initialized = true; } for (idx_t r = chunk_start; r < chunk_end; r++) { - if (!ALL_VALID && !mask.RowIsValid(r)) { + if (!ALL_VALID && !input.RowIsValid(r)) { continue; } - const TGT target_value = OP::template Operation(data_ptr[r]); + const TGT target_value = OP::template Operation(input.Value(r)); OP::template HandleStats(stats, target_value); page_state.bss_encoder.WriteValue(target_value); } @@ -450,12 +901,7 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } case duckdb_parquet::Encoding::PLAIN: { D_ASSERT(page_state.encoding == duckdb_parquet::Encoding::PLAIN); - if (mask.CannotHaveNull()) { - TemplatedWritePlain(input_column, stats, chunk_start, chunk_end, mask, temp_writer); - } else { - TemplatedWritePlain(input_column, stats, chunk_start, chunk_end, mask, - temp_writer); - } + TemplatedWritePlain(input, stats, chunk_start, chunk_end, temp_writer); break; } default: diff --git a/src/duckdb/extension/parquet/parquet_column_schema.cpp b/src/duckdb/extension/parquet/parquet_column_schema.cpp index 9616bb4d6..f6923febd 100644 --- a/src/duckdb/extension/parquet/parquet_column_schema.cpp +++ b/src/duckdb/extension/parquet/parquet_column_schema.cpp @@ -203,7 +203,7 @@ unique_ptr ParquetColumnSchema::Stats(const FileMetaData &file_m stats.Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); return stats.ToUnique(); } - return ParquetStatisticsUtils::TransformColumnStatistics(*this, columns, parquet_options.can_have_nan); + return ParquetStatisticsUtils::TransformColumnStatistics(*this, columns, parquet_options); } } // namespace duckdb diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index 4a85a660f..fa267a6cc 100644 --- a/src/duckdb/extension/parquet/parquet_extension.cpp +++ b/src/duckdb/extension/parquet/parquet_extension.cpp @@ -26,6 +26,7 @@ #include #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/table_function_catalog_entry.hpp" +#include "duckdb/common/bind_helpers.hpp" #include "duckdb/common/constants.hpp" #include "duckdb/common/enums/file_compression_type.hpp" #include "duckdb/common/file_system.hpp" @@ -114,6 +115,7 @@ struct ParquetWriteBindData : public TableFunctionData { bool write_page_index = false; //! What false positive rate are we willing to accept for bloom filters double bloom_filter_false_positive_ratio = 0.01; + idx_t bloom_filter_fallback_max_bytes = ParquetBloomFilterMemory::DEFAULT_LIMIT; //! After how many row groups to rotate to a new file optional_idx row_groups_per_file; @@ -157,6 +159,7 @@ static void ParquetListCopyOptions(ClientContext &context, CopyOptionsInput &inp copy_options["bloom_filter_false_positive_ratio"] = CopyOption(LogicalType::DOUBLE, CopyOptionMode::WRITE_ONLY); copy_options["debug_use_openssl"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::READ_WRITE); copy_options["write_bloom_filter"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY); + copy_options["bloom_filter_fallback_max_bytes"] = CopyOption(LogicalType::ANY, CopyOptionMode::WRITE_ONLY); copy_options["write_page_index"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY); copy_options["compression_level"] = CopyOption(LogicalType::BIGINT, CopyOptionMode::WRITE_ONLY); copy_options["parquet_version"] = CopyOption(LogicalType::VARCHAR, CopyOptionMode::WRITE_ONLY); @@ -324,6 +327,8 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun bind_data->data_page_size_limit = val; } else if (option_name == "write_bloom_filter") { bind_data->enable_bloom_filters = BooleanValue::Get(option_values[0].DefaultCastAs(LogicalType::BOOLEAN)); + } else if (option_name == "bloom_filter_fallback_max_bytes") { + bind_data->bloom_filter_fallback_max_bytes = ParseBytesArg(option_name, option_values[0]); } else if (option_name == "write_page_index") { bind_data->write_page_index = BooleanValue::Get(option_values[0].DefaultCastAs(LogicalType::BOOLEAN)); } else if (option_name == "bloom_filter_false_positive_ratio") { @@ -424,6 +429,7 @@ static unique_ptr ParquetWriteInitializeGlobal(ClientContext options.enable_bloom_filters = parquet_bind.enable_bloom_filters, options.write_page_index = parquet_bind.write_page_index; options.bloom_filter_false_positive_ratio = parquet_bind.bloom_filter_false_positive_ratio; + options.bloom_filter_fallback_max_bytes = parquet_bind.bloom_filter_fallback_max_bytes; options.compression_level = parquet_bind.compression_level; options.parquet_version = parquet_bind.parquet_version, options.geoparquet_version = parquet_bind.geoparquet_version; @@ -828,6 +834,11 @@ static void ParquetCopySerialize(Serializer &serializer, const FunctionData &bin default_value.data_page_size_limit); serializer.WritePropertyWithDefault(122, "write_page_index", bind_data.write_page_index, default_value.write_page_index); + serializer.WritePropertyWithDefault(123, "enable_bloom_filters", bind_data.enable_bloom_filters, + default_value.enable_bloom_filters); + serializer.WritePropertyWithDefault(124, "bloom_filter_fallback_max_bytes", + bind_data.bloom_filter_fallback_max_bytes, + default_value.bloom_filter_fallback_max_bytes); } static unique_ptr ParquetCopyDeserialize(Deserializer &deserializer, CopyFunction &function) { @@ -872,6 +883,10 @@ static unique_ptr ParquetCopyDeserialize(Deserializer &deserialize deserializer.ReadPropertyWithExplicitDefault(121, "data_page_size_limit", default_value.data_page_size_limit); data->write_page_index = deserializer.ReadPropertyWithExplicitDefault(122, "write_page_index", default_value.write_page_index); + data->enable_bloom_filters = + deserializer.ReadPropertyWithExplicitDefault(123, "enable_bloom_filters", default_value.enable_bloom_filters); + data->bloom_filter_fallback_max_bytes = deserializer.ReadPropertyWithExplicitDefault( + 124, "bloom_filter_fallback_max_bytes", default_value.bloom_filter_fallback_max_bytes); return std::move(data); } @@ -989,7 +1004,7 @@ static bool IsExtensionGeometryType(const LogicalType &type, ClientContext &cont if (type.GetAlias() != "GEOMETRY") { return false; } - return GeoParquetFileMetadata::IsGeoParquetConversionEnabled(context); + return GeoParquetFileMetadata::IsGeoParquetConversionEnabled(context.GetContext()); } static vector> ParquetWriteSelect(CopyToSelectInput &input) { @@ -1156,6 +1171,10 @@ static void LoadInternal(ExtensionLoader &loader) { config.replacement_scans.emplace_back(ParquetScanReplacement); config.AddExtensionOption("binary_as_string", "In Parquet files, interpret binary data as a string.", LogicalType::BOOLEAN, Value(false)); + config.AddExtensionOption("parquet_can_have_nan", + "In Parquet files without a nan_count, assume FLOAT/DOUBLE columns can hold NaN outside " + "their min/max. The default for the can_have_nan option of Parquet scans.", + LogicalType::BOOLEAN, Value(false)); config.AddExtensionOption("disable_parquet_prefetching", "Disable the prefetching mechanism in Parquet", LogicalType::BOOLEAN, Value(false)); config.AddExtensionOption("prefetch_all_parquet_files", diff --git a/src/duckdb/extension/parquet/parquet_file_metadata_cache.cpp b/src/duckdb/extension/parquet/parquet_file_metadata_cache.cpp index 2fb5f5aa2..91492e9bb 100644 --- a/src/duckdb/extension/parquet/parquet_file_metadata_cache.cpp +++ b/src/duckdb/extension/parquet/parquet_file_metadata_cache.cpp @@ -88,7 +88,8 @@ bool ParquetFileMetadataCache::IsValid(CachingFileHandle &new_handle) const { } ParquetCacheValidity ParquetFileMetadataCache::IsValid(const OpenFileInfo &info, ClientContext &context) const { - CacheValidationMode validation_mode = ExternalFileCacheUtil::GetCacheValidationMode(info, &context, *context.db); + CacheValidationMode validation_mode = + ExternalFileCacheUtil::GetCacheValidationMode(info, &context.GetContext(), *context.db); if (validation_mode == CacheValidationMode::NO_VALIDATION) { return ParquetCacheValidity::VALID; } diff --git a/src/duckdb/extension/parquet/parquet_geometry.cpp b/src/duckdb/extension/parquet/parquet_geometry.cpp index 42fe27e27..4c917b6a3 100644 --- a/src/duckdb/extension/parquet/parquet_geometry.cpp +++ b/src/duckdb/extension/parquet/parquet_geometry.cpp @@ -1,5 +1,6 @@ #include "parquet_geometry.hpp" +#include "duckdb/main/context.hpp" #include #include @@ -40,7 +41,7 @@ using namespace duckdb_yyjson; // NOLINT unique_ptr GeoParquetFileMetadata::TryRead(const duckdb_parquet::FileMetaData &file_meta_data, ClientContext &context) { // Conversion not enabled, or spatial is not loaded! - if (!IsGeoParquetConversionEnabled(context)) { + if (!IsGeoParquetConversionEnabled(context.GetContext())) { return nullptr; } @@ -354,7 +355,7 @@ bool GeoParquetFileMetadata::IsGeometryColumn(const string &column_name) const { return geometry_columns.find(column_name) != geometry_columns.end(); } -bool GeoParquetFileMetadata::IsGeoParquetConversionEnabled(const ClientContext &context) { +bool GeoParquetFileMetadata::IsGeoParquetConversionEnabled(const Context &context) { bool geoparquet_enabled = false; context.TryGetCurrentSetting("enable_geoparquet_conversion", geoparquet_enabled); return geoparquet_enabled; diff --git a/src/duckdb/extension/parquet/parquet_int96.cpp b/src/duckdb/extension/parquet/parquet_int96.cpp index 2178ad62e..afbcee2b4 100644 --- a/src/duckdb/extension/parquet/parquet_int96.cpp +++ b/src/duckdb/extension/parquet/parquet_int96.cpp @@ -52,6 +52,8 @@ unique_ptr CreateInt96AsStructExpression(ClientContext &context) { args.push_back(std::move(ref)); ScalarFunction func("__internal_int96_as_struct", vector {LogicalType::BLOB}, Int96StructType(), Int96AsStructFunction); + // a day or a time outside its range is an error of the file, not an internal one + func.SetFallible(); return func.Bind(context, std::move(args)); } diff --git a/src/duckdb/extension/parquet/parquet_metadata.cpp b/src/duckdb/extension/parquet/parquet_metadata.cpp index d00b53687..fc770d65d 100644 --- a/src/duckdb/extension/parquet/parquet_metadata.cpp +++ b/src/duckdb/extension/parquet/parquet_metadata.cpp @@ -25,6 +25,7 @@ #include "duckdb/common/multi_file/multi_file_data.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/open_file_info.hpp" +#include "duckdb/common/operator/subtract.hpp" #include "duckdb/common/optional_idx.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/pair.hpp" @@ -80,9 +81,9 @@ struct ParquetMetadataFilePaths { }; struct ParquetMetaDataBindData : public TableFunctionData { - unique_ptr file_paths; + shared_ptr file_list; - //! The file list is consumed by the first execution + //! The file list is a glob snapshot taken at bind time bool SupportStatementCache() const override { return false; } @@ -1164,7 +1165,12 @@ void ParquetPageIndexProcessor::ReadRow(vector> &output, idx_t first_row_index = Value::BIGINT(location.first_row_index); const auto next_row = page_idx + 1 < locations.size() ? locations[page_idx + 1].first_row_index : row_group.num_rows; - num_rows = Value::BIGINT(next_row - location.first_row_index); + int64_t page_row_count; + if (!TrySubtractOperator::Operation(next_row, location.first_row_index, page_row_count)) { + throw DataCorruptionException("Failed to read file \"%s\": metadata is corrupt. Page row count overflows", + reader.file.path); + } + num_rows = Value::BIGINT(page_row_count); } // page_offset output[5].get().Append(offset); @@ -1348,10 +1354,8 @@ unique_ptr ParquetMetaDataOperator::Bind(ClientContext &context, T result = std::move(probe_bind_data); } - result->file_paths = make_uniq(); - result->file_paths->file_list = multi_file_reader->CreateFileList(context, input.inputs[0], glob_input); - D_ASSERT(!result->file_paths->file_list->IsEmpty()); - result->file_paths->file_list->InitializeScan(result->file_paths->scan_data); + result->file_list = multi_file_reader->CreateFileList(context, input.inputs[0], glob_input); + D_ASSERT(!result->file_list->IsEmpty()); BindSchema(return_types, names); @@ -1360,8 +1364,13 @@ unique_ptr ParquetMetaDataOperator::Bind(ClientContext &context, T unique_ptr ParquetMetaDataOperator::InitGlobal(ClientContext &context, TableFunctionInitInput &input) { - auto &bind_data = input.bind_data->CastNoConst(); - return make_uniq(std::move(bind_data.file_paths), context); + auto &bind_data = input.bind_data->Cast(); + // The file cursor is scan state: a scan can be initialized multiple times and must restart from the + // first file each time. + auto file_paths = make_uniq(); + file_paths->file_list = bind_data.file_list; + file_paths->file_list->InitializeScan(file_paths->scan_data); + return make_uniq(std::move(file_paths), context); } template diff --git a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp index e63df1248..6c48ea6c6 100644 --- a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp +++ b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp @@ -224,14 +224,18 @@ static vector ParquetMultiFileGetPartitionStats(ClientConte auto &bind_data = input.bind_data->Cast(); if (bind_data.file_list->GetExpandResult() == FileExpandResult::SINGLE_FILE) { auto result = TableFunctionMultiFileWrapper::GetPartitionStats(context, input); - if (!bind_data.file_options.bound_schema.empty()) { - // Column accessors address physical ordinals and types, not the mapped output or generated roles. - const bool identity = - bind_data.initial_reader && bind_data.HasIdentityMapping(bind_data.initial_reader->GetColumns()); - if (!identity) { - for (auto &partition : result) { - partition.partition_row_group.reset(); - } + // Column accessors address physical ordinals and types, not the mapped output or generated roles. + bool identity = false; + if (bind_data.initial_reader) { + identity = bind_data.HasIdentityMapping(bind_data.initial_reader->GetColumns()); + } else if (!bind_data.union_readers.empty()) { + auto &file = *bind_data.union_readers[0]; + identity = bind_data.HasIdentityMapping( + MultiFileColumnDefinition::ColumnsFromNamesAndTypes(StringsToIdentifiers(file.names), file.types)); + } + if (!identity) { + for (auto &partition : result) { + partition.partition_row_group.reset(); } } return result; @@ -257,7 +261,8 @@ void ParquetScanFunction::AddNamedParameters(TableFunction &table_function) { .Add("can_have_nan", LogicalType::BOOLEAN) .Add("prefetch_strategy", LogicalType::VARCHAR) .Add("utf8_validation", LogicalType::VARCHAR) - .Add("int96_as", LogicalType::VARCHAR); + .Add("int96_as", LogicalType::VARCHAR) + .Add("maximum_files_for_stats", LogicalType::UBIGINT); }; // the multi-file function already declares options of its own - the single-file function declares none auto &signature = table_function.GetSignature(); @@ -472,10 +477,6 @@ unique_ptr ParquetMultiFileInfo::GetCardinality(ClientContext &c } // we don't have any scan data - check if we can get some intel from the file list // in particular - if we have file sizes, we try to estimate rows per file from the file size - MultiFileListScanData scan_data; - scan_data.scan_type = MultiFileListScanType::FETCH_IF_AVAILABLE; - bind_data.file_list->InitializeScan(scan_data); - OpenFileInfo file; idx_t initial_cardinality = MaxValue(parquet_data.initial_file_cardinality, 1ULL); idx_t estimated_bytes_per_row = parquet_data.initial_file_data_size / initial_cardinality; // for very small cardinalities, compression doesn't really work well @@ -486,33 +487,10 @@ unique_ptr ParquetMultiFileInfo::GetCardinality(ClientContext &c } estimated_bytes_per_row = MaxValue(estimated_bytes_per_row, 10ULL); - idx_t files_with_sizes = 0; - idx_t estimated_file_row_count = 0; - while (bind_data.file_list->Scan(scan_data, file)) { - if (!file.extended_info) { - // no extended info - estimated_file_row_count = 0; - break; - } - idx_t current_file_size; - if (!file.extended_info->TryGetOption("file_size", current_file_size)) { - // no file size available - estimated_file_row_count = 0; - break; - } - // we have the file size - estimate row count based on estimated bytes per row - files_with_sizes++; - idx_t rows_in_this_file = MaxValue(current_file_size / estimated_bytes_per_row, 1ULL); - estimated_file_row_count += rows_in_this_file; - } - idx_t per_file_cardinality; - if (estimated_file_row_count > 0) { - // use estimate based on file sizes - per_file_cardinality = estimated_file_row_count / files_with_sizes; - } else { - // no estimate based on file sizes - use initial file cardinality - per_file_cardinality = parquet_data.initial_file_cardinality; - } + // use the estimate based on file sizes; without one, the initial file cardinality + auto estimated_rows_per_file = bind_data.file_list->EstimateRowsPerFile(estimated_bytes_per_row); + idx_t per_file_cardinality = + estimated_rows_per_file.IsValid() ? estimated_rows_per_file.GetIndex() : parquet_data.initial_file_cardinality; // if we have several files, our cardinality estimate can be way off if our initial file is ~empty // we set the minimum per file cardinality to 1000 just to avoid greatly underestimating idx_t min_per_file_cardinality = 1000ULL; diff --git a/src/duckdb/extension/parquet/parquet_page_index.cpp b/src/duckdb/extension/parquet/parquet_page_index.cpp index dc8b3b305..55ff1324e 100644 --- a/src/duckdb/extension/parquet/parquet_page_index.cpp +++ b/src/duckdb/extension/parquet/parquet_page_index.cpp @@ -118,7 +118,8 @@ idx_t ParquetPageIndexUtils::PageRowCount(const duckdb_parquet::OffsetIndex &off void ParquetPageIndexUtils::FilterPages(const ParquetColumnSchema &schema, const duckdb_parquet::ColumnIndex &column_index, const TableFilter &filter, - bool can_have_nan, vector &result) { + const ParquetOptions &parquet_options, bool can_have_nan, + vector &result) { const auto page_count = column_index.null_pages.size(); D_ASSERT(ColumnIndexIsValid(column_index, page_count)); auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "ParquetPageIndexUtils::FilterPages"); @@ -140,7 +141,8 @@ void ParquetPageIndexUtils::FilterPages(const ParquetColumnSchema &schema, if (has_null_count) { page_stats.__set_null_count(column_index.null_counts[page_idx]); } - stats = ParquetStatisticsUtils::TransformParquetStatistics(schema.type, schema, page_stats, can_have_nan); + stats = ParquetStatisticsUtils::TransformParquetStatistics(schema.type, schema, page_stats, parquet_options, + can_have_nan); if (!stats) { continue; } diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 0ea72d05e..769c089c3 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/optional_ptr.hpp" #include "duckdb/parallel/callback_async_task.hpp" +#include "duckdb/storage/buffer_manager.hpp" #include "duckdb/common/reference_map.hpp" #include "duckdb/function/partition_stats.hpp" #include "parquet_types.h" @@ -279,7 +280,7 @@ static uint64_t DetermineAcceptedColumnGap(ClientContext &context, ParquetReader } static void ParseParquetFooter(const_data_ptr_t buffer, const string &file_path, idx_t file_size, - const shared_ptr &encryption_config, uint32_t &footer_len, + const shared_ptr &encryption_config, idx_t &footer_len, bool &footer_encrypted) { if (memcmp(buffer + 4, "PAR1", 4) == 0) { footer_encrypted = false; @@ -298,7 +299,7 @@ static void ParseParquetFooter(const_data_ptr_t buffer, const string &file_path, // read four-byte footer length from just before the end magic bytes footer_len = Load(buffer); if (footer_len == 0 || file_size < 12 + footer_len) { - throw InvalidInputException("Footer length error in file '%s'", file_path); + throw DataCorruptionException("Footer length error in file '%s'", file_path); } } @@ -314,7 +315,7 @@ LoadMetadata(ClientContext &context, Allocator &allocator, CachingFileHandle &fi } bool footer_encrypted; - uint32_t footer_len; + idx_t footer_len; // footer size is not provided - read it from the back if (!footer_size.IsValid()) { // We have to do two reads here: @@ -353,7 +354,7 @@ LoadMetadata(ClientContext &context, Allocator &allocator, CachingFileHandle &fi file_size < 12 + provided_footer_len) { throw InvalidInputException("Invalid footer length provided for file '%s'", file_handle.GetPath()); } - footer_len = UnsafeNumericCast(provided_footer_len); + footer_len = provided_footer_len; idx_t total_footer_len = footer_len + 8; auto metadata_pos = file_size - total_footer_len; @@ -363,7 +364,7 @@ LoadMetadata(ClientContext &context, Allocator &allocator, CachingFileHandle &fi auto read_head = transport.GetReadHead(metadata_pos); auto data_ptr = read_head->buffer_ptr; - uint32_t read_footer_len; + idx_t read_footer_len; ParseParquetFooter(data_ptr + footer_len, file_handle.GetPath(), file_size, encryption_config, read_footer_len, footer_encrypted); if (read_footer_len != footer_len) { @@ -599,7 +600,7 @@ LogicalType ParquetReader::DeriveLogicalType(const SchemaElement &s_ele, const P throw IOException( "DECIMAL converted type can only be set for value of Type::(FIXED_LEN_)BYTE_ARRAY/INT32/INT64"); } - return LogicalType::DECIMAL(s_ele.precision, s_ele.scale); + return LogicalType::DECIMAL(NumericCast(s_ele.precision), NumericCast(s_ele.scale)); case ConvertedType::UTF8: case ConvertedType::ENUM: switch (s_ele.type) { @@ -1420,6 +1421,8 @@ void ParquetReader::AddVirtualColumn(column_t virtual_column_id) { ParquetOptions::ParquetOptions(ClientContext &context) { context.TryGetCurrentSetting("binary_as_string", binary_as_string); + // a can_have_nan option of the scan is parsed after this, so it overrides the setting + context.TryGetCurrentSetting("parquet_can_have_nan", can_have_nan); context.TryGetCurrentSetting("debug_delta_only_variant_encoding_enabled", variant_legacy_encoding); } @@ -1540,6 +1543,9 @@ unique_ptr ParquetUnionData::GetStatistics(ClientContext &contex if (reader) { return reader->Cast().GetStatistics(context, name); } + if (!root_schema) { + return nullptr; + } return ParquetReader::ReadStatistics(context, *this, name); } @@ -1870,12 +1876,18 @@ FilterPropagateResult ParquetReader::CheckRowGroupFilterStatistics(ClientContext ParquetReaderScanState &state, ColumnReader &column_reader, const TableFilter &filter) { - auto &group = GetGroup(state); + return CheckRowGroupFilterStatistics(context, state.group_index, column_reader, filter); +} + +FilterPropagateResult ParquetReader::CheckRowGroupFilterStatistics(ClientContext &context, idx_t group_index, + ColumnReader &column_reader, + const TableFilter &filter) { + auto &group = GetFileMetadata()->row_groups[group_index]; auto schema_column_index = column_reader.ColumnIndex(); auto prune_result = FilterPropagateResult::NO_PRUNING_POSSIBLE; bool is_generated_column = schema_column_index >= group.columns.size(); bool is_expression = column_reader.Schema().schema_type == ParquetColumnSchemaType::EXPRESSION; - auto stats = column_reader.Stats(state.group_index, group.columns); + auto stats = column_reader.Stats(group_index, group.columns); if (stats) { bool has_min_max = false; if (!is_generated_column) { @@ -1900,12 +1912,15 @@ FilterPropagateResult ParquetReader::CheckRowGroupFilterStatistics(ClientContext return prune_result; } -bool ParquetReader::DynamicFiltersExcludeRowGroup(ClientContext &context, ParquetReaderScanState &state) { +bool ParquetReader::FiltersExcludeRowGroup(ClientContext &context, ParquetReaderScanState &state, + bool dynamic_filters_only) { for (auto &scan_filter : state.scan_filters) { - auto &expr_filter = - ExpressionFilter::GetExpressionFilter(scan_filter.filter, "ParquetReader::DynamicFiltersExcludeRowGroup"); - if (!ExpressionFilter::ContainsInternalFunction(*expr_filter.expr, DynamicFilterScalarFun::NAME)) { - continue; + if (dynamic_filters_only) { + auto &expr_filter = + ExpressionFilter::GetExpressionFilter(scan_filter.filter, "ParquetReader::FiltersExcludeRowGroup"); + if (!ExpressionFilter::ContainsInternalFunction(*expr_filter.expr, DynamicFilterScalarFun::NAME)) { + continue; + } } auto &column_reader = state.GetColumnReader(MultiFileLocalIndex(scan_filter.filter_idx)); auto prune_result = CheckRowGroupFilterStatistics(context, state, column_reader, scan_filter.filter); @@ -1935,6 +1950,11 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS } auto row_group_num_rows = NumericCast(group.num_rows); + if (filters && row_group_num_rows > 0 && state.offset_in_group == row_group_num_rows) { + // the row group is already ruled out (statistics pass or an earlier column): no Bloom filter reads + return; + } + if (filters) { // filters contain output chunk index, not file col idx! auto filter_entry = filters->TryGetFilterByColumnIndex(col_idx); @@ -1957,16 +1977,29 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS check_bloom_filter = prune_result != FilterPropagateResult::FILTER_ALWAYS_FALSE; } } + if (bloom_reader && parquet_options.RepairsInvalidUTF8() && + StringColumnReader::GetStringColumnType(bloom_reader->Type()) == + StringColumnReader::StringColumnType::VARCHAR) { + // the bloom filter holds the stored bytes, which repairing invalid UTF-8 changes + bloom_reader = nullptr; + } auto hash_strategy = bloom_reader ? ParquetStatisticsUtils::GetBloomFilterHashStrategy( bloom_reader->Schema(), interval_bloom_filter_version) : nullopt; if (check_bloom_filter && bloom_reader && bloom_filter && bloom_reader->Schema().schema_type == ParquetColumnSchemaType::COLUMN && - bloom_reader->ColumnIndex() < group.columns.size() && hash_strategy && - ParquetStatisticsUtils::BloomFilterExcludes( - *bloom_filter, group.columns[bloom_reader->ColumnIndex()].meta_data, *state.thrift_file_proto, - allocator, bloom_reader->Schema(), *hash_strategy)) { - prune_result = FilterPropagateResult::FILTER_ALWAYS_FALSE; + bloom_reader->ColumnIndex() < group.columns.size() && hash_strategy) { + auto &bloom_meta_data = group.columns[bloom_reader->ColumnIndex()].meta_data; + if (bloom_meta_data.__isset.bloom_filter_offset && bloom_meta_data.bloom_filter_offset > 0 && + ParquetStatisticsUtils::HasBloomFilterConstants(*bloom_filter, *hash_strategy)) { + TryAttachBloomFilterReadHead(context, state, column_reader, filter, + bloom_source->Type().IsNested(), bloom_reader->ColumnIndex()); + } + if (ParquetStatisticsUtils::BloomFilterExcludes( + *bloom_filter, group.columns[bloom_reader->ColumnIndex()].meta_data, + *state.thrift_file_proto, allocator, bloom_reader->Schema(), *hash_strategy)) { + prune_result = FilterPropagateResult::FILTER_ALWAYS_FALSE; + } } } @@ -2028,6 +2061,154 @@ bool ParquetReader::TryAttachPageIndexBuffer(ThriftFileTransport &transport) con return true; } +static void FetchBloomFilterGroups(ClientContext &context, const vector> &read_heads, + CachingFileHandle &file_handle); + +struct ParquetReader::BloomFilterReadPlan { + unordered_map> row_group_heads; + vector> fetch_heads; +}; + +ParquetReader::BloomFilterReadPlan +ParquetReader::PlanBloomFilterReads(ClientContext &context, ThriftFileTransport &transport, ColumnReader &column_reader, + const TableFilter &filter, bool nested_filter, idx_t column_chunk_idx) { + struct BloomFilterRange { + idx_t offset; + idx_t length; + idx_t row_group; + }; + vector ranges; + idx_t filter_bytes = 0; + idx_t largest_filter = 0; + auto &row_groups = GetFileMetadata()->row_groups; + for (idx_t group_index = 0; group_index < row_groups.size(); group_index++) { + auto &row_group = row_groups[group_index]; + if (column_chunk_idx >= row_group.columns.size()) { + continue; + } + auto &meta_data = row_group.columns[column_chunk_idx].meta_data; + if (!meta_data.__isset.bloom_filter_offset || !meta_data.__isset.bloom_filter_length || + meta_data.bloom_filter_offset <= 0 || meta_data.bloom_filter_length <= 0) { + continue; + } + auto prune_result = CheckRowGroupFilterStatistics(context, group_index, column_reader, filter); + if (nested_filter ? prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE + : prune_result != FilterPropagateResult::NO_PRUNING_POSSIBLE) { + continue; + } + const auto offset = NumericCast(meta_data.bloom_filter_offset); + const auto length = NumericCast(meta_data.bloom_filter_length); + if (offset >= transport.GetSize() || length > transport.GetSize() - offset) { + continue; + } + if (length > PrefetchCostModel::GAP_MAX - filter_bytes) { + ranges.clear(); + break; + } + filter_bytes += length; + largest_filter = MaxValue(largest_filter, length); + ranges.push_back({offset, length, group_index}); + } + std::sort(ranges.begin(), ranges.end(), + [](const BloomFilterRange &a, const BloomFilterRange &b) { return a.offset < b.offset; }); + const auto concurrency = + MaxValue(1, MinValue(TaskScheduler::GetScheduler(context).NumberOfThreads(), ranges.size())); + const auto group_size = MaxValue(largest_filter, (filter_bytes + concurrency - 1) / concurrency); + ReadAheadBuffer read_ahead(transport.GetCachingFileHandle(), transport.GetAcceptedColumnGap()); + for (auto &range : ranges) { + if (!read_ahead.read_heads.empty()) { + auto &last_head = *read_ahead.read_heads.front(); + const auto merged_end = MaxValue(last_head.GetEnd(), range.offset + range.length); + if (merged_end - last_head.location > group_size) { + read_ahead.merge_set.clear(); + } + } + read_ahead.AddReadHead(range.offset, range.length); + } + read_ahead.merge_set.clear(); + auto &buffer_manager = BufferManager::GetBufferManager(context); + const auto memory_limit = buffer_manager.GetMaxMemory(); + const auto used_memory = buffer_manager.GetUsedMemory(); + const auto available_memory = memory_limit - MinValue(memory_limit, used_memory); + const auto budget = MinValue(PrefetchCostModel::GAP_MAX, available_memory / 8); + idx_t retained_bytes = 0; + for (auto &head : read_ahead.read_heads) { + // Include the block header and sector rounding in the retained-memory estimate. + const auto allocation_size = BufferManager::GetAllocSize(head->size + Storage::DEFAULT_BLOCK_HEADER_SIZE); + if (allocation_size > budget - retained_bytes) { + read_ahead.read_heads.clear(); + break; + } + retained_bytes += allocation_size; + } + // AddReadHead prepends heads; match them to the ranges in file order. + std::reverse(read_ahead.read_heads.begin(), read_ahead.read_heads.end()); + BloomFilterReadPlan plan; + idx_t head_idx = 0; + for (auto &range : ranges) { + while (head_idx < read_ahead.read_heads.size() && + range.offset + range.length > read_ahead.read_heads[head_idx]->GetEnd()) { + head_idx++; + } + if (head_idx == read_ahead.read_heads.size()) { + break; + } + auto &head = read_ahead.read_heads[head_idx]; + D_ASSERT(range.offset >= head->location && range.offset + range.length <= head->GetEnd()); + plan.row_group_heads.emplace(range.row_group, head); + } + if (read_ahead.read_heads.size() > 1) { + plan.fetch_heads = std::move(read_ahead.read_heads); + } + return plan; +} + +bool ParquetReader::TryAttachBloomFilterReadHead(ClientContext &context, ParquetReaderScanState &state, + ColumnReader &column_reader, const TableFilter &filter, + bool nested_filter, idx_t column_chunk_idx) { + if (!state.prefetch_mode || parquet_options.encryption_config) { + return false; + } + auto ¤t_meta_data = GetGroup(state).columns[column_chunk_idx].meta_data; + if (!current_meta_data.__isset.bloom_filter_length || current_meta_data.bloom_filter_length <= 0) { + return false; + } + const auto current_offset = NumericCast(current_meta_data.bloom_filter_offset); + const auto current_length = NumericCast(current_meta_data.bloom_filter_length); + auto &transport = reinterpret_cast(*state.thrift_file_proto->getTransport()); + auto &file_handle = transport.GetCachingFileHandle(); + shared_ptr read_head; + vector> fetch_heads; + { + lock_guard guard(bloom_filter_read_heads_lock); + auto entry = bloom_filter_read_heads.find(column_chunk_idx); + if (entry == bloom_filter_read_heads.end()) { + auto plan = + PlanBloomFilterReads(context, transport, column_reader, filter, nested_filter, column_chunk_idx); + fetch_heads = std::move(plan.fetch_heads); + entry = bloom_filter_read_heads.emplace(column_chunk_idx, std::move(plan.row_group_heads)).first; + } + auto &heads = entry->second; + auto head = heads.find(state.group_index); + if (head == heads.end()) { + return false; + } + read_head = std::move(head->second); + // In-flight scans keep their own references; the reader only retains unclaimed groups. + heads.erase(head); + if (current_offset < read_head->location || current_offset >= read_head->GetEnd() || + current_length > read_head->GetEnd() - current_offset) { + return false; + } + } + if (!fetch_heads.empty()) { + FetchBloomFilterGroups(context, fetch_heads, file_handle); + } + read_head->Fetch(file_handle); + transport.AddFetchedReadHead(std::move(read_head)); + return true; +} + void ParquetReader::PreparePageIndex(ClientContext &context, ParquetReaderScanState &state) { state.page_index.Reset(); state.page_index_active = false; @@ -2150,7 +2331,7 @@ void ParquetReader::PreparePageIndexInternal(ClientContext &context, ParquetRead can_have_nan = ParquetStatisticsUtils::CanHaveNaN(column_chunk.meta_data.statistics, can_have_nan); } ParquetPageIndexUtils::FilterPages(column_reader.Schema(), column_index, filter_column.filter.get(), - can_have_nan, page_may_match[i]); + parquet_options, can_have_nan, page_may_match[i]); for (auto may_match : page_may_match[i]) { any_page_pruned = any_page_pruned || !may_match; } @@ -2314,8 +2495,8 @@ void ParquetReader::InitializeScan(ClientContext &context, ParquetReaderScanStat state.use_page_index = true; context.TryGetCurrentSetting("parquet_use_page_index", state.use_page_index); if (filters) { - state.adaptive_filter_cache.InitializeAdaptiveFilter(*filters, filter_global_indices, context.logger, - file.path); + state.adaptive_filter_cache.InitializeAdaptiveFilter(*filters, filter_global_indices, + context.GetContext().GetLoggerPtr(), file.path); for (auto &entry : *filters) { state.scan_filters.emplace_back(context, entry.GetIndex(), entry.Filter()); } @@ -2475,6 +2656,21 @@ CollectIOTasks(ThriftFileTransport &trans, const shared_ptr & return io_tasks; } +static void FetchBloomFilterGroups(ClientContext &context, const vector> &read_heads, + CachingFileHandle &file_handle) { + vector> tasks; + tasks.reserve(read_heads.size()); + // Fetch checks readiness under the head's lock. + for (auto &read_head : read_heads) { + tasks.push_back(make_uniq([read_head, &file_handle] { read_head->Fetch(file_handle); }, + read_head->size)); + } + auto result = AsyncResult::FromTasks(std::move(tasks), TaskSchedulerType::ASYNC); + if (result.HasTasks()) { + result.ExecuteTasksSynchronously(context); + } +} + ParquetPrefetchStrategy ParquetReader::WholeGroupPrefetch(ParquetReaderScanState &state, ThriftFileTransport &trans, const duckdb_parquet::RowGroup &group, uint64_t total_row_group_span, bool log_prefetch) { @@ -2593,6 +2789,11 @@ ParquetPrefetchStrategy ParquetReader::RegisterRowGroupReads(ClientContext &cont state.group_offset = GetRowGroupOffset(*this, state.group_index); auto &group = GetGroup(state); + // rule the row group out on the statistics of all filters before any column reads a Bloom filter + if (filters && group.num_rows > 0 && FiltersExcludeRowGroup(context, state, false)) { + rows_read += NumericCast(group.num_rows); + state.offset_in_group = NumericCast(group.num_rows); + } // several readers can read the same column chunk (e.g. two fields of one variant column), count each chunk once unordered_set scanned_column_chunks; for (idx_t i = 0; i < column_ids.size(); i++) { @@ -2851,7 +3052,7 @@ AsyncResult ParquetReader::Process(ClientContext &context, ParquetReaderScanStat Logger::Get(context).ShouldLog(ParquetPrefetchLogType::NAME, ParquetPrefetchLogType::LEVEL); const idx_t group_num_rows = GetGroup(state).num_rows; // Queued row groups may predate the current dynamic filter. Do not revisit a partially decoded chunk. - if (state.offset_in_group == 0 && !state.resuming_payload && DynamicFiltersExcludeRowGroup(context, state)) { + if (state.offset_in_group == 0 && !state.resuming_payload && FiltersExcludeRowGroup(context, state, true)) { rows_read += group_num_rows; state.offset_in_group = group_num_rows; } diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 9285ab956..2b1b15f24 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -18,6 +18,7 @@ #include "duckdb/common/types/value.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/helper.hpp" +#include "duckdb/common/array_ptr.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" #include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -51,6 +52,7 @@ #include "duckdb/storage/statistics/string_stats.hpp" #include "duckdb/storage/statistics/variant_stats.hpp" #include "parquet_column_schema.hpp" +#include "parquet_reader.hpp" #include "parquet_types.h" #include "thrift/protocol/TProtocol.h" #include "thrift_tools.hpp" @@ -128,7 +130,7 @@ Value ParquetStatisticsUtils::ConvertValue(const LogicalType &type, const Parque } //! Statistics values that do not fit in the width of the decimal are ignored template -static Value ParquetDecimalStatsValue(T value, uint8_t width, uint8_t scale) { +static Value ParquetDecimalStatsValue(T value, uint32_t width, uint32_t scale) { const auto max_value = Hugeint::POWERS_OF_TEN[width]; const auto hugeint_value = hugeint_t(value); if (hugeint_value >= max_value || hugeint_value <= -max_value) { @@ -488,10 +490,18 @@ static bool TryGetStringStats(const string &value, bool has_value, const string return false; } -unique_ptr -ParquetStatisticsUtils::TransformParquetStatistics(const LogicalType &type, const ParquetColumnSchema &schema, - const duckdb_parquet::Statistics &parquet_stats, bool can_have_nan, - optional_ptr column_chunk) { +unique_ptr ParquetStatisticsUtils::TransformParquetStatistics( + const LogicalType &type, const ParquetColumnSchema &schema, const duckdb_parquet::Statistics &parquet_stats, + const ParquetOptions &parquet_options, bool can_have_nan, optional_ptr column_chunk) { + // INT96 has no defined sort order: a column is only ordered chronologically when the file declares + // INT96_TIMESTAMP_ORDER for it. Under the default TYPE_ORDER the statistics bound the values by byte comparison, + // which is a different order, so pruning on them silently drops rows - the specification requires readers to + // ignore all statistics of such a column, whether it declares TYPE_ORDER or no column order at all. + // See test/sql/copy/parquet/int96_invalid_stats.test + if (schema.parquet_type == Type::INT96) { + auto unknown_stats = BaseStatistics::CreateUnknown(type); + return unknown_stats.ToUnique(); + } switch (type.id()) { case LogicalTypeId::BOOLEAN: case LogicalTypeId::UTINYINT: @@ -529,6 +539,11 @@ ParquetStatisticsUtils::TransformParquetStatistics(const LogicalType &type, cons case LogicalTypeId::BLOB: case LogicalTypeId::VARCHAR: { const bool is_varchar = type.id() == LogicalTypeId::VARCHAR; + if (parquet_options.RepairsInvalidUTF8() && + StringColumnReader::GetStringColumnType(type) == StringColumnReader::StringColumnType::VARCHAR) { + // a repaired value can lie below the minimum or above the maximum of the stored bytes + return StringStats::CreateUnknown(type).ToUnique(); + } auto min_stats_type = parquet_stats.__isset.is_min_value_exact && parquet_stats.is_min_value_exact ? StringStatsType::EXACT_STATS : StringStatsType::TRUNCATED_STATS; @@ -547,6 +562,10 @@ ParquetStatisticsUtils::TransformParquetStatistics(const LogicalType &type, cons max_stats_type == StringStatsType::EXACT_STATS && min_stats == max_stats) { auto constant_stats = StringStats::CreateEmpty(type); StringStats::FromConstant(constant_stats, string_t(min_stats)); + // min/max statistics do not tell us whether the chunk also contains NULL values. CreateEmpty + // leaves the validity mask as "no rows at all", which lets an IS NULL filter prune pages that + // do contain nulls. Keep the validity unknown here; callers that know the null count refine it. + constant_stats.Set(StatsInfo::CAN_HAVE_NULL_AND_VALID_VALUES); return constant_stats.ToUnique(); } auto string_stats = StringStats::CreateUnknown(type); @@ -600,7 +619,9 @@ ParquetStatisticsUtils::TransformParquetStatistics(const LogicalType &type, cons if (!types.empty()) { stats_types.Clear(); for (auto &geom_type : types) { - stats_types.AddWKBType(geom_type); + if (!stats_types.TryAddWKBType(geom_type)) { + throw DataCorruptionException("Invalid geometry type in Parquet file"); + } } } } @@ -618,7 +639,8 @@ ParquetStatisticsUtils::TransformParquetStatistics(const LogicalType &type, cons unique_ptr ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &schema, - const duckdb_parquet::ColumnChunkList &columns, bool can_have_nan) { + const duckdb_parquet::ColumnChunkList &columns, + const ParquetOptions &parquet_options) { // Not supported types auto &type = schema.type; if (type.id() == LogicalTypeId::ARRAY) { @@ -630,7 +652,7 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch if (type.id() == LogicalTypeId::LIST || type.id() == LogicalTypeId::MAP) { auto list_stats = ListStats::CreateUnknown(type); auto &child_schema = schema.children[0]; - auto child_stats = ParquetStatisticsUtils::TransformColumnStatistics(child_schema, columns, can_have_nan); + auto child_stats = ParquetStatisticsUtils::TransformColumnStatistics(child_schema, columns, parquet_options); ListStats::SetChildStats(list_stats, std::move(child_stats)); row_group_stats = list_stats.ToUnique(); return row_group_stats; @@ -641,7 +663,8 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch // Recurse into child readers for (idx_t i = 0; i < schema.children.size(); i++) { auto &child_schema = schema.children[i]; - auto child_stats = ParquetStatisticsUtils::TransformColumnStatistics(child_schema, columns, can_have_nan); + auto child_stats = + ParquetStatisticsUtils::TransformColumnStatistics(child_schema, columns, parquet_options); StructStats::SetChildStats(struct_stats, i, std::move(child_stats)); } row_group_stats = struct_stats.ToUnique(); @@ -671,13 +694,13 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch if (schema.children[0].name != "metadata" || value.name != "value") { return nullptr; } - auto value_stats = ParquetStatisticsUtils::TransformColumnStatistics(value, columns, can_have_nan); + auto value_stats = ParquetStatisticsUtils::TransformColumnStatistics(value, columns, parquet_options); //! Best-effort: nodes whose stats can't be converted are left UNKNOWN (not fully shredded) rather //! than discarding the statistics for the entire variant column ConvertUnshreddedStats(untyped_value_index_stats, value_stats.get()); auto parquet_typed_value_stats = - ParquetStatisticsUtils::TransformColumnStatistics(typed_value, columns, can_have_nan); + ParquetStatisticsUtils::TransformColumnStatistics(typed_value, columns, parquet_options); ConvertShreddedStats(typed_value_stats, parquet_typed_value_stats.get()); //! Set validity to UNKNOWN variant_stats.SetHasNoNull(); @@ -692,7 +715,8 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch return nullptr; } auto &parquet_stats = column_chunk.meta_data.statistics; - row_group_stats = TransformParquetStatistics(type, schema, parquet_stats, can_have_nan, &column_chunk); + row_group_stats = TransformParquetStatistics(type, schema, parquet_stats, parquet_options, + parquet_options.can_have_nan, &column_chunk); // null count is generic if (row_group_stats) { @@ -1156,6 +1180,11 @@ ParquetStatisticsUtils::GetBloomFilterHashStrategy(const ParquetColumnSchema &sc } } +bool ParquetStatisticsUtils::HasBloomFilterConstants(const TableFilter &filter, + ParquetBloomFilterHashStrategy hash_strategy) { + return HasFilterConstants(filter, hash_strategy); +} + bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filter, const duckdb_parquet::ColumnMetaData &column_meta_data, TProtocol &file_proto, Allocator &allocator, @@ -1185,7 +1214,10 @@ bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filte transport.SetLocation(bloom_filter_start); if (bloom_filter_length > 0) { - transport.Prefetch(bloom_filter_start, bloom_filter_length); + auto read_head = transport.GetReadHead(bloom_filter_start, bloom_filter_length); + if (!read_head || !read_head->data_isset) { + transport.Prefetch(bloom_filter_start, bloom_filter_length); + } } duckdb_parquet::BloomFilterHeader filter_header; @@ -1221,21 +1253,98 @@ bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filte return ApplyBloomFilter(duckdb_filter, bloom_filter, schema, hash_strategy); } -ParquetBloomFilter::ParquetBloomFilter(idx_t num_entries, double bloom_filter_false_positive_ratio) { - // aim for hit ratio of 0.01% - // see http://tfk.mit.edu/pdf/bloom.pdf - double f = bloom_filter_false_positive_ratio; - double k = 8.0; - double n = LossyNumericCast(num_entries); - double m = -k * n / std::log(1 - std::pow(f, 1 / k)); - auto b = MaxValue(NextPowerOfTwo(LossyNumericCast(m / k)) / 32, 1); +bool ParquetBloomFilterMemory::TryReserve(idx_t bytes) { + if (TryReserveInternal(bytes)) { + return true; + } + if (bytes > limit) { + return false; + } + make_room(); + return TryReserveInternal(bytes); +} - D_ASSERT(b > 0 && IsPowerOfTwo(b)); +bool ParquetBloomFilterMemory::TryReserveInternal(idx_t bytes) { + lock_guard guard(lock); + if (bytes > limit - used) { + return false; + } + used += bytes; + return true; +} - data = make_uniq(Allocator::DefaultAllocator(), sizeof(ParquetBloomBlock) * b); - data->zero(); - block_count = data->len / sizeof(ParquetBloomBlock); - D_ASSERT(data->len % sizeof(ParquetBloomBlock) == 0); +void ParquetBloomFilterMemory::Release(idx_t bytes) { + lock_guard guard(lock); + D_ASSERT(bytes <= used); + used -= bytes; +} + +// see http://tfk.mit.edu/pdf/bloom.pdf +static optional_idx BloomFilterSize(idx_t num_entries, double target) { + D_ASSERT(target > 0 && target <= 1); + // Check the floating-point size before converting or rounding to a power of two. + const auto bytes = -LossyNumericCast(num_entries) / std::log1p(-std::pow(target, 1.0 / 8.0)); + constexpr idx_t max_filter_bytes = 128ULL * 1024 * 1024; + if (!std::isfinite(bytes) || bytes > max_filter_bytes) { + return optional_idx(); + } + return MaxValue(sizeof(ParquetBloomBlock), NextPowerOfTwo(LossyNumericCast(bytes))); +} + +static unique_ptr AllocateBloomFilter(Allocator &allocator, idx_t size) { + auto buffer = make_uniq(allocator, size); + buffer->zero(); + return buffer; +} + +optional_idx ParquetBloomFilter::EstimateSize(idx_t num_entries, double target) { + return BloomFilterSize(num_entries, target); +} + +unique_ptr ParquetBloomFilter::Create(Allocator &allocator, idx_t num_entries, double target) { + const auto size = BloomFilterSize(num_entries, target); + if (!size.IsValid()) { + return nullptr; + } + return make_uniq(AllocateBloomFilter(allocator, size.GetIndex())); +} + +unique_ptr ParquetBloomFilter::TryCreate(Allocator &allocator, idx_t num_entries, double target, + shared_ptr memory) { + if (!num_entries) { + return nullptr; + } + const auto size = BloomFilterSize(num_entries, target); + if (!size.IsValid()) { + return nullptr; + } + // Reserve scratch space as well, so concurrent compaction stays within the budget. + const auto reservation = size.GetIndex() + size.GetIndex() / 2; + if (!memory->TryReserve(reservation)) { + return nullptr; + } + try { + auto result = make_uniq(AllocateBloomFilter(allocator, size.GetIndex())); + result->memory = memory; + result->reserved_bytes = reservation; + return result; + } catch (...) { + memory->Release(reservation); + throw; + } +} + +ParquetBloomFilter::~ParquetBloomFilter() { + data.reset(); + ReleaseReservation(); +} + +void ParquetBloomFilter::ReleaseReservation() { + if (memory) { + memory->Release(reserved_bytes); + memory.reset(); + reserved_bytes = 0; + } } ParquetBloomFilter::ParquetBloomFilter(unique_ptr data_p) { @@ -1276,6 +1385,44 @@ double ParquetBloomFilter::OneRatio() { return LossyNumericCast(one_count) / (LossyNumericCast(data->len) * 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); + const auto factor = block_count / new_block_count; + for (idx_t i = 0; i < new_block_count; i++) { + auto &merged = target[i]; + for (idx_t j = i * factor; j < (i + 1) * factor; j++) { + for (idx_t word = 0; word < 8; word++) { + merged.block[word] |= source[j].block[word]; + } + } + } + data = std::move(folded); + block_count = new_block_count; +} + +void ParquetBloomFilter::FoldToTarget(Allocator &allocator, double target) { + D_ASSERT(IsPowerOfTwo(block_count)); + double zero_ratio = 1.0 - OneRatio(); + auto new_block_count = block_count; + while (new_block_count > 1) { + zero_ratio *= zero_ratio; + if (std::pow(1.0 - zero_ratio, 8) > target) { + break; + } + new_block_count /= 2; + } + if (new_block_count < block_count) { + Shrink(allocator, new_block_count); + } + if (memory) { + memory->Release(reserved_bytes - data->len); + reserved_bytes = data->len; + } +} + ResizeableBuffer *ParquetBloomFilter::Get() { return data.get(); } diff --git a/src/duckdb/extension/parquet/parquet_timestamp.cpp b/src/duckdb/extension/parquet/parquet_timestamp.cpp index 057561fda..c87f5a4a4 100644 --- a/src/duckdb/extension/parquet/parquet_timestamp.cpp +++ b/src/duckdb/extension/parquet/parquet_timestamp.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" +#include "duckdb/common/operator/subtract.hpp" #include "duckdb/common/types/date.hpp" #include "duckdb/common/types/time.hpp" #include "duckdb/common/types/timestamp.hpp" @@ -20,6 +21,17 @@ static constexpr int64_t MICROSECONDS_PER_DAY = MILLISECONDS_PER_DAY * 1000LL; static constexpr int64_t NANOSECONDS_PER_MICRO = 1000LL; static constexpr int64_t NANOSECONDS_PER_DAY = MICROSECONDS_PER_DAY * 1000LL; +bool ParquetTimeIsValid(const int64_t &raw, const int64_t day) { + return raw >= 0 && raw <= day; +} + +template +static void CheckParquetTime(const T &raw, const int64_t day) { + if (!ParquetTimeIsValid(raw, day)) { + throw InvalidInputException("Invalid TIME value %d in Parquet file - TIME values must be within a day", raw); + } +} + static inline int64_t ImpalaTimestampToDays(const Int96 &impala_timestamp) { return impala_timestamp.value[2] - JULIAN_TO_UNIX_EPOCH_DAYS; } @@ -44,7 +56,8 @@ static int64_t ImpalaTimestampToNanoseconds(const Int96 &impala_timestamp) { if (days_since_epoch < 0) { // Don't saturate the minimum value by going past it if (!TryMultiplyOperator::Operation(days_since_epoch + 1, NANOSECONDS_PER_DAY, day_nanoseconds) || - !TryAddOperator::Operation(day_nanoseconds, nanoseconds - NANOSECONDS_PER_DAY, result)) { + !TrySubtractOperator::Operation(nanoseconds, NANOSECONDS_PER_DAY, nanoseconds) || + !TryAddOperator::Operation(day_nanoseconds, nanoseconds, result)) { // out of range for TIMESTAMP_NS - saturate to -infinity return timestamp_ns_t::ninfinity().value; } @@ -70,11 +83,18 @@ timestamp_t ImpalaTimestampToTimestamp(const Int96 &raw_ts) { } date_t ImpalaTimestampToDate(const Int96 &raw_ts) { - return date_t(NumericCast(ImpalaTimestampToDays(raw_ts))); + auto days_since_epoch = ImpalaTimestampToDays(raw_ts); + // the Julian day is unsigned, so the day count can lie outside the finite DATE range + if (days_since_epoch <= date_t::ninfinity().days || days_since_epoch >= date_t::infinity().days) { + throw InvalidInputException("Int96 timestamp is out of range"); + } + return date_t(static_cast(days_since_epoch)); } dtime_ns_t ImpalaTimestampToTimeNs(const Int96 &raw_ts) { - return dtime_ns_t(Load(const_data_ptr_cast(raw_ts.value))); + auto nanoseconds = Load(const_data_ptr_cast(raw_ts.value)); + CheckParquetTime(nanoseconds, Interval::NANOS_PER_DAY); + return dtime_ns_t(nanoseconds); } Int96 TimestampToImpalaTimestamp(timestamp_t &ts) { @@ -141,17 +161,6 @@ static T ParquetWrapTime(const T &raw, const T day) { return modulus + (modulus < 0) * day; } -bool ParquetTimeIsValid(const int64_t &raw, const int64_t day) { - return raw >= 0 && raw <= day; -} - -template -static void CheckParquetTime(const T &raw, const int64_t day) { - if (!ParquetTimeIsValid(raw, day)) { - throw InvalidInputException("Invalid TIME value %d in Parquet file - TIME values must be within a day", raw); - } -} - dtime_t ParquetMsIntToTime(const int32_t &raw_millis) { CheckParquetTime(raw_millis, Interval::MSECS_PER_SEC * Interval::SECS_PER_DAY); return Time::FromTimeMs(raw_millis); diff --git a/src/duckdb/extension/parquet/parquet_writer.cpp b/src/duckdb/extension/parquet/parquet_writer.cpp index 3f0ea07db..0533e108d 100644 --- a/src/duckdb/extension/parquet/parquet_writer.cpp +++ b/src/duckdb/extension/parquet/parquet_writer.cpp @@ -111,6 +111,24 @@ class ParquetPreparedWriteBuffer : public AsyncWriteBuffer { idx_t size; }; +class ParquetBloomFilterWriteBuffer : public AsyncWriteBuffer { +public: + explicit ParquetBloomFilterWriteBuffer(unique_ptr bloom_filter_p) + : bloom_filter(std::move(bloom_filter_p)) { + } + + data_ptr_t Ptr() override { + return bloom_filter->Get()->ptr; + } + + idx_t Size() const override { + return bloom_filter->Get()->len; + } + +private: + unique_ptr bloom_filter; +}; + bool ParquetWriter::TryGetParquetType(const LogicalType &duckdb_type, optional_ptr parquet_type_ptr, bool write_timestamp_as_int96) { Type::type parquet_type; @@ -337,8 +355,8 @@ void ParquetWriter::SetSchemaProperties(const LogicalType &duckdb_type, duckdb_p break; case LogicalTypeId::DECIMAL: schema_ele.converted_type = ConvertedType::DECIMAL; - schema_ele.precision = DecimalType::GetWidth(duckdb_type); - schema_ele.scale = DecimalType::GetScale(duckdb_type); + schema_ele.precision = NumericCast(DecimalType::GetWidth(duckdb_type)); + schema_ele.scale = NumericCast(DecimalType::GetScale(duckdb_type)); schema_ele.__isset.converted_type = true; schema_ele.__isset.precision = true; schema_ele.__isset.scale = true; @@ -518,7 +536,7 @@ ParquetWriter::ParquetWriter(ClientContext &context, FileSystem &fs, ParquetWrit : context(context), options(std::move(options_p)), metadata_arena(BufferAllocator::Get(context)), file_meta_data(metadata_arena) { // initialize the file writer - writer = make_uniq(context, fs, options.file_name.c_str(), options.open_flags); + writer = make_uniq(context.GetContext(), fs, options.file_name.c_str(), options.open_flags); if (options.encryption_config) { // Get the encryption util @@ -565,6 +583,15 @@ ParquetWriter::ParquetWriter(ClientContext &context, FileSystem &fs, ParquetWrit } } + bloom_filter_fallback_memory = + make_shared_ptr(options.bloom_filter_fallback_max_bytes, [this]() { + auto batch_guard = writer->StartBatch(); + { + lock_guard glock(lock); + FlushBloomFilters(); + } + batch_guard.Finish(); + }); InitializeColumnWriters(); } @@ -586,6 +613,9 @@ void ParquetWriter::InitializeColumnWriters() { column_writers.push_back(ColumnWriter::CreateWriterRecursive( context, *this, path_in_schema, types[i], Identifier(unique_names[i]), allow_geometry, &options.field_ids, &options.shredding_types, 0, 1, can_have_nulls)); + auto &column_writer = *column_writers.back(); + column_writer.bloom_filter_fallback = + options.enable_bloom_filters && !options.encryption_config && column_writer.SupportsBloomFilterFallback(); } } @@ -616,7 +646,7 @@ void ParquetWriter::AnalyzeSchema(ColumnDataCollection &buffer, vector { template struct DecimalStatsUnifier : public NumericStatsUnifier { - DecimalStatsUnifier(uint8_t width, uint8_t scale) : width(width), scale(scale) { + DecimalStatsUnifier(uint32_t width, uint32_t scale) : width(width), scale(scale) { } - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; string StatsToString(const string &stats) override { if (stats.empty()) { @@ -1278,6 +1314,10 @@ void ParquetWriter::FlushColumnStats(idx_t col_idx, duckdb_parquet::ColumnChunk stats_unifier->max_is_exact = stats_unifier->max_is_exact && column.meta_data.statistics.__isset.is_max_value_exact && column.meta_data.statistics.is_max_value_exact; + } else if (column.meta_data.statistics.__isset.null_count && + column.meta_data.statistics.null_count == column.meta_data.num_values) { + // every value of this column in the row group is NULL, so the row group has no min/max to contribute: + // the min/max of the other row groups still describe every non-NULL value in the file } else { stats_unifier->all_min_max_set = false; } @@ -1435,17 +1475,18 @@ void ParquetWriter::InitializeSchemaFromPreparedRowGroup(const PreparedRowGroup InitializeStatsUnifiers(); } -void ParquetWriter::Finalize() { - InitializeSchemaElements(); - - // dump the bloom filters right before footer, not if stuff is encrypted - +void ParquetWriter::FlushBloomFilters() { + std::sort(bloom_filters.begin(), bloom_filters.end(), + [](const ParquetBloomFilterEntry &a, const ParquetBloomFilterEntry &b) { + return a.column_idx < b.column_idx || + (a.column_idx == b.column_idx && a.row_group_idx < b.row_group_idx); + }); for (auto &bloom_filter_entry : bloom_filters) { D_ASSERT(!options.encryption_config); // write nonsense bloom filter header duckdb_parquet::BloomFilterHeader filter_header; - auto bloom_filter_bytes = bloom_filter_entry.bloom_filter->Get(); - filter_header.numBytes = NumericCast(bloom_filter_bytes->len); + const auto bloom_filter_size = bloom_filter_entry.bloom_filter->Get()->len; + filter_header.numBytes = NumericCast(bloom_filter_size); filter_header.algorithm.__set_BLOCK(duckdb_parquet::SplitBlockAlgorithm()); filter_header.compression.__set_UNCOMPRESSED(duckdb_parquet::Uncompressed()); filter_header.hash.__set_XXHASH(duckdb_parquet::XxHash()); @@ -1458,13 +1499,21 @@ void ParquetWriter::Finalize() { column_chunk.meta_data.bloom_filter_offset = NumericCast(writer->GetTotalWritten()); auto bloom_filter_header_size = Write(filter_header); - // write actual data - WriteData(bloom_filter_bytes->ptr, bloom_filter_bytes->len); + // the async writer accounts for the bytes it queues, so the filter no longer needs the budget + bloom_filter_entry.bloom_filter->ReleaseReservation(); + WriteData(make_uniq(std::move(bloom_filter_entry.bloom_filter))); column_chunk.meta_data.__isset.bloom_filter_length = true; - column_chunk.meta_data.bloom_filter_length = - NumericCast(bloom_filter_header_size + bloom_filter_bytes->len); + column_chunk.meta_data.bloom_filter_length = NumericCast(bloom_filter_header_size + bloom_filter_size); } + bloom_filters.clear(); +} + +void ParquetWriter::Finalize() { + InitializeSchemaElements(); + + // dump the remaining bloom filters right before footer, not if stuff is encrypted + FlushBloomFilters(); // the page index goes right in front of the footer, after the bloom filters, so that it is part of the tail of the // file a reader fetches together with the footer: first the ColumnIndex of every column chunk, then the @@ -1501,7 +1550,7 @@ void ParquetWriter::Finalize() { } // Add geoparquet metadata to the file metadata - if (geoparquet_data && GeoParquetFileMetadata::IsGeoParquetConversionEnabled(context) && + if (geoparquet_data && GeoParquetFileMetadata::IsGeoParquetConversionEnabled(context.GetContext()) && GetGeoParquetVersion() != GeoParquetVersion::NONE) { geoparquet_data->Write(file_meta_data); } diff --git a/src/duckdb/extension/parquet/read_single_parquet_file.cpp b/src/duckdb/extension/parquet/read_single_parquet_file.cpp index e6c27eaea..eb8d29273 100644 --- a/src/duckdb/extension/parquet/read_single_parquet_file.cpp +++ b/src/duckdb/extension/parquet/read_single_parquet_file.cpp @@ -5,6 +5,7 @@ #include "parquet_reader.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/once_flag.hpp" +#include "duckdb/common/operator/add.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/operator/logical_get.hpp" @@ -397,7 +398,20 @@ static unique_ptr ReadSingleParquetFileCardinality(ClientContext if (!parquet_data.cardinality.IsValid()) { return nullptr; } - return make_uniq(parquet_data.cardinality.GetIndex()); + auto result = make_uniq(parquet_data.cardinality.GetIndex()); + if (!parquet_data.metadata) { + return result; + } + // Execution reuses these row groups; the footer's total is not validated against their population. + idx_t maximum = 0; + for (auto &group : parquet_data.metadata->metadata->file_metadata.row_groups) { + if (group.num_rows < 0 || !TryAddOperator::Operation(maximum, static_cast(group.num_rows), maximum)) { + return result; + } + } + result->has_max_cardinality = true; + result->max_cardinality = maximum; + return result; } //! The virtual columns the parquet reader can produce for a file @@ -468,12 +482,13 @@ bool ParquetScanFunction::ProjectionExpressionPushdown(ClientContext &context, } auto &bind_data = input.get.bind_data->CastNoConst(); // Don't do pushdown on custom schema users like Ducklake, or when the schemas of several files are unified - if (!bind_data.reader_bind.schema.empty() || !bind_data.union_readers.empty()) { + if (!bind_data.reader_bind.schema.empty() || bind_data.file_options.union_by_name) { return false; } // Don't do pushdown with multiple files - the metadata of all but the first file is not available upfront, and // the files may have their columns in a different order - if (bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES || !bind_data.initial_reader) { + if (bind_data.file_list->GetExpandResult() != FileExpandResult::SINGLE_FILE || + bind_data.union_readers.size() != 1) { return false; } const auto &column_id = input.get.GetColumnIds()[input.column_index]; @@ -490,19 +505,18 @@ bool ParquetScanFunction::ProjectionExpressionPushdown(ClientContext &context, if (input.get.table_filters.HasFilter(input.column_index)) { return false; } - auto &reader = bind_data.initial_reader->Cast(); - if (!reader.bind_data) { + auto &file = bind_data.union_readers[0]->Cast(); + if (!file.bind_data) { return false; } - auto &parquet_data = reader.bind_data->Cast(); + auto &parquet_data = file.bind_data->Cast(); auto &metadata_reader = parquet_data.GetMetadataReader(context); auto &children = metadata_reader.root_schema->children; - if (idx >= children.size() || idx >= bind_data.types.size() || idx >= reader.types.size()) { + if (idx >= children.size() || idx >= bind_data.types.size() || idx >= file.types.size()) { return false; } - if (!bind_data.file_options.bound_schema.empty() && - (idx >= reader.columns.size() || - !bind_data.MatchesPhysicalColumn(idx, reader.columns[idx].name, reader.types[idx]))) { + if (idx >= file.names.size() || + !bind_data.MatchesPhysicalColumn(idx, Identifier(file.names[idx]), file.types[idx])) { // The pushed expression addresses a physical column, before name mapping and conversion. return false; } @@ -522,12 +536,19 @@ bool ParquetScanFunction::ProjectionExpressionPushdown(ClientContext &context, parquet_data.AddProjectionExpression(idx, expression); bind_data.types[idx] = type; bind_data.columns[idx].type = type; - // the reader of the file was bound before the expression was pushed down - update its types - reader.types[idx] = type; - if (idx < reader.columns.size()) { - reader.columns[idx].type = type; + file.types[idx] = type; + if (bind_data.initial_reader) { + // The cached reader was bound before the expression was pushed down. + auto &reader = bind_data.initial_reader->Cast(); + reader.types[idx] = type; + if (idx < reader.columns.size()) { + reader.columns[idx].type = type; + } } auto &data = bind_data.bind_data->Cast(); + if (data.options.schema_bind_data && data.options.schema_bind_data != file.bind_data) { + data.options.schema_bind_data->Cast().AddProjectionExpression(idx, expression); + } if (idx < data.options.expected_types.size()) { data.options.expected_types[idx] = type; } diff --git a/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp b/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp index 3df8d70b5..751b9906b 100644 --- a/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp +++ b/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp @@ -13,6 +13,10 @@ namespace duckdb { class ParquetReader; struct hugeint_t; +[[noreturn]] void ParquetDecimalUtils::ThrowInvalidDecimalEncoding() { + throw DataCorruptionException("Invalid decimal encoding in Parquet file"); +} + template static unique_ptr CreateDecimalReaderInternal(const ParquetReader &reader, const ParquetColumnSchema &schema) { diff --git a/src/duckdb/extension/parquet/writer/enum_column_writer.cpp b/src/duckdb/extension/parquet/writer/enum_column_writer.cpp index b030cc307..841ab3a03 100644 --- a/src/duckdb/extension/parquet/writer/enum_column_writer.cpp +++ b/src/duckdb/extension/parquet/writer/enum_column_writer.cpp @@ -32,22 +32,40 @@ class EnumStatisticsState : public StringStatisticsState { return false; } }; + +class EnumColumnWriterState : public PrimitiveColumnWriterState { +public: + EnumColumnWriterState(ParquetWriter &writer, duckdb_parquet::RowGroup &row_group, idx_t col_idx, idx_t enum_count) + : PrimitiveColumnWriterState(writer, row_group, col_idx), seen_enum(enum_count, false) { + } + + //! Tracks which enum values have been written in this row group + vector seen_enum; +}; } // namespace class EnumWriterPageState : public ColumnWriterPageState { public: - explicit EnumWriterPageState(uint32_t bit_width) : encoder(bit_width), written_value(false) { + EnumWriterPageState(uint32_t bit_width, vector &seen_enum) + : encoder(bit_width), written_value(false), seen_enum(seen_enum) { } RleBpEncoder encoder; bool written_value; + vector &seen_enum; }; EnumColumnWriter::EnumColumnWriter(ParquetWriter &writer, ParquetColumnSchema &&column_schema, vector schema_path_p) : PrimitiveColumnWriter(writer, std::move(column_schema), std::move(schema_path_p)) { bit_width = RleBpDecoder::ComputeBitWidthFromValueCount(EnumType::GetSize(Type())); - seen_enum.resize(EnumType::GetSize(Type()), false); +} + +unique_ptr EnumColumnWriter::InitializeWriteState(duckdb_parquet::RowGroup &row_group) { + auto result = + make_uniq(writer, row_group, row_group.columns.size(), EnumType::GetSize(Type())); + RegisterToRowGroup(row_group); + return std::move(result); } unique_ptr EnumColumnWriter::InitializeStatsState() { @@ -68,7 +86,7 @@ void EnumColumnWriter::WriteEnumInternal(WriteStream &temp_writer, Vector &input page_state.written_value = true; } page_state.encoder.WriteValue(temp_writer, ptr[r]); - seen_enum[ptr[r]] = true; + page_state.seen_enum[ptr[r]] = true; } } } @@ -92,9 +110,10 @@ void EnumColumnWriter::WriteVector(WriteStream &temp_writer, ColumnWriterStatist } } -unique_ptr EnumColumnWriter::InitializePageState(PrimitiveColumnWriterState &state, +unique_ptr EnumColumnWriter::InitializePageState(PrimitiveColumnWriterState &state_p, idx_t page_idx) { - return make_uniq(bit_width); + auto &state = state_p.Cast(); + return make_uniq(bit_width, state.seen_enum); } void EnumColumnWriter::FlushPageState(WriteStream &temp_writer, ColumnWriterPageState *state_p) { @@ -117,10 +136,16 @@ bool EnumColumnWriter::HasDictionary(PrimitiveColumnWriterState &state) { } idx_t EnumColumnWriter::DictionarySize(PrimitiveColumnWriterState &state_p) { - return EnumType::GetSize(Type()); + auto &state = state_p.Cast(); + idx_t distinct_count = 0; + for (auto seen : state.seen_enum) { + distinct_count += seen; + } + return distinct_count; } -void EnumColumnWriter::FlushDictionary(PrimitiveColumnWriterState &state, ColumnWriterStatistics *stats_p) { +void EnumColumnWriter::FlushDictionary(PrimitiveColumnWriterState &state_p, ColumnWriterStatistics *stats_p) { + auto &state = state_p.Cast(); auto &stats = stats_p->Cast(); auto &enum_values = EnumType::GetValuesInsertOrder(Type()); auto enum_count = EnumType::GetSize(Type()); @@ -129,7 +154,7 @@ void EnumColumnWriter::FlushDictionary(PrimitiveColumnWriterState &state, Column auto temp_writer = make_uniq(BufferAllocator::Get(writer.GetContext())); for (idx_t r = 0; r < enum_count; r++) { D_ASSERT(!FlatVector::IsNull(enum_values, r)); - if (seen_enum[r]) { + if (state.seen_enum[r]) { stats.Update(string_values[r]); temp_writer->Write(string_values[r].GetSize()); temp_writer->WriteData(const_data_ptr_cast(string_values[r].GetData()), string_values[r].GetSize()); diff --git a/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp b/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp index 2d3c9c995..72148fd64 100644 --- a/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp +++ b/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp @@ -560,6 +560,11 @@ void PrimitiveColumnWriter::FinalizeWrite(ColumnWriterState &state_p) { FinalizePageIndex(state, page_index); 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 > + NumericCast(column_chunk.meta_data.total_compressed_size)) { + state.bloom_filter.reset(); + } if (state.bloom_filter) { writer.BufferBloomFilter(state.col_idx, std::move(state.bloom_filter)); } diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 58d372725..3448e2656 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-alpha52095"; + descriptor->api_version = "v2.1.0-alpha54042"; 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-alpha52095"; + descriptor->api_version = "v2.1.0-alpha54042"; 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-alpha52095"; + descriptor->api_version = "v2.1.0-alpha54042"; 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-alpha52095"; + descriptor->api_version = "v2.1.0-alpha54042"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog.cpp b/src/duckdb/src/catalog/catalog.cpp index e24b7386d..28be08e76 100644 --- a/src/duckdb/src/catalog/catalog.cpp +++ b/src/duckdb/src/catalog/catalog.cpp @@ -40,9 +40,11 @@ #include "duckdb/main/connection.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/database_manager.hpp" +#include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/function/built_in_functions.hpp" #include "duckdb/catalog/similar_catalog_entry.hpp" #include "duckdb/catalog/schema_scan_filters.hpp" +#include "duckdb/catalog/entry_scan_filters.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/storage/database_size.hpp" @@ -1282,8 +1284,15 @@ CatalogEntryLookup Catalog::TryLookupDefaultTable(CatalogEntryRetriever &retriev auto transaction = catalog_by_name->GetCatalogTransaction(retriever.GetContext()); QueryErrorContext context; - auto table_schema = catalog_by_name->GetDefaultTableSchema(); - auto table_name = catalog_by_name->GetDefaultTable(); + // read the schema and the table under one lock: ATTACH can change both while we look them up + Identifier table_schema; + Identifier table_name; + { + lock_guard guard(catalog_by_name->default_table_lock); + table_schema = !catalog_by_name->default_table_schema.empty() ? catalog_by_name->default_table_schema + : Identifier(DEFAULT_SCHEMA); + table_name = catalog_by_name->default_table; + } optional_ptr at_clause; if (!catalog_by_name->SupportsTimeTravel() && allow_ignore_at_clause) { @@ -1509,6 +1518,11 @@ bool SchemaScanFilters::Accepts(ClientContext &context, const SchemaCatalogEntry Satisfies(context, schema_oid, Value::BIGINT(NumericCast(schema.oid))); } +bool EntryScanFilters::Accepts(ClientContext &context, const CatalogEntry &entry) const { + return SchemaScanFilters::Satisfies(context, name, Value(entry.name.GetIdentifierName())) && + SchemaScanFilters::Satisfies(context, oid, Value::BIGINT(NumericCast(entry.oid))); +} + vector> Catalog::GetSchemasForScan(ClientContext &context, const SchemaScanFilters &filters) { vector> schemas; @@ -1562,11 +1576,14 @@ vector> Catalog::GetAllSchemas(ClientContext &cont vector> result; auto &db_manager = DatabaseManager::Get(context); + auto &meta_transaction = MetaTransaction::Get(context); auto databases = db_manager.GetDatabases(context); for (auto &database : databases) { if (database->GetVisibility() == AttachVisibility::HIDDEN) { continue; } + // keep the database alive until the end of the transaction, the returned schemas reference it + meta_transaction.UseDatabase(database); auto &catalog = database->GetCatalog(); auto new_schemas = catalog.GetSchemas(context); result.insert(result.end(), new_schemas.begin(), new_schemas.end()); @@ -1678,19 +1695,23 @@ optional Catalog::GetDefaultSchema() const { //! Whether this catalog has a default table. Catalogs with a default table can be queries by their catalog name bool Catalog::HasDefaultTable() const { + lock_guard guard(default_table_lock); return !default_table.empty(); } void Catalog::SetDefaultTable(const Identifier &schema, const Identifier &name) { + lock_guard guard(default_table_lock); default_table = name; default_table_schema = schema; } Identifier Catalog::GetDefaultTable() const { + lock_guard guard(default_table_lock); return default_table; } Identifier Catalog::GetDefaultTableSchema() const { + lock_guard guard(default_table_lock); return !default_table_schema.empty() ? default_table_schema : DEFAULT_SCHEMA; } diff --git a/src/duckdb/src/catalog/catalog_entry/schema_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/schema_catalog_entry.cpp index 77581c8f2..adc0de782 100644 --- a/src/duckdb/src/catalog/catalog_entry/schema_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/schema_catalog_entry.cpp @@ -2,6 +2,7 @@ #include "duckdb/catalog/default/default_schemas.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/entry_scan_filters.hpp" #include "duckdb/common/algorithm.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/catalog/dependency_list.hpp" @@ -84,6 +85,14 @@ void SchemaCatalogEntry::Scan(CatalogTransaction transaction, CatalogType type, Scan(transaction.GetContext(), type, callback); } +void SchemaCatalogEntry::Scan(ClientContext &context, SchemaScanInfo &info) { + Scan(context, info.type, [&](CatalogEntry &entry) { + if (!info.filter || info.filter->Accepts(context, entry)) { + info.callback(entry); + } + }); +} + template static void ScanSchemaTreeInternal(SchemaCatalogEntry &root, SCAN scan, const std::function &callback) { diff --git a/src/duckdb/src/catalog/catalog_set.cpp b/src/duckdb/src/catalog/catalog_set.cpp index 2a7c5ba9e..1a039ba26 100644 --- a/src/duckdb/src/catalog/catalog_set.cpp +++ b/src/duckdb/src/catalog/catalog_set.cpp @@ -376,7 +376,7 @@ bool CatalogSet::AlterEntry(CatalogTransaction transaction, const Identifier &na unique_ptr entry_to_destroy; if (transaction.transaction) { // serialize the AlterInfo into a temporary buffer - MemoryStream stream(Allocator::Get(*transaction.db)); + MemoryStream stream(Allocator::Get(transaction.db)); BinarySerializer serializer(stream); serializer.Begin(); serializer.WriteProperty(100, "column_name", alter_info.GetColumnName()); diff --git a/src/duckdb/src/catalog/catalog_transaction.cpp b/src/duckdb/src/catalog/catalog_transaction.cpp index a470ce895..9b4c2e7ed 100644 --- a/src/duckdb/src/catalog/catalog_transaction.cpp +++ b/src/duckdb/src/catalog/catalog_transaction.cpp @@ -1,18 +1,19 @@ #include "duckdb/catalog/catalog_transaction.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/transaction/transaction.hpp" namespace duckdb { CatalogTransaction::CatalogTransaction(Catalog &catalog, ClientContext &context) - : db(&DatabaseInstance::GetDatabase(context)), context(&context), transaction(&Transaction::Get(context, catalog)), + : db(DatabaseInstance::GetDatabase(context)), context(&context), transaction(&Transaction::Get(context, catalog)), view(transaction->GetSnapshotView()) { } CatalogTransaction::CatalogTransaction(DatabaseInstance &db, transaction_t transaction_id_p, VisibilityBound visibility_bound_p) - : db(&db), context(nullptr), transaction(nullptr), view(transaction_id_p, visibility_bound_p) { + : db(db), context(nullptr), transaction(nullptr), view(transaction_id_p, visibility_bound_p) { } ClientContext &CatalogTransaction::GetContext() { @@ -26,6 +27,14 @@ CatalogTransaction CatalogTransaction::GetSystemCatalogTransaction(ClientContext return CatalogTransaction(Catalog::GetSystemCatalog(context), context); } +CatalogTransaction CatalogTransaction::GetSystemCatalogTransaction(Context &context) { + auto client_context = context.TryGetClientContext(); + if (client_context) { + return GetSystemCatalogTransaction(*client_context); + } + return GetSystemTransaction(context.GetDatabase()); +} + CatalogTransaction CatalogTransaction::GetSystemTransaction(DatabaseInstance &db) { return CatalogTransaction(db, SYSTEM_TRANSACTION_TIMESTAMP, VisibilityBound::Through(SYSTEM_TRANSACTION_TIMESTAMP)); } diff --git a/src/duckdb/src/catalog/default/default_types.cpp b/src/duckdb/src/catalog/default/default_types.cpp index 370633eb8..4e45d7bce 100644 --- a/src/duckdb/src/catalog/default/default_types.cpp +++ b/src/duckdb/src/catalog/default/default_types.cpp @@ -48,8 +48,8 @@ LogicalType BindDefaultDecimalType(BindLogicalTypeInput &input) { } LogicalType BindDecimalType(BindLogicalTypeInput &input) { - auto width = input.modifiers[0].GetValue().GetValue(); - auto scale = input.modifiers[1].GetValue().GetValue(); + auto width = input.modifiers[0].GetValue().GetValue(); + auto scale = input.modifiers[1].GetValue().GetValue(); if (width < 1 || width > Decimal::MAX_WIDTH_DECIMAL) { throw BinderException(input.GetLocation(0), "DECIMAL type width must be between 1 and %d", diff --git a/src/duckdb/src/common/arrow/arrow_converter.cpp b/src/duckdb/src/common/arrow/arrow_converter.cpp index 32192b016..1188752e2 100644 --- a/src/duckdb/src/common/arrow/arrow_converter.cpp +++ b/src/duckdb/src/common/arrow/arrow_converter.cpp @@ -242,7 +242,7 @@ void SetArrowFormat(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child, co child.format = "tin"; break; case LogicalTypeId::DECIMAL: { - uint8_t width, scale, bit_width; + uint32_t width, scale, bit_width; if (options.arrow_output_version <= ArrowFormatVersion::V1_4) { // Before version 1.4 all decimals were int128 bit_width = 128; diff --git a/src/duckdb/src/common/bind_helpers.cpp b/src/duckdb/src/common/bind_helpers.cpp index 74bfde8da..3957a0a02 100644 --- a/src/duckdb/src/common/bind_helpers.cpp +++ b/src/duckdb/src/common/bind_helpers.cpp @@ -24,6 +24,33 @@ Value ConvertVectorToValue(vector set) { return Value::LIST(std::move(set)); } +idx_t ParseBytesArg(const Identifier &name, const Value &arg) { + if (arg.IsNull()) { + throw BinderException("NULL is not supported as a valid option for COPY option \"%s\"", + StringUtil::Upper(name.GetIdentifierName())); + } + optional_idx result; + if (arg.type().id() == LogicalTypeId::VARCHAR) { + result = DBConfig::ParseMemoryLimit(arg.ToString()); + } else { + auto cast_arg = arg.DefaultTryCastAs(LogicalType::UBIGINT); + if (!cast_arg) { + throw BinderException("Unable to parse bytes from \"%s\" for copy option \"%s\" ", arg.ToString(), + StringUtil::Upper(name.GetIdentifierName())); + } + auto bytes = cast_arg->GetValue(); + if (bytes != DConstants::INVALID_INDEX) { + result = bytes; + } + } + if (!result.IsValid()) { + // e.g. '-1' or 'none', which ParseMemoryLimit parses as unlimited + throw BinderException("Copy option \"%s\" must be a valid size, not \"%s\"", + StringUtil::Upper(name.GetIdentifierName()), arg.ToString()); + } + return result.GetIndex(); +} + vector ParseColumnList(const vector &set, const vector &names, const Identifier &option_name) { vector result; diff --git a/src/duckdb/src/common/compressed_file_system.cpp b/src/duckdb/src/common/compressed_file_system.cpp index cbbe26606..97dcd81e5 100644 --- a/src/duckdb/src/common/compressed_file_system.cpp +++ b/src/duckdb/src/common/compressed_file_system.cpp @@ -74,8 +74,7 @@ void CompressedFile::Initialize(QueryContext context, bool write) { stream_data.in_buf_size, MinValue(REMOTE_READ_IN_BUF_SIZE, child_handle->GetFileSize())); } stream_data.out_buf_size = compressed_fs.OutBufferSize(); - auto &allocator = - context.Valid() ? BufferAllocator::Get(*context.GetClientContext()) : Allocator::DefaultAllocator(); + auto &allocator = context.Valid() ? BufferAllocator::Get(*context.GetContext()) : Allocator::DefaultAllocator(); stream_data.in_buff = allocator.Allocate(stream_data.in_buf_size); stream_data.in_buff_start = stream_data.in_buff.get(); stream_data.in_buff_end = stream_data.in_buff.get(); diff --git a/src/duckdb/src/common/csv_writer.cpp b/src/duckdb/src/common/csv_writer.cpp index 56bef0a57..719f694e4 100644 --- a/src/duckdb/src/common/csv_writer.cpp +++ b/src/duckdb/src/common/csv_writer.cpp @@ -25,12 +25,7 @@ CSVWriterState::CSVWriterState(DatabaseInstance &db, idx_t flush_size_p) : flush_size(flush_size_p), stream(make_uniq(BufferAllocator::Get(db), flush_size)) { } -CSVWriterState::~CSVWriterState() { - if (stream && !Exception::UncaughtException()) { - // Ensure we don't accidentally destroy unflushed data - D_ASSERT(stream->GetPosition() == 0); - } -} +CSVWriterState::~CSVWriterState() = default; CSVWriterOptions::CSVWriterOptions(const string &delim, const char "e, const string &write_newline, char comment_char) { diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index a24553067..6a4e389ee 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -2621,20 +2621,19 @@ const StringUtil::EnumStringLiteral *GetExternalResourceOperationValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(ExternalResourceOperation::CREATE), "CREATE" }, { static_cast(ExternalResourceOperation::REGISTER), "REGISTER" }, - { static_cast(ExternalResourceOperation::DESTROY), "DESTROY" }, - { static_cast(ExternalResourceOperation::SHOW), "SHOW" } + { static_cast(ExternalResourceOperation::DESTROY), "DESTROY" } }; return values; } template<> const char* EnumUtil::ToChars(ExternalResourceOperation value) { - return StringUtil::EnumToString(GetExternalResourceOperationValues(), 4, "ExternalResourceOperation", static_cast(value)); + return StringUtil::EnumToString(GetExternalResourceOperationValues(), 3, "ExternalResourceOperation", static_cast(value)); } template<> ExternalResourceOperation EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetExternalResourceOperationValues(), 4, "ExternalResourceOperation", value)); + return static_cast(StringUtil::StringToEnum(GetExternalResourceOperationValues(), 3, "ExternalResourceOperation", value)); } const StringUtil::EnumStringLiteral *GetExtraDropInfoTypeValues() { @@ -2660,19 +2659,20 @@ const StringUtil::EnumStringLiteral *GetExtraPersistentColumnDataTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(ExtraPersistentColumnDataType::INVALID), "INVALID" }, { static_cast(ExtraPersistentColumnDataType::VARIANT), "VARIANT" }, - { static_cast(ExtraPersistentColumnDataType::GEOMETRY), "GEOMETRY" } + { static_cast(ExtraPersistentColumnDataType::GEOMETRY), "GEOMETRY" }, + { static_cast(ExtraPersistentColumnDataType::LIST), "LIST" } }; return values; } template<> const char* EnumUtil::ToChars(ExtraPersistentColumnDataType value) { - return StringUtil::EnumToString(GetExtraPersistentColumnDataTypeValues(), 3, "ExtraPersistentColumnDataType", static_cast(value)); + return StringUtil::EnumToString(GetExtraPersistentColumnDataTypeValues(), 4, "ExtraPersistentColumnDataType", static_cast(value)); } template<> ExtraPersistentColumnDataType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetExtraPersistentColumnDataTypeValues(), 3, "ExtraPersistentColumnDataType", value)); + return static_cast(StringUtil::StringToEnum(GetExtraPersistentColumnDataTypeValues(), 4, "ExtraPersistentColumnDataType", value)); } const StringUtil::EnumStringLiteral *GetFileBufferTypeValues() { @@ -4645,19 +4645,21 @@ const StringUtil::EnumStringLiteral *GetOptimizerTypeValues() { { static_cast(OptimizerType::REDUNDANT_ORDER_KEYS), "REDUNDANT_ORDER_KEYS" }, { static_cast(OptimizerType::DISJUNCTIVE_JOIN_REWRITER), "DISJUNCTIVE_JOIN_REWRITER" }, { static_cast(OptimizerType::REDUNDANT_ORDER), "REDUNDANT_ORDER" }, - { static_cast(OptimizerType::WINDOW_JOIN_PUSHDOWN), "WINDOW_JOIN_PUSHDOWN" } + { 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" } }; return values; } template<> const char* EnumUtil::ToChars(OptimizerType value) { - return StringUtil::EnumToString(GetOptimizerTypeValues(), 50, "OptimizerType", static_cast(value)); + return StringUtil::EnumToString(GetOptimizerTypeValues(), 52, "OptimizerType", static_cast(value)); } template<> OptimizerType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 50, "OptimizerType", value)); + return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 52, "OptimizerType", value)); } const StringUtil::EnumStringLiteral *GetOrderByColumnTypeValues() { @@ -5216,6 +5218,24 @@ PipelineInputMode EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetPipelineInputModeValues(), 2, "PipelineInputMode", value)); } +const StringUtil::EnumStringLiteral *GetPipelineScheduleGraphValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(PipelineScheduleGraph::SCHEDULED), "SCHEDULED" }, + { static_cast(PipelineScheduleGraph::WITH_ANALYSIS), "WITH_ANALYSIS" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(PipelineScheduleGraph value) { + return StringUtil::EnumToString(GetPipelineScheduleGraphValues(), 2, "PipelineScheduleGraph", static_cast(value)); +} + +template<> +PipelineScheduleGraph EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetPipelineScheduleGraphValues(), 2, "PipelineScheduleGraph", value)); +} + const StringUtil::EnumStringLiteral *GetPipelineScheduleModeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(PipelineScheduleMode::COMPLETE), "COMPLETE" }, @@ -5580,6 +5600,7 @@ const StringUtil::EnumStringLiteral *GetRecursiveCTESourcePhaseValues() { { static_cast(RecursiveCTESourcePhase::INITIAL), "INITIAL" }, { static_cast(RecursiveCTESourcePhase::SCANNING_UNION), "SCANNING_UNION" }, { static_cast(RecursiveCTESourcePhase::RECURSING_KEY), "RECURSING_KEY" }, + { static_cast(RecursiveCTESourcePhase::EXECUTING_RECURSION), "EXECUTING_RECURSION" }, { static_cast(RecursiveCTESourcePhase::DRAINING_FINAL_KEY_STATE), "DRAINING_FINAL_KEY_STATE" }, { static_cast(RecursiveCTESourcePhase::FINISHED), "FINISHED" } }; @@ -5588,12 +5609,51 @@ const StringUtil::EnumStringLiteral *GetRecursiveCTESourcePhaseValues() { template<> const char* EnumUtil::ToChars(RecursiveCTESourcePhase value) { - return StringUtil::EnumToString(GetRecursiveCTESourcePhaseValues(), 5, "RecursiveCTESourcePhase", static_cast(value)); + return StringUtil::EnumToString(GetRecursiveCTESourcePhaseValues(), 6, "RecursiveCTESourcePhase", static_cast(value)); } template<> RecursiveCTESourcePhase EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetRecursiveCTESourcePhaseValues(), 5, "RecursiveCTESourcePhase", value)); + return static_cast(StringUtil::StringToEnum(GetRecursiveCTESourcePhaseValues(), 6, "RecursiveCTESourcePhase", value)); +} + +const StringUtil::EnumStringLiteral *GetRecursiveCTEStageStepValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(RecursiveCTEStageStep::START), "START" }, + { static_cast(RecursiveCTEStageStep::PIPELINE_RUNNING), "PIPELINE_RUNNING" }, + { static_cast(RecursiveCTEStageStep::EVENT_WAIT), "EVENT_WAIT" }, + { static_cast(RecursiveCTEStageStep::FINISH_FINALIZE), "FINISH_FINALIZE" }, + { static_cast(RecursiveCTEStageStep::FINISH_EVENT_WAIT), "FINISH_EVENT_WAIT" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(RecursiveCTEStageStep value) { + return StringUtil::EnumToString(GetRecursiveCTEStageStepValues(), 5, "RecursiveCTEStageStep", static_cast(value)); +} + +template<> +RecursiveCTEStageStep EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetRecursiveCTEStageStepValues(), 5, "RecursiveCTEStageStep", value)); +} + +const StringUtil::EnumStringLiteral *GetRecursiveEpochResultValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(RecursiveEpochResult::COMPLETE), "COMPLETE" }, + { static_cast(RecursiveEpochResult::BLOCKED), "BLOCKED" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(RecursiveEpochResult value) { + return StringUtil::EnumToString(GetRecursiveEpochResultValues(), 2, "RecursiveEpochResult", static_cast(value)); +} + +template<> +RecursiveEpochResult EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetRecursiveEpochResultValues(), 2, "RecursiveEpochResult", value)); } const StringUtil::EnumStringLiteral *GetRecursiveProbeSidePreferenceValues() { @@ -6111,6 +6171,7 @@ const StringUtil::EnumStringLiteral *GetSerializationVersionDeprecatedValues() { { static_cast(SerializationVersionDeprecated::V1_5_5), "V1_5_5" }, { static_cast(SerializationVersionDeprecated::V1_5_6), "V1_5_6" }, { static_cast(SerializationVersionDeprecated::V2_0_0), "V2_0_0" }, + { static_cast(SerializationVersionDeprecated::V2_0_1), "V2_0_1" }, { static_cast(SerializationVersionDeprecated::V2_1_0), "V2_1_0" }, { static_cast(SerializationVersionDeprecated::LATEST), "LATEST" }, { static_cast(SerializationVersionDeprecated::INVALID), "INVALID" } @@ -6120,12 +6181,12 @@ const StringUtil::EnumStringLiteral *GetSerializationVersionDeprecatedValues() { template<> const char* EnumUtil::ToChars(SerializationVersionDeprecated value) { - return StringUtil::EnumToString(GetSerializationVersionDeprecatedValues(), 32, "SerializationVersionDeprecated", static_cast(value)); + return StringUtil::EnumToString(GetSerializationVersionDeprecatedValues(), 33, "SerializationVersionDeprecated", static_cast(value)); } template<> SerializationVersionDeprecated EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetSerializationVersionDeprecatedValues(), 32, "SerializationVersionDeprecated", value)); + return static_cast(StringUtil::StringToEnum(GetSerializationVersionDeprecatedValues(), 33, "SerializationVersionDeprecated", value)); } const StringUtil::EnumStringLiteral *GetSetOperationTypeValues() { @@ -6690,6 +6751,7 @@ const StringUtil::EnumStringLiteral *GetStorageVersionValues() { { static_cast(StorageVersion::V1_5_5), "V1_5_5" }, { static_cast(StorageVersion::V1_5_6), "V1_5_6" }, { static_cast(StorageVersion::V2_0_0), "V2_0_0" }, + { static_cast(StorageVersion::V2_0_1), "V2_0_1" }, { static_cast(StorageVersion::V2_1_0), "V2_1_0" }, { static_cast(StorageVersion::LATEST), "LATEST" }, { static_cast(StorageVersion::DEPRECATED), "DEPRECATED" }, @@ -6700,12 +6762,12 @@ const StringUtil::EnumStringLiteral *GetStorageVersionValues() { template<> const char* EnumUtil::ToChars(StorageVersion value) { - return StringUtil::EnumToString(GetStorageVersionValues(), 72, "StorageVersion", static_cast(value)); + return StringUtil::EnumToString(GetStorageVersionValues(), 73, "StorageVersion", static_cast(value)); } template<> StorageVersion EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetStorageVersionValues(), 72, "StorageVersion", value)); + return static_cast(StringUtil::StringToEnum(GetStorageVersionValues(), 73, "StorageVersion", value)); } const StringUtil::EnumStringLiteral *GetStrTimeSpecifierValues() { @@ -7149,6 +7211,28 @@ TransactionType EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetTransactionTypeValues(), 4, "TransactionType", value)); } +const StringUtil::EnumStringLiteral *GetTransformChildKindValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(TransformChildKind::REQUIRED), "REQUIRED" }, + { static_cast(TransformChildKind::OPTIONAL), "OPTIONAL" }, + { static_cast(TransformChildKind::LIST), "LIST" }, + { static_cast(TransformChildKind::OPTIONAL_LIST), "OPTIONAL_LIST" }, + { static_cast(TransformChildKind::REPEAT), "REPEAT" }, + { static_cast(TransformChildKind::OPTIONAL_REPEAT), "OPTIONAL_REPEAT" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(TransformChildKind value) { + return StringUtil::EnumToString(GetTransformChildKindValues(), 6, "TransformChildKind", static_cast(value)); +} + +template<> +TransformChildKind EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetTransformChildKindValues(), 6, "TransformChildKind", value)); +} + const StringUtil::EnumStringLiteral *GetTriggerEventTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(TriggerEventType::INSERT_EVENT), "INSERT" }, diff --git a/src/duckdb/src/common/enums/optimizer_type.cpp b/src/duckdb/src/common/enums/optimizer_type.cpp index a41da18d3..c6b797f5e 100644 --- a/src/duckdb/src/common/enums/optimizer_type.cpp +++ b/src/duckdb/src/common/enums/optimizer_type.cpp @@ -62,6 +62,8 @@ static const DefaultOptimizerType internal_optimizer_types[] = { {"redundant_order_keys", OptimizerType::REDUNDANT_ORDER_KEYS}, {"disjunctive_join_rewriter", OptimizerType::DISJUNCTIVE_JOIN_REWRITER}, {"redundant_order", OptimizerType::REDUNDANT_ORDER}, + {"self_join_aggregate", OptimizerType::SELF_JOIN_AGGREGATE}, + {"scalar_aggregate_merge", OptimizerType::SCALAR_AGGREGATE_MERGE}, {nullptr, OptimizerType::INVALID}}; string OptimizerTypeToString(OptimizerType type) { diff --git a/src/duckdb/src/common/file_system.cpp b/src/duckdb/src/common/file_system.cpp index 04a78aaa0..83b5da215 100644 --- a/src/duckdb/src/common/file_system.cpp +++ b/src/duckdb/src/common/file_system.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/checksum.hpp" @@ -103,8 +104,7 @@ FileSystem::~FileSystem() { } FileSystem &FileSystem::GetFileSystem(ClientContext &context) { - auto &client_data = ClientData::Get(context); - return *client_data.client_file_system; + return context.GetContext().GetFileSystem(); } bool PathMatched(const string &path, const string &sub_path) { @@ -747,6 +747,10 @@ void FileSystem::SetDisabledFileSystems(const vector &names) { throw NotImplementedException("%s: Can't disable file systems on a non-virtual file system", GetName()); } +vector FileSystem::GetDisabledFileSystems() { + return vector(); +} + bool FileSystem::SubSystemIsDisabled(const string &name) { throw NotImplementedException("%s: Non-virtual file system does not have subsystems", GetName()); } @@ -842,16 +846,23 @@ int64_t FileHandle::Read(void *buffer, idx_t nr_bytes) { return file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); } +static optional_ptr GetTrackingProfiler(bool track_io, const QueryContext &context) { + if (!track_io || !context.Valid()) { + return nullptr; + } + return context.GetContext()->TryGetQueryProfiler(); +} + int64_t FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes) { - const bool track = track_io && context.GetClientContext(); + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); // A sequential read can return fewer bytes than requested (e.g. at EOF), so track the bytes // actually read rather than the requested amount. auto bytes_read = file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); if (track) { const auto elapsed_us = NumericCast(start.ElapsedMicros()); - QueryProfiler::Get(*context.GetClientContext()) - .TrackBytesRead(UnsafeNumericCast(bytes_read), elapsed_us); + profiler->TrackBytesRead(UnsafeNumericCast(bytes_read), elapsed_us); } return bytes_read; @@ -866,13 +877,13 @@ int64_t FileHandle::Write(void *buffer, idx_t nr_bytes) { } int64_t FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes) { - const bool track = track_io && context.GetClientContext(); + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); auto bytes_written = file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes)); if (bytes_written > 0 && track) { const auto elapsed_us = NumericCast(start.ElapsedMicros()); - QueryProfiler::Get(*context.GetClientContext()) - .TrackBytesWritten(UnsafeNumericCast(bytes_written), elapsed_us); + profiler->TrackBytesWritten(UnsafeNumericCast(bytes_written), elapsed_us); } return bytes_written; @@ -883,22 +894,24 @@ void FileHandle::Read(void *buffer, idx_t nr_bytes, idx_t location) { } void FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { - const bool track = track_io && context.GetClientContext(); + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes), location); if (track) { const auto elapsed_us = NumericCast(start.ElapsedMicros()); - QueryProfiler::Get(*context.GetClientContext()).TrackBytesRead(nr_bytes, elapsed_us); + profiler->TrackBytesRead(nr_bytes, elapsed_us); } } void FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { - const bool track = track_io && context.GetClientContext(); + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes), location); if (track) { const auto elapsed_us = NumericCast(start.ElapsedMicros()); - QueryProfiler::Get(*context.GetClientContext()).TrackBytesWritten(nr_bytes, elapsed_us); + profiler->TrackBytesWritten(nr_bytes, elapsed_us); } } @@ -995,9 +1008,9 @@ void FileHandle::TryAddLogger(FileOpener &opener) { return; } - auto context = opener.TryGetClientContext(); - if (context && Logger::Get(*context).ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { - logger = context->logger; + auto &context = opener.TryGetContext(); + if (context.IsClient() && context.GetLogger().ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { + logger = context.GetLoggerPtr(); return; } diff --git a/src/duckdb/src/common/local_file_system.cpp b/src/duckdb/src/common/local_file_system.cpp index a1a35e84e..3113c2484 100644 --- a/src/duckdb/src/common/local_file_system.cpp +++ b/src/duckdb/src/common/local_file_system.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/local_file_system.hpp" #include "duckdb/common/checksum.hpp" @@ -6,6 +7,7 @@ #include "duckdb/common/file_opener.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/memory_mapped_file.hpp" +#include "duckdb/common/operator/add.hpp" #include "duckdb/common/process_util.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/thread.hpp" @@ -241,7 +243,16 @@ static void CloseFileAndAppendError(int fd, string &extended_error) { static FileMetadata StatsFromStruct(struct stat s) { FileMetadata file_metadata; file_metadata.file_size = s.st_size; - file_metadata.last_modification_time = Timestamp::FromEpochSeconds(s.st_mtime); +#ifdef __APPLE__ + const auto &modification_time = s.st_mtimespec; +#else + const auto &modification_time = s.st_mtim; +#endif + // with the fraction of a second, so that a file rewritten within the same second gets another version tag + const auto modification_seconds = Timestamp::FromEpochSeconds(static_cast(modification_time.tv_sec)); + file_metadata.last_modification_time = + Timestamp::FromEpochMicroSeconds(AddOperatorOverflowCheck::Operation( + modification_seconds.value, static_cast(modification_time.tv_nsec) / Interval::NANOS_PER_MICRO)); file_metadata.device_id = static_cast(s.st_dev); file_metadata.file_id = static_cast(s.st_ino); @@ -1745,7 +1756,9 @@ optional LocalFileSystem::GetStatsIfExists(const OpenFileInfo &fil OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (raw_handle == INVALID_HANDLE_VALUE) { auto error_code = GetLastError(); - if (error_code == ERROR_FILE_NOT_FOUND || error_code == ERROR_PATH_NOT_FOUND) { + // a name that cannot be a local file does not exist, as for ENOENT and ENOTDIR + if (error_code == ERROR_FILE_NOT_FOUND || error_code == ERROR_PATH_NOT_FOUND || + error_code == ERROR_INVALID_NAME || error_code == ERROR_BAD_PATHNAME || error_code == ERROR_DIRECTORY) { return nullopt; } SetLastError(error_code); @@ -2161,7 +2174,21 @@ static bool IsSymbolicLink(const string &path) { vector LocalFileSystem::FetchFileWithoutGlob(const string &path, optional_ptr opener, bool absolute_path) { vector result; - if (FileExists(path, opener) || IsPipe(path, opener)) { + // a regular file comes with its type, size, modification time and version tag, as from a glob + auto add_file = [&](const string &file_path) { + OpenFileInfo info(file_path); + auto file_metadata = GetStatsIfExists(info, opener); + if (file_metadata) { + info.extended_info = make_shared_ptr(); + auto &options = info.extended_info->options; + options.emplace("type", Value("file")); + FillFileOptions(*file_metadata, options); + } + result.push_back(std::move(info)); + }; + if (FileExists(path, opener)) { + add_file(path); + } else if (IsPipe(path, opener)) { result.emplace_back(path); } else if (!absolute_path) { Value value; @@ -2170,7 +2197,9 @@ vector LocalFileSystem::FetchFileWithoutGlob(const string &path, o vector search_paths = StringUtil::Split(search_paths_str, ','); for (const auto &search_path : search_paths) { auto joined_path = JoinPath(search_path, path); - if (FileExists(joined_path, opener) || IsPipe(joined_path, opener)) { + if (FileExists(joined_path, opener)) { + add_file(joined_path); + } else if (IsPipe(joined_path, opener)) { result.emplace_back(joined_path); } } @@ -2260,7 +2289,7 @@ struct LocalGlobResult : public LazyMultiFileList { LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, FileGlobOptions options_p, optional_ptr opener) - : LazyMultiFileList(FileOpener::TryGetClientContext(opener)), fs(fs), path(fs.ExpandPath(path_p, opener)), + : LazyMultiFileList(FileOpener::TryGetContext(opener)), fs(fs), path(fs.ExpandPath(path_p, opener)), opener(opener) { if (path.empty()) { finished = true; diff --git a/src/duckdb/src/common/logical_type_info.cpp b/src/duckdb/src/common/logical_type_info.cpp index 1545d8ef6..de83239cc 100644 --- a/src/duckdb/src/common/logical_type_info.cpp +++ b/src/duckdb/src/common/logical_type_info.cpp @@ -136,7 +136,7 @@ bool LogicalTypeInfo::EqualsInternal(const LogicalTypeInfo *other_p) const { DecimalTypeInfo::DecimalTypeInfo() : LogicalTypeInfo(LogicalTypeInfoType::DECIMAL_TYPE_INFO) { } -DecimalTypeInfo::DecimalTypeInfo(uint8_t width_p, uint8_t scale_p) +DecimalTypeInfo::DecimalTypeInfo(uint32_t width_p, uint32_t scale_p) : LogicalTypeInfo(LogicalTypeInfoType::DECIMAL_TYPE_INFO), width(width_p), scale(scale_p) { D_ASSERT(width_p >= scale_p); } diff --git a/src/duckdb/src/common/multi_file/base_file_reader.cpp b/src/duckdb/src/common/multi_file/base_file_reader.cpp index d42cbf29d..1961d6ea9 100644 --- a/src/duckdb/src/common/multi_file/base_file_reader.cpp +++ b/src/duckdb/src/common/multi_file/base_file_reader.cpp @@ -45,4 +45,8 @@ unique_ptr BaseUnionData::GetStatistics(ClientContext &context, return nullptr; } +unique_ptr BaseUnionData::GetVirtualColumnStatistics(ClientContext &, column_t) { + return nullptr; +} + } // namespace duckdb diff --git a/src/duckdb/src/common/multi_file/multi_file_list.cpp b/src/duckdb/src/common/multi_file/multi_file_list.cpp index 38ecf87cb..2f91401ce 100644 --- a/src/duckdb/src/common/multi_file/multi_file_list.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_list.cpp @@ -11,6 +11,7 @@ #include #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { @@ -238,6 +239,28 @@ bool MultiFileList::IsEmpty() const { return GetExpandResult() == FileExpandResult::NO_FILES; } +optional_idx MultiFileList::EstimateRowsPerFile(idx_t bytes_per_row) const { + D_ASSERT(bytes_per_row > 0); + MultiFileListScanData scan_data; + scan_data.scan_type = MultiFileListScanType::FETCH_IF_AVAILABLE; + InitializeScan(scan_data); + OpenFileInfo file; + idx_t file_count = 0; + idx_t row_count = 0; + while (Scan(scan_data, file)) { + idx_t file_size; + if (!file.extended_info || !file.extended_info->TryGetOption("file_size", file_size)) { + return optional_idx(); + } + row_count += MaxValue(file_size / bytes_per_row, 1); + file_count++; + } + if (file_count == 0) { + return optional_idx(); + } + return row_count / file_count; +} + unique_ptr MultiFileList::Copy() const { return make_uniq(GetAllFiles()); } @@ -281,7 +304,7 @@ idx_t SimpleMultiFileList::GetTotalFileCount() const { //===--------------------------------------------------------------------===// // LazyFileList //===--------------------------------------------------------------------===// -LazyMultiFileList::LazyMultiFileList(optional_ptr context_p) : context(context_p) { +LazyMultiFileList::LazyMultiFileList(optional_ptr services_p) : services(services_p) { } vector LazyMultiFileList::GetAllFiles() const { @@ -340,7 +363,7 @@ bool LazyMultiFileList::ExpandNextPathInternal() const { if (all_files_expanded) { return false; } - if (context && context->IsInterrupted()) { + if (services && services->IsInterrupted()) { throw InterruptException(); } if (!ExpandNextPath()) { @@ -367,8 +390,8 @@ GlobMultiFileList::GlobMultiFileList(ClientContext &context_p, vector gl } GlobMultiFileList::GlobMultiFileList(ClientContext &context_p, vector globs_p, FileGlobInput glob_input_p) - : LazyMultiFileList(&context_p), context(context_p), globs(std::move(globs_p)), glob_input(std::move(glob_input_p)), - current_glob(0) { + : LazyMultiFileList(&context_p.GetContext()), context(context_p), globs(std::move(globs_p)), + glob_input(std::move(glob_input_p)), current_glob(0) { } vector GlobMultiFileList::GetDisplayFileList(optional_idx max_files) const { diff --git a/src/duckdb/src/common/multi_file/multi_file_reader.cpp b/src/duckdb/src/common/multi_file/multi_file_reader.cpp index 4e3be75b9..80cde8d24 100644 --- a/src/duckdb/src/common/multi_file/multi_file_reader.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_reader.cpp @@ -94,7 +94,7 @@ bool MultiFileBindData::MatchesPhysicalColumn(idx_t column_idx, const Identifier } bool MultiFileBindData::HasIdentityMapping(const vector &physical_columns) const { - if (physical_columns.size() != names.size() || physical_columns.size() != types.size()) { + if (physical_columns.size() > names.size() || names.size() != types.size()) { return false; } for (idx_t i = 0; i < physical_columns.size(); i++) { @@ -102,6 +102,12 @@ bool MultiFileBindData::HasIdentityMapping(const vector(); } else if (key == "hive_types_autocast" || key == "hive_type_autocast") { if (val.IsNull()) { throw InvalidInputException("Cannot use NULL as argument for %s", key); @@ -1067,7 +1078,41 @@ MultiFileReaderBindData MultiFileReader::BindReader(ClientContext &context, vect if (file_options.maximum_sample_files > 1) { return BindSampledReader(context, return_types, names, files, result, options, file_options); } - return BindFirstReader(context, return_types, names, files, result, options, file_options); + auto bind_data = BindFirstReader(context, return_types, names, files, result, options, file_options); + ReadFilesForStatistics(context, files, result, options, file_options); + return bind_data; +} + +void MultiFileReader::ReadFilesForStatistics(ClientContext &context, MultiFileList &files, MultiFileBindData &result, + BaseFileReaderOptions &options, MultiFileOptions &file_options) { + auto max_files = file_options.maximum_files_for_stats; + if (max_files == 0 || !result.union_readers.empty()) { + return; + } + // a single file bound on its own already has its statistics from the initial reader + const idx_t min_files = result.initial_reader ? 2 : 1; + auto count = files.GetFileCount(max_files + 1); + if (count.type != FileExpansionType::ALL_FILES_EXPANDED || count.count < min_files || count.count > max_files) { + return; + } + // an open first file is reused: only the others are read. A file that cannot be read gives no statistics rather + // than failing the bind: the scan reports it + auto all_files = files.GetAllFiles(); + if (result.initial_reader && result.initial_reader->GetFileName() != all_files[0].path) { + return; + } + vector unread_files(all_files.begin() + (result.initial_reader ? 1 : 0), all_files.end()); + auto readers = UnionByName::ReadUnionData(context, unread_files, options, file_options, *this, *result.interface, + true, TaskSchedulerType::ASYNC); + for (auto &reader : readers) { + if (!reader) { + return; + } + } + if (result.initial_reader) { + readers.insert(readers.begin(), result.initial_reader->GetUnionData(0)); + } + std::move(readers.begin(), readers.end(), std::back_inserter(result.union_readers)); } MultiFileReaderBindData MultiFileReader::BindFirstReader(ClientContext &context, vector &return_types, 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 bf00460c4..31ea7893c 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 @@ -1,4 +1,5 @@ #include "duckdb/common/multi_file/table_function_multi_file.hpp" +#include "duckdb/common/operator/add.hpp" #include @@ -171,6 +172,14 @@ unique_ptr TableFunctionUnionData::GetStatistics(ClientContext & return nullptr; } +unique_ptr TableFunctionUnionData::GetVirtualColumnStatistics(ClientContext &context, + column_t virtual_column_id) { + if (!statistics || !bind_data) { + return nullptr; + } + return statistics(context, bind_data.get(), virtual_column_id); +} + shared_ptr TableFunctionFileReader::GetUnionData(idx_t file_idx) { auto result = make_shared_ptr(file); result->names = IdentifiersToStrings(names); @@ -591,12 +600,23 @@ void TableFunctionMultiFileWrapper::GetVirtualColumns(ClientContext &context, Mu } } +void TableFunctionMultiFileWrapper::ReadFilesForStatistics(ClientContext &context, MultiFileBindData &bind_data) { + auto &data = bind_data.bind_data->Cast(); + bind_data.multi_file_reader->ReadFilesForStatistics(context, *bind_data.file_list, bind_data, data.options, + bind_data.file_options); +} + void TableFunctionMultiFileWrapper::FinalizeBindData(MultiFileBindData &multi_file_data) { auto &data = multi_file_data.bind_data->Cast(); if (multi_file_data.initial_reader) { // the cardinality estimate comes from the first file - keep it, as a filter pushdown can prune that file's // reader before the optimizer asks for the estimate data.cardinality = multi_file_data.initial_reader->Cast().GetCardinality(); + if (multi_file_data.union_readers.empty()) { + auto file = multi_file_data.initial_reader->GetUnionData(0); + file->reader.reset(); + multi_file_data.union_readers.push_back(std::move(file)); + } } if (!multi_file_data.file_options.schema.empty()) { // the schema was given up front, so BindReader never ran to find out whether the scan reads several files @@ -716,14 +736,79 @@ shared_ptr TableFunctionMultiFileWrapper::CreateReader(ClientCon return std::move(result); } +//! The bytes a row is taken to have when a scan's row count is estimated from the sizes of its files alone: the +//! floor the parquet reader puts under the ratio it measures in an opened file. A deliberate overestimate of the rows, +//! the same for every format this wrapper serves - a read_csv or read_json row is typically much wider - since +//! estimating too many rows is safer than estimating none. +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) { + 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(); + if (cardinality == 0) { + return optional_idx(); + } + return optional_idx(cardinality); +} + unique_ptr TableFunctionMultiFileWrapper::GetCardinality(ClientContext &context, const MultiFileBindData &bind_data, idx_t file_count) { + if (bind_data.file_list->IsEmpty()) { + return make_uniq(idx_t(0), idx_t(0)); + } auto &data = bind_data.bind_data->Cast(); - if (!data.cardinality.IsValid()) { + auto result = make_uniq(); + auto explicit_cardinality = ExplicitCardinality(data); + if (explicit_cardinality.IsValid()) { + result->has_estimated_cardinality = true; + result->estimated_cardinality = explicit_cardinality.GetIndex(); + } else if (data.cardinality.IsValid()) { + result->has_estimated_cardinality = true; + result->estimated_cardinality = data.cardinality.GetIndex() * file_count; + } else { + // no file was opened at bind (e.g. because the schema was given): estimate from the sizes of the files, when + // the file list carries them (a local glob, or a list of {filename, file_size} structs) + auto rows_per_file = bind_data.file_list->EstimateRowsPerFile(MIN_ESTIMATED_BYTES_PER_ROW); + if (rows_per_file.IsValid()) { + result->has_estimated_cardinality = true; + result->estimated_cardinality = rows_per_file.GetIndex() * file_count; + } + } + const bool single_file_opened = + !bind_data.file_options.union_by_name && bind_data.union_readers.size() == 1 && + bind_data.file_list->GetExpandResult() == FileExpandResult::SINGLE_FILE && + bind_data.union_readers[0]->GetFileName() == bind_data.file_list->GetFirstFile().path; + const bool all_files_opened = !bind_data.union_readers.empty() && + (bind_data.file_options.union_by_name || bind_data.union_readers.size() > 1) && + bind_data.union_readers.size() == bind_data.file_list->GetTotalFileCount(); + if (function.cardinality && (single_file_opened || all_files_opened)) { + // the bound is the sum of what each opened file proves it holds + idx_t maximum = 0; + bool has_maximum = true; + for (auto &union_data : bind_data.union_readers) { + auto &file = union_data->Cast(); + auto stats = file.bind_data ? function.cardinality(context, file.bind_data.get()) : nullptr; + if (!stats || !stats->has_max_cardinality || + !TryAddOperator::Operation(maximum, stats->max_cardinality, maximum)) { + has_maximum = false; + break; + } + } + if (has_maximum) { + result->has_max_cardinality = true; + result->max_cardinality = maximum; + } + } + if (!result->has_estimated_cardinality && !result->has_max_cardinality) { return nullptr; } - return make_uniq(data.cardinality.GetIndex() * file_count); + return result; } //===--------------------------------------------------------------------===// @@ -813,16 +898,19 @@ vector TableFunctionMultiFileWrapper::GetPartitionStats(Cli GetPartitionStatsInput &input) { vector result; auto &bind_data = input.bind_data->Cast(); - if (bind_data.file_list->GetExpandResult() != FileExpandResult::SINGLE_FILE || !bind_data.initial_reader) { + if (bind_data.file_list->GetExpandResult() != FileExpandResult::SINGLE_FILE || + bind_data.union_readers.size() != 1) { return result; } - auto &reader = bind_data.initial_reader->Cast(); - auto &function = reader.GetFunction(); - if (!function.get_partition_stats || !reader.bind_data) { + auto &file = bind_data.union_readers[0]->Cast(); + DynamicCastCheck(bind_data.interface.get()); + auto &wrapper = static_cast(*bind_data.interface); + auto &function = wrapper.function; + if (!function.get_partition_stats || !file.bind_data) { return result; } BoundTableFunction bound_function(function); - GetPartitionStatsInput file_input(bound_function, reader.bind_data.get()); + GetPartitionStatsInput file_input(bound_function, file.bind_data.get()); return function.get_partition_stats(context, file_input); } @@ -853,6 +941,9 @@ TableFunction TableFunctionMultiFileWrapper::CreateFunction(TableFunction single result.filter_prune = single_file_function.filter_prune; result.supports_pushdown_type = single_file_function.supports_pushdown_type; result.late_materialization = single_file_function.late_materialization; + // the declared stability of the wrapped function describes its executions independently of the file list, so it + // carries over to the multi-file scan - an explicitly volatile declaration is never upgraded + result.stability = single_file_function.stability; if (single_file_function.get_partition_stats) { // the row groups of the scan are those of its files result.get_partition_stats = GetPartitionStats; diff --git a/src/duckdb/src/common/multi_file/union_by_name.cpp b/src/duckdb/src/common/multi_file/union_by_name.cpp index 5226970fb..a04d50687 100644 --- a/src/duckdb/src/common/multi_file/union_by_name.cpp +++ b/src/duckdb/src/common/multi_file/union_by_name.cpp @@ -1,6 +1,7 @@ #include "duckdb/common/multi_file/union_by_name.hpp" #include "duckdb/common/multi_file/multi_file_function.hpp" #include "duckdb/parallel/task_executor.hpp" +#include "duckdb/common/error_data.hpp" namespace duckdb { @@ -9,14 +10,24 @@ class UnionByReaderTask : public BaseExecutorTask { UnionByReaderTask(TaskExecutor &executor, ClientContext &context, const OpenFileInfo &file, idx_t file_idx, vector> &readers, BaseFileReaderOptions &options, MultiFileOptions &file_options, MultiFileReader &multi_file_reader, - MultiFileReaderInterface &interface) + MultiFileReaderInterface &interface, bool ignore_errors) : BaseExecutorTask(executor), context(context), file(file), file_idx(file_idx), readers(readers), - options(options), file_options(file_options), multi_file_reader(multi_file_reader), interface(interface) { + options(options), file_options(file_options), multi_file_reader(multi_file_reader), interface(interface), + ignore_errors(ignore_errors) { } void ExecuteTask() override { - auto reader = multi_file_reader.CreateReader(context, file, options, file_options, interface); - readers[file_idx] = reader->GetUnionData(file_idx); + try { + auto reader = multi_file_reader.CreateReader(context, file, options, file_options, interface); + if (reader) { + readers[file_idx] = reader->GetUnionData(file_idx); + } + } catch (std::exception &ex) { + ErrorData error(ex); + if (!ignore_errors || error.Type() == ExceptionType::INTERRUPT) { + throw; + } + } } string TaskType() const override { @@ -32,26 +43,35 @@ class UnionByReaderTask : public BaseExecutorTask { MultiFileOptions &file_options; MultiFileReader &multi_file_reader; MultiFileReaderInterface &interface; + bool ignore_errors; }; -vector> UnionByName::UnionCols(ClientContext &context, const vector &files, - vector &union_col_types, - vector &union_col_names, - BaseFileReaderOptions &options, MultiFileOptions &file_options, - MultiFileReader &multi_file_reader, - MultiFileReaderInterface &interface) { +vector> +UnionByName::ReadUnionData(ClientContext &context, const vector &files, BaseFileReaderOptions &options, + MultiFileOptions &file_options, MultiFileReader &multi_file_reader, + MultiFileReaderInterface &interface, bool ignore_errors, TaskSchedulerType scheduler_type) { vector> union_readers; union_readers.resize(files.size()); - TaskExecutor executor(context); + TaskExecutor executor(context, scheduler_type); // schedule tasks for all files for (idx_t file_idx = 0; file_idx < files.size(); ++file_idx) { auto task = make_uniq(executor, context, files[file_idx], file_idx, union_readers, options, - file_options, multi_file_reader, interface); + file_options, multi_file_reader, interface, ignore_errors); executor.ScheduleTask(std::move(task)); } // complete all tasks executor.WorkOnTasks(); + return union_readers; +} + +vector> UnionByName::UnionCols(ClientContext &context, const vector &files, + vector &union_col_types, + vector &union_col_names, + BaseFileReaderOptions &options, MultiFileOptions &file_options, + MultiFileReader &multi_file_reader, + MultiFileReaderInterface &interface) { + auto union_readers = ReadUnionData(context, files, options, file_options, multi_file_reader, interface); // now combine the result schemas interface.CombineSchemas(context, union_readers, file_options.union_by_name, union_col_types, union_col_names); diff --git a/src/duckdb/src/common/open_file_info.cpp b/src/duckdb/src/common/open_file_info.cpp index d17aa1c64..f34338232 100644 --- a/src/duckdb/src/common/open_file_info.cpp +++ b/src/duckdb/src/common/open_file_info.cpp @@ -149,4 +149,8 @@ bool ExtendedOpenFileInfo::TryGetOption(const string &name, timestamp_t &result) return true; } +bool ExtendedOpenFileInfo::TryGetSecretName(string &name) const { + return TryGetOption(SECRET_OPTION, name); +} + } // namespace duckdb diff --git a/src/duckdb/src/common/operator/cast_operators.cpp b/src/duckdb/src/common/operator/cast_operators.cpp index 3a8e5453c..1345e9a66 100644 --- a/src/duckdb/src/common/operator/cast_operators.cpp +++ b/src/duckdb/src/common/operator/cast_operators.cpp @@ -10,6 +10,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/blob.hpp" #include "duckdb/common/types/cast_helpers.hpp" @@ -2448,70 +2449,70 @@ bool TryCast::Operation(string_t input, uhugeint_t &result, bool strict) { //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(string_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(string_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(string_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(string_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(string_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(string_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> bool TryCastToDecimalCommaSeparated::Operation(string_t input, int16_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale) { + uint32_t width, uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> bool TryCastToDecimalCommaSeparated::Operation(string_t input, int32_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale) { + uint32_t width, uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> bool TryCastToDecimalCommaSeparated::Operation(string_t input, int64_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale) { + uint32_t width, uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> bool TryCastToDecimalCommaSeparated::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale) { + uint32_t width, uint32_t scale) { return TryDecimalStringCast(input, result, parameters, width, scale); } template <> -string_t StringCastFromDecimal::Operation(int16_t input, uint8_t width, uint8_t scale, StringHeap &heap) { +string_t StringCastFromDecimal::Operation(int16_t input, uint32_t width, uint32_t scale, StringHeap &heap) { return DecimalToString::Format(input, width, scale, heap); } template <> -string_t StringCastFromDecimal::Operation(int32_t input, uint8_t width, uint8_t scale, StringHeap &heap) { +string_t StringCastFromDecimal::Operation(int32_t input, uint32_t width, uint32_t scale, StringHeap &heap) { return DecimalToString::Format(input, width, scale, heap); } template <> -string_t StringCastFromDecimal::Operation(int64_t input, uint8_t width, uint8_t scale, StringHeap &heap) { +string_t StringCastFromDecimal::Operation(int64_t input, uint32_t width, uint32_t scale, StringHeap &heap) { return DecimalToString::Format(input, width, scale, heap); } template <> -string_t StringCastFromDecimal::Operation(hugeint_t input, uint8_t width, uint8_t scale, StringHeap &heap) { +string_t StringCastFromDecimal::Operation(hugeint_t input, uint32_t width, uint32_t scale, StringHeap &heap) { return DecimalToString::Format(input, width, scale, heap); } @@ -2521,7 +2522,7 @@ string_t StringCastFromDecimal::Operation(hugeint_t input, uint8_t width, uint8_ // Decimal <-> Bool //===--------------------------------------------------------------------===// template -bool TryCastBoolToDecimal(bool input, T &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool TryCastBoolToDecimal(bool input, T &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { // a decimal without integer digits cannot hold true if (input && width <= scale) { string error = StringUtil::Format("Could not cast value true to DECIMAL(%d,%d)", width, scale); @@ -2533,50 +2534,50 @@ bool TryCastBoolToDecimal(bool input, T &result, CastParameters ¶meters, uin } template <> -bool TryCastToDecimal::Operation(bool input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(bool input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastBoolToDecimal(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(bool input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(bool input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastBoolToDecimal(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(bool input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(bool input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastBoolToDecimal(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(bool input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(bool input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastBoolToDecimal(input, result, parameters, width, scale); } template <> -bool TryCastFromDecimal::Operation(int16_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCast::Operation(input, result); } template <> -bool TryCastFromDecimal::Operation(int32_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCast::Operation(input, result); } template <> -bool TryCastFromDecimal::Operation(int64_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCast::Operation(input, result); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCast::Operation(input, result); } @@ -2598,7 +2599,7 @@ struct UnsignedToDecimalOperator { }; template -bool StandardNumericToDecimalCast(SRC input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool StandardNumericToDecimalCast(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { // check for overflow DST max_width = UnsafeNumericCast(NumericHelper::POWERS_OF_TEN[width - scale]); if (OP::template Operation(input, max_width)) { @@ -2611,7 +2612,8 @@ bool StandardNumericToDecimalCast(SRC input, DST &result, CastParameters ¶me } template -bool NumericToHugeDecimalCast(SRC input, hugeint_t &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool NumericToHugeDecimalCast(SRC input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { // check for overflow hugeint_t max_width = Hugeint::POWERS_OF_TEN[width - scale]; hugeint_t hinput = Hugeint::Convert(input); @@ -2628,23 +2630,23 @@ bool NumericToHugeDecimalCast(SRC input, hugeint_t &result, CastParameters ¶ // Cast int8_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(int8_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int8_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int8_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int8_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int8_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int8_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int8_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int8_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2652,23 +2654,23 @@ bool TryCastToDecimal::Operation(int8_t input, hugeint_t &result, CastParameters // Cast int16_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2676,23 +2678,23 @@ bool TryCastToDecimal::Operation(int16_t input, hugeint_t &result, CastParameter // Cast int32_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2700,23 +2702,23 @@ bool TryCastToDecimal::Operation(int32_t input, hugeint_t &result, CastParameter // Cast int64_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2724,26 +2726,26 @@ bool TryCastToDecimal::Operation(int64_t input, hugeint_t &result, CastParameter // Cast uint8_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(uint8_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint8_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint8_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint8_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint8_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint8_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint8_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint8_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2751,26 +2753,26 @@ bool TryCastToDecimal::Operation(uint8_t input, hugeint_t &result, CastParameter // Cast uint16_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(uint16_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint16_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint16_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint16_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2778,26 +2780,26 @@ bool TryCastToDecimal::Operation(uint16_t input, hugeint_t &result, CastParamete // Cast uint32_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(uint32_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint32_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint32_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint32_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint32_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint32_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint32_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint32_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2805,26 +2807,26 @@ bool TryCastToDecimal::Operation(uint32_t input, hugeint_t &result, CastParamete // Cast uint64_t -> Decimal //===--------------------------------------------------------------------===// template <> -bool TryCastToDecimal::Operation(uint64_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint64_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint64_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint64_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint64_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint64_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return StandardNumericToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uint64_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uint64_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return NumericToHugeDecimalCast(input, result, parameters, width, scale); } @@ -2832,7 +2834,7 @@ bool TryCastToDecimal::Operation(uint64_t input, hugeint_t &result, CastParamete // Hugeint -> Decimal Cast //===--------------------------------------------------------------------===// template -bool HugeintToDecimalCast(hugeint_t input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool HugeintToDecimalCast(hugeint_t input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { // check for overflow hugeint_t max_width = Hugeint::POWERS_OF_TEN[width - scale]; if (input >= max_width || input <= -max_width) { @@ -2845,26 +2847,26 @@ bool HugeintToDecimalCast(hugeint_t input, DST &result, CastParameters ¶mete } template <> -bool TryCastToDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return HugeintToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return HugeintToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return HugeintToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return HugeintToDecimalCast(input, result, parameters, width, scale); } @@ -2872,7 +2874,7 @@ bool TryCastToDecimal::Operation(hugeint_t input, hugeint_t &result, CastParamet // Uhugeint -> Decimal Cast //===--------------------------------------------------------------------===// template -bool UhugeintToDecimalCast(uhugeint_t input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool UhugeintToDecimalCast(uhugeint_t input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { // check for overflow uhugeint_t max_width = Uhugeint::POWERS_OF_TEN[width - scale]; if (input >= max_width) { @@ -2885,26 +2887,26 @@ bool UhugeintToDecimalCast(uhugeint_t input, DST &result, CastParameters ¶me } template <> -bool TryCastToDecimal::Operation(uhugeint_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uhugeint_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return UhugeintToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uhugeint_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uhugeint_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return UhugeintToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uhugeint_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uhugeint_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return UhugeintToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(uhugeint_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(uhugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return UhugeintToDecimalCast(input, result, parameters, width, scale); } @@ -2912,9 +2914,9 @@ bool TryCastToDecimal::Operation(uhugeint_t input, hugeint_t &result, CastParame // Float/Double -> Decimal Cast //===--------------------------------------------------------------------===// template -bool DoubleToDecimalCast(SRC input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool DoubleToDecimalCast(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { double value = input * NumericHelper::DOUBLE_POWERS_OF_TEN[scale]; - double roundedValue = round(value); + double roundedValue = RoundToNearestAwayFromZero(value); if (roundedValue <= -NumericHelper::DOUBLE_POWERS_OF_TEN[width] || roundedValue >= NumericHelper::DOUBLE_POWERS_OF_TEN[width] || !Value::IsFinite(roundedValue)) { string error = StringUtil::Format("Could not cast value %f to DECIMAL(%d,%d)", input, width, scale); @@ -2927,50 +2929,50 @@ bool DoubleToDecimalCast(SRC input, DST &result, CastParameters ¶meters, uin } template <> -bool TryCastToDecimal::Operation(float input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(float input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(float input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(float input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(float input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(float input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(float input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(float input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(double input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(double input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(double input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(double input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(double input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(double input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } template <> -bool TryCastToDecimal::Operation(double input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastToDecimal::Operation(double input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return DoubleToDecimalCast(input, result, parameters, width, scale); } @@ -2978,7 +2980,7 @@ bool TryCastToDecimal::Operation(double input, hugeint_t &result, CastParameters // Decimal -> Numeric Cast //===--------------------------------------------------------------------===// template -bool TryCastDecimalToNumeric(SRC input, DST &result, CastParameters ¶meters, uint8_t scale) { +bool TryCastDecimalToNumeric(SRC input, DST &result, CastParameters ¶meters, uint32_t scale) { // Round away from 0. const auto power = NumericHelper::POWERS_OF_TEN[scale]; // https://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate @@ -2994,7 +2996,7 @@ bool TryCastDecimalToNumeric(SRC input, DST &result, CastParameters ¶meters, } template -bool TryCastHugeDecimalToNumeric(hugeint_t input, DST &result, CastParameters ¶meters, uint8_t scale) { +bool TryCastHugeDecimalToNumeric(hugeint_t input, DST &result, CastParameters ¶meters, uint32_t scale) { const auto power = Hugeint::POWERS_OF_TEN[scale]; const auto rounding = ((input < 0) ? -power : power) / 2; auto scaled_value = (input + rounding) / power; @@ -3011,23 +3013,23 @@ bool TryCastHugeDecimalToNumeric(hugeint_t input, DST &result, CastParameters &p // Cast Decimal -> int8_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3035,23 +3037,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, int8_t &result, CastParamete // Cast Decimal -> int16_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3059,23 +3061,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, int16_t &result, CastParamet // Cast Decimal -> int32_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3083,23 +3085,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, int32_t &result, CastParamet // Cast Decimal -> int64_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3107,23 +3109,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, int64_t &result, CastParamet // Cast Decimal -> uint8_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3131,23 +3133,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, uint8_t &result, CastParamet // Cast Decimal -> uint16_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3155,23 +3157,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, uint16_t &result, CastParame // Cast Decimal -> uint32_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3179,23 +3181,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, uint32_t &result, CastParame // Cast Decimal -> uint64_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3203,23 +3205,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, uint64_t &result, CastParame // Cast Decimal -> hugeint_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3227,23 +3229,23 @@ bool TryCastFromDecimal::Operation(hugeint_t input, hugeint_t &result, CastParam // Cast Decimal -> uhugeint_t //===--------------------------------------------------------------------===// template <> -bool TryCastFromDecimal::Operation(int16_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToNumeric(input, result, parameters, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastHugeDecimalToNumeric(input, result, parameters, scale); } @@ -3297,9 +3299,9 @@ bool IsRepresentableExactly(hugeint_t input, double dst) { } template -static bool CanUseDecimalFloatingPointFastPath(SRC input, uint8_t scale) { - return duckdb_fast_float::binary_format::min_exponent_fast_path() <= -scale && - -scale <= duckdb_fast_float::binary_format::max_exponent_fast_path() && +static bool CanUseDecimalFloatingPointFastPath(SRC input, uint32_t scale) { + return duckdb_fast_float::binary_format::min_exponent_fast_path() <= -int64_t(scale) && + -int64_t(scale) <= duckdb_fast_float::binary_format::max_exponent_fast_path() && IsRepresentableExactly(input, DST(0.0)); } @@ -3351,7 +3353,7 @@ static void FillDecimalDigits(hugeint_t input, duckdb_fast_float::decimal &decim } template -bool TryCastDecimalToFloatingPoint(SRC input, DST &result, uint8_t width, uint8_t scale) { +bool TryCastDecimalToFloatingPoint(SRC input, DST &result, uint32_t width, uint32_t scale) { if (scale == 0 || CanUseDecimalFloatingPointFastPath(input, scale)) { // Fast path, integer and decimal exponent are representable exactly as a float/double result = Cast::Operation(input) / DST(NumericHelper::DOUBLE_POWERS_OF_TEN[scale]); @@ -3376,51 +3378,51 @@ bool TryCastDecimalToFloatingPoint(SRC input, DST &result, uint8_t width, uint8_ // DECIMAL -> FLOAT template <> -bool TryCastFromDecimal::Operation(int16_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } // DECIMAL -> DOUBLE template <> -bool TryCastFromDecimal::Operation(int16_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int16_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } template <> -bool TryCastFromDecimal::Operation(int32_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int32_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } template <> -bool TryCastFromDecimal::Operation(int64_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(int64_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } template <> -bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { +bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { return TryCastDecimalToFloatingPoint(input, result, width, scale); } diff --git a/src/duckdb/src/common/query_context.cpp b/src/duckdb/src/common/query_context.cpp new file mode 100644 index 000000000..1f1ba6b1d --- /dev/null +++ b/src/duckdb/src/common/query_context.cpp @@ -0,0 +1,17 @@ +#include "duckdb/common/query_context.hpp" + +#include "duckdb/main/client_context.hpp" + +namespace duckdb { + +QueryContext::QueryContext(optional_ptr client_context_p) : client_context(client_context_p) { + if (client_context) { + context = &client_context->GetContext(); + } +} + +QueryContext::QueryContext(ClientContext &client_context_p) + : context(&client_context_p.GetContext()), client_context(&client_context_p) { +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/random_engine.cpp b/src/duckdb/src/common/random_engine.cpp index 156b4baec..83c0ff760 100644 --- a/src/duckdb/src/common/random_engine.cpp +++ b/src/duckdb/src/common/random_engine.cpp @@ -17,20 +17,30 @@ struct RandomState { pcg32 pcg; }; -RandomEngine::RandomEngine(int64_t seed) : random_state(make_uniq()) { - if (seed < 0) { +//! A seed drawn from the operating system's entropy source +static uint64_t EntropySeed() { #ifdef __linux__ - idx_t random_seed = 0; - int result = -1; + uint64_t random_seed = 0; + int result = -1; #if defined(SYS_getrandom) - result = static_cast(syscall(SYS_getrandom, &random_seed, sizeof(random_seed), 0)); + result = static_cast(syscall(SYS_getrandom, &random_seed, sizeof(random_seed), 0)); +#endif + if (result == -1) { + // Something went wrong with the syscall, we use chrono + const auto now = std::chrono::high_resolution_clock::now(); + random_seed = static_cast(now.time_since_epoch().count()); + } + return random_seed; +#else + std::random_device device; + return (static_cast(device()) << UINT64_C(32)) | static_cast(device()); #endif - if (result == -1) { - // Something went wrong with the syscall, we use chrono - const auto now = std::chrono::high_resolution_clock::now(); - random_seed = now.time_since_epoch().count(); - } - random_state->pcg.seed(random_seed); +} + +RandomEngine::RandomEngine(int64_t seed) : random_state(make_uniq()), explicitly_seeded(seed >= 0) { + if (seed < 0) { +#ifdef __linux__ + random_state->pcg.seed(EntropySeed()); #else random_state->pcg.seed(pcg_extras::seed_seq_from()); #endif @@ -80,6 +90,17 @@ uint32_t RandomEngine::NextRandomInteger32(uint32_t min, uint32_t max) { void RandomEngine::SetSeed(uint64_t seed) { random_state->pcg.seed(seed); + explicitly_seeded = true; +} + +uint64_t RandomEngine::NextSeed() { + auto seed = NextRandomInteger64(); + return explicitly_seeded ? seed : seed ^ EntropySeed(); +} + +uint32_t RandomEngine::NextSeed32() { + auto seed = NextRandomInteger(); + return explicitly_seeded ? seed : seed ^ static_cast(EntropySeed()); } void RandomEngine::RandomData(duckdb::data_ptr_t data, duckdb::idx_t len) { diff --git a/src/duckdb/src/common/row_operations/row_aggregate.cpp b/src/duckdb/src/common/row_operations/row_aggregate.cpp index 9df3f28d6..4a8ffff05 100644 --- a/src/duckdb/src/common/row_operations/row_aggregate.cpp +++ b/src/duckdb/src/common/row_operations/row_aggregate.cpp @@ -69,8 +69,9 @@ void RowOperations::UpdateStates(RowOperationsState &state, AggregateObject &agg } void RowOperations::UpdateFilteredStates(RowOperationsState &state, AggregateFilterData &filter_data, - AggregateObject &aggr, Vector &addresses, DataChunk &payload, idx_t arg_idx) { - idx_t count = filter_data.ApplyFilter(payload); + AggregateObject &aggr, Vector &addresses, idx_t arg_idx) { + // the filter has been applied to the payload by AggregateFilterDataSet::ApplyFilters + idx_t count = filter_data.selected_count; if (count == 0) { return; } @@ -104,7 +105,7 @@ void RowOperations::UpdateStatesClustered(RowOperationsState &state, vectorGetFilterData(aggr_idx), aggr, addresses, payload, + RowOperations::UpdateFilteredStates(state, filter_set->GetFilterData(aggr_idx), aggr, addresses, payload_idx); } else { UpdateStates(state, aggr, addresses, payload, payload_idx, clustered); diff --git a/src/duckdb/src/common/serializer/async_file_writer.cpp b/src/duckdb/src/common/serializer/async_file_writer.cpp index a56bbb20f..60fd2ad53 100644 --- a/src/duckdb/src/common/serializer/async_file_writer.cpp +++ b/src/duckdb/src/common/serializer/async_file_writer.cpp @@ -2,7 +2,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/helper.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/storage/buffer_manager.hpp" #include @@ -14,7 +14,7 @@ const FileOpenFlags AsyncFileWriter::DEFAULT_OPEN_FLAGS = class CopiedAsyncWriteBuffer : public AsyncWriteBuffer { public: - CopiedAsyncWriteBuffer(ClientContext &context, idx_t capacity_p) + CopiedAsyncWriteBuffer(Context &context, idx_t capacity_p) : data(BufferAllocator::Get(context).Allocate(capacity_p)), capacity(capacity_p) { } @@ -42,22 +42,14 @@ class CopiedAsyncWriteBuffer : public AsyncWriteBuffer { idx_t size = 0; }; -static ClientContext &RequireClientContext(QueryContext context) { - auto client_context = context.GetClientContext(); - if (!client_context) { - throw InvalidInputException("AsyncFileWriter requires a ClientContext"); - } - return *client_context; -} - -AsyncFileWriter::AsyncFileWriter(QueryContext context_p, FileSystem &fs_p, const string &path_p, +AsyncFileWriter::AsyncFileWriter(Context &context_p, FileSystem &fs_p, const string &path_p, const FileOpenFlags &open_flags) - : context(context_p), client_context(RequireClientContext(context_p)), fs(fs_p), path(path_p) { + : context(context_p), fs(fs_p), path(path_p) { handle = fs.OpenFile(path, open_flags | FileLockType::WRITE_LOCK); try { ManagedAsyncWriteStreamTarget &target = *this; - write_queue = make_uniq(client_context, target); + write_queue = make_uniq(context, target); } catch (...) { auto error = std::current_exception(); try { @@ -146,7 +138,7 @@ void AsyncFileWriter::WriteDataInternal(const_data_ptr_t buffer, idx_t write_siz // Caller-owned memory cannot outlive async scheduling, so even large const inputs are copied before registration. if (write_size >= AsyncWriteConfig::COPIED_BUFFER_CAPACITY) { SealCopiedBuffer(ScheduleMode::DEFER); - auto owned_buffer = make_uniq(client_context, write_size); + auto owned_buffer = make_uniq(context, write_size); owned_buffer->Append(buffer, write_size); RegisterWrite(std::move(owned_buffer)); return; @@ -158,7 +150,7 @@ void AsyncFileWriter::WriteDataInternal(const_data_ptr_t buffer, idx_t write_siz idx_t sealed_buffer_offset = 0; if (!copied_buffer) { copied_buffer_offset = total_written; - copied_buffer = make_uniq(client_context, AsyncWriteConfig::COPIED_BUFFER_CAPACITY); + copied_buffer = make_uniq(context, AsyncWriteConfig::COPIED_BUFFER_CAPACITY); } auto append_size = MinValue(write_size - offset, copied_buffer->Remaining()); copied_buffer->Append(buffer + offset, append_size); @@ -258,7 +250,7 @@ void AsyncFileWriter::WriteDataSynchronously(data_ptr_t buffer, idx_t write_size idx_t sealed_buffer_offset = 0; if (!copied_buffer) { copied_buffer_offset = total_written; - copied_buffer = make_uniq(client_context, AsyncWriteConfig::COPIED_BUFFER_CAPACITY); + copied_buffer = make_uniq(context, AsyncWriteConfig::COPIED_BUFFER_CAPACITY); } auto append_size = MinValue(write_size - input_offset, copied_buffer->Remaining()); copied_buffer->Append(buffer + input_offset, append_size); diff --git a/src/duckdb/src/common/serializer/async_memory_governor.cpp b/src/duckdb/src/common/serializer/async_memory_governor.cpp index dc3f320d1..74cb6da9b 100644 --- a/src/duckdb/src/common/serializer/async_memory_governor.cpp +++ b/src/duckdb/src/common/serializer/async_memory_governor.cpp @@ -1,19 +1,18 @@ #include "duckdb/common/serializer/async_memory_governor.hpp" #include "duckdb/common/helper.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" namespace duckdb { -ManagedAsyncMemoryGovernor::ManagedAsyncMemoryGovernor(ClientContext &client_context_p) - : client_context(client_context_p) { - auto &scheduler = TaskScheduler::GetScheduler(client_context); +ManagedAsyncMemoryGovernor::ManagedAsyncMemoryGovernor(Context &context_p) : context(context_p) { + auto &scheduler = context.GetTaskScheduler(); auto regular_threads = MaxValue(NumericCast(scheduler.NumberOfThreads()), 1); auto async_threads = NumericCast(scheduler.NumberOfAsyncThreads()); - auto max_memory = BufferManager::GetBufferManager(client_context).GetMaxMemory(); + auto max_memory = context.GetBufferManager().GetMaxMemory(); max_pending_bytes = MinValue(ManagedAsyncMemoryConfig::MAX_PENDING_BYTES_PER_THREAD * regular_threads, max_memory / ManagedAsyncMemoryConfig::MAX_PENDING_MEMORY_LIMIT_DIVISOR); min_pending_bytes = @@ -21,7 +20,7 @@ ManagedAsyncMemoryGovernor::ManagedAsyncMemoryGovernor(ClientContext &client_con max_memory / ManagedAsyncMemoryConfig::MIN_PENDING_MEMORY_LIMIT_DIVISOR)); // A reservation is only useful when drain tasks run asynchronously; synchronous draining bounds itself. if (async_threads > 0 && max_pending_bytes > 0) { - memory_state = TemporaryMemoryManager::Get(client_context).Register(client_context); + memory_state = TemporaryMemoryManager::Get(context).Register(context); memory_state->SetMinimumReservation(min_pending_bytes); memory_state->SetZero(); } @@ -38,6 +37,7 @@ void ManagedAsyncMemoryGovernor::UpdateReservation(idx_t current_pending_bytes) return; } + lock_guard guard(reservation_lock); auto current_reservation = memory_state->GetReservation(); while (current_pending_bytes > MinValue(current_reservation, max_pending_bytes)) { idx_t next_request; @@ -61,7 +61,7 @@ void ManagedAsyncMemoryGovernor::UpdateReservation(idx_t current_pending_bytes) } auto previous_reservation = current_reservation; - memory_state->SetRemainingSizeAndUpdateReservation(client_context, next_request); + memory_state->SetRemainingSizeAndUpdateReservation(context, next_request); memory_request_bytes = next_request; current_reservation = memory_state->GetReservation(); if (current_reservation <= previous_reservation) { @@ -87,7 +87,11 @@ idx_t ManagedAsyncMemoryGovernor::BackpressureBudget() const { } void ManagedAsyncMemoryGovernor::Release() { - if (!memory_state || memory_request_bytes == 0) { + if (!memory_state) { + return; + } + lock_guard guard(reservation_lock); + if (memory_request_bytes == 0) { return; } memory_state->SetZero(); diff --git a/src/duckdb/src/common/serializer/async_task_queue.cpp b/src/duckdb/src/common/serializer/async_task_queue.cpp index 80d7d1e7e..d6bb56e33 100644 --- a/src/duckdb/src/common/serializer/async_task_queue.cpp +++ b/src/duckdb/src/common/serializer/async_task_queue.cpp @@ -2,7 +2,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/helper.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/parallel/task_executor.hpp" #include "duckdb/parallel/task_scheduler.hpp" @@ -79,15 +79,14 @@ class AsyncTaskQueueTask : public BaseExecutorTask { bool started = false; }; -AsyncTaskQueue::AsyncTaskQueue(ClientContext &client_context_p, idx_t max_active_tasks_p) - : client_context(client_context_p) { - auto &scheduler = TaskScheduler::GetScheduler(client_context); +AsyncTaskQueue::AsyncTaskQueue(Context &context_p, idx_t max_active_tasks_p) : context(context_p) { + auto &scheduler = context.GetTaskScheduler(); auto async_threads = NumericCast(scheduler.NumberOfAsyncThreads()); max_active_tasks = max_active_tasks_p > 0 ? max_active_tasks_p : MaxValue(async_threads, 1); if (async_threads == 0) { return; } - executor = make_uniq(client_context, TaskSchedulerType::ASYNC); + executor = make_uniq(context, TaskSchedulerType::ASYNC); } AsyncTaskQueue::~AsyncTaskQueue() { @@ -367,12 +366,12 @@ void AsyncTaskQueue::VerifyOpen() const { //===--------------------------------------------------------------------===// // ManagedAsyncTaskQueue //===--------------------------------------------------------------------===// -ManagedAsyncTaskQueue::ManagedAsyncTaskQueue(ClientContext &client_context_p, idx_t max_active_tasks) - : client_context(client_context_p), memory_governor(client_context_p) { - auto &scheduler = TaskScheduler::GetScheduler(client_context); +ManagedAsyncTaskQueue::ManagedAsyncTaskQueue(Context &context_p, idx_t max_active_tasks) + : context(context_p), memory_governor(context_p) { + auto &scheduler = context.GetTaskScheduler(); auto async_threads = NumericCast(scheduler.NumberOfAsyncThreads()); max_active_drain_tasks = max_active_tasks > 0 ? max_active_tasks : MaxValue(async_threads, 1); - task_queue = make_uniq(client_context, max_active_drain_tasks); + task_queue = make_uniq(context, max_active_drain_tasks); } ManagedAsyncTaskQueue::~ManagedAsyncTaskQueue() { diff --git a/src/duckdb/src/common/serializer/async_write_queue.cpp b/src/duckdb/src/common/serializer/async_write_queue.cpp index 10d3a8985..384332c6a 100644 --- a/src/duckdb/src/common/serializer/async_write_queue.cpp +++ b/src/duckdb/src/common/serializer/async_write_queue.cpp @@ -4,7 +4,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/exception/http_exception.hpp" #include "duckdb/common/helper.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/parallel/task_executor.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/storage/buffer_manager.hpp" @@ -85,15 +85,15 @@ class AsyncWriteQueueTask : public BaseExecutorTask { AsyncWriteQueue &queue; }; -AsyncWriteQueue::AsyncWriteQueue(ClientContext &client_context_p, AsyncWriteTarget &target_p) - : client_context(client_context_p), target(target_p) { - auto &scheduler = TaskScheduler::GetScheduler(client_context); +AsyncWriteQueue::AsyncWriteQueue(Context &context_p, AsyncWriteTarget &target_p) + : context(context_p), target(target_p) { + auto &scheduler = context.GetTaskScheduler(); auto async_threads = scheduler.NumberOfAsyncThreads(); max_active_tasks = MaxValue(async_threads, 1); if (async_threads == 0) { return; } - executor = make_uniq(client_context, TaskSchedulerType::ASYNC); + executor = make_uniq(context, TaskSchedulerType::ASYNC); } AsyncWriteQueue::~AsyncWriteQueue() { @@ -504,14 +504,14 @@ idx_t ManagedAsyncWriteQueue::PendingWrite::Size() const { return size; } -ManagedAsyncWriteQueue::ManagedAsyncWriteQueue(ClientContext &client_context_p, AsyncWriteTarget &target_p) - : client_context(client_context_p), target(target_p), memory_governor(client_context_p) { - auto &scheduler = TaskScheduler::GetScheduler(client_context); +ManagedAsyncWriteQueue::ManagedAsyncWriteQueue(Context &context_p, AsyncWriteTarget &target_p) + : context(context_p), target(target_p), memory_governor(context_p) { + auto &scheduler = context.GetTaskScheduler(); auto async_threads = scheduler.NumberOfAsyncThreads(); max_active_drain_tasks = MaxValue(async_threads, 1); AsyncWriteTarget &async_target = *this; - write_queue = make_uniq(client_context, async_target); + write_queue = make_uniq(context, async_target); } ManagedAsyncWriteQueue::~ManagedAsyncWriteQueue() { @@ -958,8 +958,8 @@ idx_t ManagedAsyncWriteStreamQueue::PendingWrite::Size() const { class ManagedAsyncWriteStreamQueue::CoalescedWritePayload : public AsyncWritePayload { public: - CoalescedWritePayload(ClientContext &client_context_p, deque writes_p, idx_t size_p) - : client_context(client_context_p), writes(std::move(writes_p)), size(size_p) { + CoalescedWritePayload(Context &context_p, deque writes_p, idx_t size_p) + : context(context_p), writes(std::move(writes_p)), size(size_p) { } data_ptr_t Ptr() override { @@ -967,7 +967,7 @@ class ManagedAsyncWriteStreamQueue::CoalescedWritePayload : public AsyncWritePay return writes.front().payload->Ptr(); } if (!coalesced.get()) { - coalesced = BufferAllocator::Get(client_context).Allocate(size); + coalesced = BufferAllocator::Get(context).Allocate(size); idx_t offset = 0; for (auto &write : writes) { auto current_size = write.Size(); @@ -986,7 +986,7 @@ class ManagedAsyncWriteStreamQueue::CoalescedWritePayload : public AsyncWritePay } private: - ClientContext &client_context; + Context &context; deque writes; AllocatedData coalesced; idx_t size; @@ -1020,9 +1020,8 @@ class ManagedAsyncWriteStreamQueue::MaterializedWritePayload : public AsyncWrite idx_t size; }; -ManagedAsyncWriteStreamQueue::ManagedAsyncWriteStreamQueue(ClientContext &client_context_p, - ManagedAsyncWriteStreamTarget &target_p) - : client_context(client_context_p), target(target_p) { +ManagedAsyncWriteStreamQueue::ManagedAsyncWriteStreamQueue(Context &context_p, ManagedAsyncWriteStreamTarget &target_p) + : context(context_p), target(target_p) { auto local_file = target.IsLocalFile(); coalesce_threshold = local_file ? AsyncWriteConfig::LOCAL_COALESCE_THRESHOLD : AsyncWriteConfig::REMOTE_COALESCE_THRESHOLD; @@ -1030,7 +1029,7 @@ ManagedAsyncWriteStreamQueue::ManagedAsyncWriteStreamQueue(ClientContext &client drain_task_byte_budget = MaxValue(AsyncWriteConfig::DRAIN_TASK_BYTE_BUDGET, coalesce_threshold); limit_coalesced_write_size = local_file; - auto &scheduler = TaskScheduler::GetScheduler(client_context); + auto &scheduler = context.GetTaskScheduler(); auto async_threads = scheduler.NumberOfAsyncThreads(); write_mode = target.GetWriteMode(); @@ -1041,7 +1040,7 @@ ManagedAsyncWriteStreamQueue::ManagedAsyncWriteStreamQueue(ClientContext &client } AsyncWriteTarget &async_target = *this; - write_queue = make_uniq(client_context, async_target); + write_queue = make_uniq(context, async_target); } ManagedAsyncWriteStreamQueue::~ManagedAsyncWriteStreamQueue() { @@ -1359,7 +1358,7 @@ unique_ptr ManagedAsyncWriteStreamQueue::CreatePayload(deque< if (writes.size() == 1) { return std::move(writes.front().payload); } - return make_uniq(client_context, std::move(writes), size); + return make_uniq(context, std::move(writes), size); } unique_ptr ManagedAsyncWriteStreamQueue::CreateMaterializedPayload(idx_t end, idx_t size) { @@ -1380,7 +1379,7 @@ unique_ptr ManagedAsyncWriteStreamQueue::CreateMaterializedPa return std::move(result); } - auto data = BufferAllocator::Get(client_context).Allocate(size); + auto data = BufferAllocator::Get(context).Allocate(size); idx_t data_offset = 0; for (idx_t write_idx = 0; write_idx < end; write_idx++) { auto &write = pending_writes[write_idx]; diff --git a/src/duckdb/src/common/sort/sort.cpp b/src/duckdb/src/common/sort/sort.cpp index dd25e0912..b6699d532 100644 --- a/src/duckdb/src/common/sort/sort.cpp +++ b/src/duckdb/src/common/sort/sort.cpp @@ -161,8 +161,8 @@ class SortGlobalSinkState : public GlobalSinkState { public: explicit SortGlobalSinkState(ClientContext &context) : num_threads(TaskScheduler::GetScheduler(context).NumberOfThreads()), - temporary_memory_state(TemporaryMemoryManager::Get(context).Register(context)), sorted_tuples(0), - sunk_tuples(0), external(Settings::Get(context)), total_count(0), + temporary_memory_state(TemporaryMemoryManager::Get(context.GetContext()).Register(context.GetContext())), + sorted_tuples(0), sunk_tuples(0), external(Settings::Get(context)), total_count(0), partition_size(0) { } @@ -193,7 +193,7 @@ class SortGlobalSinkState : public GlobalSinkState { } // Send the request - temporary_memory_state->SetRemainingSizeAndUpdateReservation(context, request); + temporary_memory_state->SetRemainingSizeAndUpdateReservation(context.GetContext(), request); // If we got less than we required, we have to go external if (temporary_memory_state->GetReservation() < required) { @@ -382,14 +382,14 @@ SinkFinalizeType Sort::Finalize(ClientContext &context, OperatorSinkFinalizeInpu gstate.total_count += sorted_run->Count(); maximum_run_count = MaxValue(maximum_run_count, sorted_run->Count()); } - if (context.config.verify_parallelism) { + if (ClientConfig::GetConfig(context).verify_parallelism) { gstate.partition_size = STANDARD_VECTOR_SIZE; } else { gstate.partition_size = MinValue(gstate.total_count, DEFAULT_ROW_GROUP_SIZE); } // Amortize external boundary searches while keeping enough parallel work and estimated memory headroom. - if (gstate.external && !is_index_sort && !context.config.verify_parallelism) { + if (gstate.external && !is_index_sort && !ClientConfig::GetConfig(context).verify_parallelism) { const auto partition_size = gstate.partition_size * 4; if (gstate.total_count / gstate.num_threads >= partition_size && CanUseLargerPartitions(gstate, partition_size)) { diff --git a/src/duckdb/src/common/time_point.cpp b/src/duckdb/src/common/time_point.cpp index 7ef15011b..3a71754aa 100644 --- a/src/duckdb/src/common/time_point.cpp +++ b/src/duckdb/src/common/time_point.cpp @@ -1,8 +1,14 @@ #include "duckdb/common/time_point.hpp" -#include "duckdb/common/assert.hpp" namespace duckdb { +//! steady_clock can step backwards in practice: on some virtual machines (#27790), and in WebAssembly builds with +//! threads, where each thread derives the clock from its own time origin. Callers cast intervals to unsigned integers, +//! so a negative interval is clamped to zero. +static steady_clock::duration NonNegative(steady_clock::duration duration) { + return duration < steady_clock::duration::zero() ? steady_clock::duration::zero() : duration; +} + TimePoint::TimePoint() : value() { } @@ -15,47 +21,39 @@ int64_t TimePoint::GetTickMs() { } double TimePoint::ElapsedSeconds(const TimePoint &start, const TimePoint &end) { - D_ASSERT(start.value <= end.value); - return std::chrono::duration_cast>(end.value - start.value).count(); + return std::chrono::duration_cast>(NonNegative(end.value - start.value)).count(); } int64_t TimePoint::ElapsedMillis(const TimePoint &start, const TimePoint &end) { - D_ASSERT(start.value <= end.value); - return std::chrono::duration_cast(end.value - start.value).count(); + return std::chrono::duration_cast(NonNegative(end.value - start.value)).count(); } int64_t TimePoint::ElapsedMicros(const TimePoint &start, const TimePoint &end) { - D_ASSERT(start.value <= end.value); - return std::chrono::duration_cast(end.value - start.value).count(); + return std::chrono::duration_cast(NonNegative(end.value - start.value)).count(); } int64_t TimePoint::ElapsedNanos(const TimePoint &start, const TimePoint &end) { - D_ASSERT(start.value <= end.value); - return std::chrono::duration_cast(end.value - start.value).count(); + return std::chrono::duration_cast(NonNegative(end.value - start.value)).count(); } double TimePoint::ElapsedSeconds() const { auto now = steady_clock::now(); - D_ASSERT(value <= now); - return std::chrono::duration_cast>(now - value).count(); + return std::chrono::duration_cast>(NonNegative(now - value)).count(); } int64_t TimePoint::ElapsedMillis() const { auto now = steady_clock::now(); - D_ASSERT(value <= now); - return std::chrono::duration_cast(now - value).count(); + return std::chrono::duration_cast(NonNegative(now - value)).count(); } int64_t TimePoint::ElapsedMicros() const { auto now = steady_clock::now(); - D_ASSERT(value <= now); - return std::chrono::duration_cast(now - value).count(); + return std::chrono::duration_cast(NonNegative(now - value)).count(); } int64_t TimePoint::ElapsedNanos() const { auto now = steady_clock::now(); - D_ASSERT(value <= now); - return std::chrono::duration_cast(now - value).count(); + return std::chrono::duration_cast(NonNegative(now - value)).count(); } TimePoint::TimePoint(time_point value_p) : value(value_p) { diff --git a/src/duckdb/src/common/types.cpp b/src/duckdb/src/common/types.cpp index 7fc287e0b..d1642e855 100644 --- a/src/duckdb/src/common/types.cpp +++ b/src/duckdb/src/common/types.cpp @@ -909,7 +909,7 @@ bool LogicalType::SupportsRegularUpdate() const { } } -bool LogicalType::GetDecimalProperties(uint8_t &width, uint8_t &scale) const { +bool LogicalType::GetDecimalProperties(uint32_t &width, uint32_t &scale) const { switch (id()) { case LogicalTypeId::SQLNULL: width = 0; @@ -999,8 +999,8 @@ static LogicalType DecimalSizeCheck(const LogicalType &left, const LogicalType & auto width = DecimalType::GetWidth(right); auto scale = DecimalType::GetScale(right); - uint8_t other_width; - uint8_t other_scale; + uint32_t other_width; + uint32_t other_scale; bool success = left.GetDecimalProperties(other_width, other_scale); if (!success) { throw InternalException("Type provided to DecimalSizeCheck was not a numeric type"); @@ -1008,7 +1008,7 @@ static LogicalType DecimalSizeCheck(const LogicalType &left, const LogicalType & D_ASSERT(other_scale == 0); const auto effective_width = width - scale; if (other_width > effective_width) { - auto new_width = NumericCast(other_width + scale); + uint32_t new_width = other_width + scale; //! Cap the width at max, if an actual value exceeds this, an exception will be thrown later if (new_width > DecimalType::MaxWidth()) { new_width = DecimalType::MaxWidth(); @@ -1455,6 +1455,7 @@ void LogicalType::Serialize(Serializer &serializer) const { LogicalType LogicalType::Deserialize(Deserializer &deserializer) { auto id = deserializer.ReadProperty(100, "id"); + deserializer.CheckAllowed(id); auto type_info = deserializer.ReadPropertyWithDefault>(101, "type_info"); if (id == LogicalTypeId::LEGACY_AGGREGATE_STATE) { // convert legacy aggregate state to blob on deserialize @@ -1543,23 +1544,23 @@ LogicalType LogicalType::WithExtensionInfo(unique_ptr info) c //===--------------------------------------------------------------------===// // Decimal Type //===--------------------------------------------------------------------===// -uint8_t DecimalType::GetWidth(const LogicalType &type) { +uint32_t DecimalType::GetWidth(const LogicalType &type) { D_ASSERT(type.id() == LogicalTypeId::DECIMAL); auto &info = type.GetTypeInfo(); return info.Cast().width; } -uint8_t DecimalType::GetScale(const LogicalType &type) { +uint32_t DecimalType::GetScale(const LogicalType &type) { D_ASSERT(type.id() == LogicalTypeId::DECIMAL); auto &info = type.GetTypeInfo(); return info.Cast().scale; } -uint8_t DecimalType::MaxWidth() { +uint32_t DecimalType::MaxWidth() { return DecimalWidth::max; } -LogicalType LogicalType::DECIMAL(uint8_t width, uint8_t 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)); diff --git a/src/duckdb/src/common/types/cast_helpers.cpp b/src/duckdb/src/common/types/cast_helpers.cpp index 1c97bfc67..ffbd693ea 100644 --- a/src/duckdb/src/common/types/cast_helpers.cpp +++ b/src/duckdb/src/common/types/cast_helpers.cpp @@ -209,7 +209,7 @@ std::string NumericHelper::ToString(uhugeint_t value) { } template <> -int DecimalToString::DecimalLength(hugeint_t value, uint8_t width, uint8_t scale) { +int DecimalToString::DecimalLength(hugeint_t value, uint32_t width, uint32_t scale) { D_ASSERT(value > NumericLimits::Minimum()); int negative; @@ -231,11 +231,11 @@ int DecimalToString::DecimalLength(hugeint_t value, uint8_t width, uint8_t scale // integer length + 1 happens when the number is outside of that range // in that case we print the integer number, but with one extra character ('.') auto extra_numbers = width > scale ? 2 : 1; - return MaxValue(scale + extra_numbers, NumericHelper::UnsignedLength(value) + 1) + negative; + return MaxValue(UnsafeNumericCast(scale) + extra_numbers, NumericHelper::UnsignedLength(value) + 1) + negative; } template <> -string_t DecimalToString::Format(hugeint_t value, uint8_t width, uint8_t scale, StringHeap &heap) { +string_t DecimalToString::Format(hugeint_t value, uint32_t width, uint32_t scale, StringHeap &heap) { int length = DecimalLength(value, width, scale); string_t result = heap.EmptyString(NumericCast(length)); @@ -275,7 +275,7 @@ char *NumericHelper::FormatUnsigned(hugeint_t value, char *ptr) { } template <> -void DecimalToString::FormatDecimal(hugeint_t value, uint8_t width, uint8_t scale, char *dst, idx_t len) { +void DecimalToString::FormatDecimal(hugeint_t value, uint32_t width, uint32_t scale, char *dst, idx_t len) { auto endptr = dst + len; int negative = value.upper < 0; diff --git a/src/duckdb/src/common/types/column/column_data_allocator.cpp b/src/duckdb/src/common/types/column/column_data_allocator.cpp index 377a66c3f..113c4c9c1 100644 --- a/src/duckdb/src/common/types/column/column_data_allocator.cpp +++ b/src/duckdb/src/common/types/column/column_data_allocator.cpp @@ -1,5 +1,6 @@ #include "duckdb/common/types/column/column_data_allocator.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/radix_partitioning.hpp" #include "duckdb/common/types/column/column_data_collection_segment.hpp" @@ -25,17 +26,22 @@ ColumnDataAllocator::ColumnDataAllocator(BufferManager &buffer_manager, ColumnDa ColumnDataAllocator::ColumnDataAllocator(ClientContext &context, ColumnDataAllocatorType allocator_type, ColumnDataCollectionLifetime lifetime) + : ColumnDataAllocator(context.GetContext(), allocator_type, lifetime) { +} + +ColumnDataAllocator::ColumnDataAllocator(Context &context, ColumnDataAllocatorType allocator_type, + ColumnDataCollectionLifetime lifetime) : type(allocator_type) { switch (type) { case ColumnDataAllocatorType::BUFFER_MANAGER_ALLOCATOR: case ColumnDataAllocatorType::HYBRID: - alloc.buffer_manager = &BufferManager::GetBufferManager(context); + alloc.buffer_manager = &context.GetBufferManager(); if (lifetime == ColumnDataCollectionLifetime::THROW_ERROR_AFTER_DATABASE_CLOSES) { - managed_result_set = ResultSetManager::Get(context).Add(*this); + managed_result_set = ResultSetManager::Get(context.GetDatabase()).Add(*this); } break; case ColumnDataAllocatorType::IN_MEMORY_ALLOCATOR: - alloc.allocator = &Allocator::Get(context); + alloc.allocator = &Allocator::Get(context.GetDatabase()); break; default: throw InternalException("Unrecognized column data allocator type"); diff --git a/src/duckdb/src/common/types/column/column_data_collection.cpp b/src/duckdb/src/common/types/column/column_data_collection.cpp index cd41ac023..5b6acfb62 100644 --- a/src/duckdb/src/common/types/column/column_data_collection.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection.cpp @@ -17,6 +17,7 @@ #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/main/database.hpp" #include "duckdb/storage/buffer_manager.hpp" +#include "duckdb/main/client_context.hpp" namespace duckdb { @@ -80,6 +81,11 @@ ColumnDataCollection::ColumnDataCollection(shared_ptr alloc ColumnDataCollection::ColumnDataCollection(ClientContext &context, vector types_p, ColumnDataAllocatorType type, ColumnDataCollectionLifetime lifetime) + : ColumnDataCollection(context.GetContext(), std::move(types_p), type, lifetime) { +} + +ColumnDataCollection::ColumnDataCollection(Context &context, vector types_p, ColumnDataAllocatorType type, + ColumnDataCollectionLifetime lifetime) : ColumnDataCollection(make_shared_ptr(context, type, lifetime), std::move(types_p)) { } diff --git a/src/duckdb/src/common/types/decimal.cpp b/src/duckdb/src/common/types/decimal.cpp index 8fa226455..4f75fb80a 100644 --- a/src/duckdb/src/common/types/decimal.cpp +++ b/src/duckdb/src/common/types/decimal.cpp @@ -3,29 +3,29 @@ #include "duckdb/common/types/cast_helpers.hpp" namespace duckdb { -constexpr uint8_t Decimal::MAX_WIDTH_DECIMAL; +constexpr uint32_t Decimal::MAX_WIDTH_DECIMAL; template -string TemplatedDecimalToString(SIGNED value, uint8_t width, uint8_t scale) { +string TemplatedDecimalToString(SIGNED value, uint32_t width, uint32_t scale) { auto len = DecimalToString::DecimalLength(value, width, scale); auto data = make_unsafe_uniq_array_uninitialized(UnsafeNumericCast(len + 1)); DecimalToString::FormatDecimal(value, width, scale, data.get(), UnsafeNumericCast(len)); return string(data.get(), UnsafeNumericCast(len)); } -string Decimal::ToString(int16_t value, uint8_t width, uint8_t scale) { +string Decimal::ToString(int16_t value, uint32_t width, uint32_t scale) { return TemplatedDecimalToString(value, width, scale); } -string Decimal::ToString(int32_t value, uint8_t width, uint8_t scale) { +string Decimal::ToString(int32_t value, uint32_t width, uint32_t scale) { return TemplatedDecimalToString(value, width, scale); } -string Decimal::ToString(int64_t value, uint8_t width, uint8_t scale) { +string Decimal::ToString(int64_t value, uint32_t width, uint32_t scale) { return TemplatedDecimalToString(value, width, scale); } -string Decimal::ToString(hugeint_t value, uint8_t width, uint8_t scale) { +string Decimal::ToString(hugeint_t value, uint32_t width, uint32_t scale) { auto len = DecimalToString::DecimalLength(value, width, scale); auto data = make_unsafe_uniq_array_uninitialized(UnsafeNumericCast(len + 1)); DecimalToString::FormatDecimal(value, width, scale, data.get(), UnsafeNumericCast(len)); diff --git a/src/duckdb/src/common/types/hugeint.cpp b/src/duckdb/src/common/types/hugeint.cpp index b98611ddb..16024a0b4 100644 --- a/src/duckdb/src/common/types/hugeint.cpp +++ b/src/duckdb/src/common/types/hugeint.cpp @@ -185,11 +185,7 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { return false; } uint64_t upper = uint64_t(result_i128 >> 64); - if (upper & 0x8000000000000000) { - return false; - } - result.upper = int64_t(upper); - result.lower = uint64_t(result_i128 & 0xffffffffffffffff); + uint64_t lower = uint64_t(result_i128 & 0xffffffffffffffff); #else // Multiply code adapted from: // https://github.com/calccrypto/uint128_t/blob/master/uint128_t.cpp @@ -213,8 +209,8 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { return false; } // if the high bits of any of these are set, there is always an overflow - if ((products[0][3] & 0xffffffff80000000) || (products[1][2] & 0xffffffff80000000) || - (products[2][1] & 0xffffffff80000000) || (products[3][0] & 0xffffffff80000000)) { + if ((products[0][3] & 0xffffffff00000000) || (products[1][2] & 0xffffffff00000000) || + (products[2][1] & 0xffffffff00000000) || (products[3][0] & 0xffffffff00000000)) { return false; } @@ -244,7 +240,7 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { first32 += second32 >> 32; // check if the combination of the different products resulted in an overflow - if (first32 & 0xffffff80000000) { + if (first32 & 0xffffffff00000000) { return false; } @@ -255,11 +251,17 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { first32 &= 0xffffffff; // combine components - result.lower = (third32 << 32) | fourth32; - result.upper = (first32 << 32) | second32; + uint64_t lower = (third32 << 32) | fourth32; + uint64_t upper = (first32 << 32) | second32; #endif - if (lhs_negative ^ rhs_negative) { - NegateInPlace(result); + // The magnitude 2**127 fits only with a negative sign, as the minimum. + bool negative = lhs_negative != rhs_negative; + if (upper > 0x8000000000000000 || (upper == 0x8000000000000000 && (!negative || lower != 0))) { + return false; + } + result = hugeint_t(int64_t(upper), lower); + if (negative) { + result = HugeintNegate(result); } return true; } @@ -446,28 +448,25 @@ bool Hugeint::TryCast(hugeint_t input, uhugeint_t &result) { return true; } -template <> -bool Hugeint::TryCast(hugeint_t input, float &result) { - double dbl_result; - Hugeint::TryCast(input, dbl_result); - result = (float)dbl_result; - return true; -} - template bool CastBigintToFloating(hugeint_t input, REAL_T &result) { - switch (input.upper) { - case -1: - // special case for upper = -1 to avoid rounding issues in small negative numbers - result = -REAL_T(NumericLimits::Maximum() - input.lower) - 1; - break; - default: - result = REAL_T(input.lower) + REAL_T(input.upper) * (REAL_T(NumericLimits::Maximum()) + 1); - break; + const bool negative = input.upper < 0; + uhugeint_t magnitude(static_cast(input.upper), input.lower); + if (negative) { + magnitude = -magnitude; + } + Uhugeint::TryCast(magnitude, result); + if (negative) { + result = -result; } return true; } +template <> +bool Hugeint::TryCast(hugeint_t input, float &result) { + return CastBigintToFloating(input, result); +} + template <> bool Hugeint::TryCast(hugeint_t input, double &result) { return CastBigintToFloating(input, result); @@ -553,17 +552,20 @@ bool ConvertFloatingToBigint(REAL_T value, hugeint_t &result) { if (!Value::IsFinite(value)) { return false; } - if (value <= -170141183460469231731687303715884105728.0 || value >= 170141183460469231731687303715884105727.0) { + if (value < -170141183460469231731687303715884105728.0 || value >= 170141183460469231731687303715884105728.0) { return false; } - bool negative = value < 0; + static constexpr REAL_T TWO_TO_THE_64 = REAL_T(18446744073709551616.0); + const bool negative = value < 0; if (negative) { value = -value; } - result.lower = (uint64_t)fmod(value, REAL_T(NumericLimits::Maximum())); - result.upper = (int64_t)(value / REAL_T(NumericLimits::Maximum())); + // The magnitude of the minimum has an upper word of 2**63; it wraps to INT64_MIN, which HugeintNegate keeps. + const auto upper = static_cast(value / TWO_TO_THE_64); + const auto lower = static_cast(std::fmod(value, TWO_TO_THE_64)); + result = hugeint_t(static_cast(upper), lower); if (negative) { - Hugeint::NegateInPlace(result); + result = HugeintNegate(result); } return true; } diff --git a/src/duckdb/src/common/types/interval.cpp b/src/duckdb/src/common/types/interval.cpp index d416360fd..ec03a4a2c 100644 --- a/src/duckdb/src/common/types/interval.cpp +++ b/src/duckdb/src/common/types/interval.cpp @@ -647,6 +647,21 @@ bool Interval::TryAdd(timestamp_t left, interval_t right, timestamp_t &result) { return Timestamp::TryFromDatetime(new_date, new_time, result); } +bool Interval::TryAdd(timestamp_ns_t ns, interval_t interval, timestamp_ns_t &result) { + if (!ns.IsFinite()) { + result = ns; + return true; + } + timestamp_t us; + int64_t nanos; + const auto precision = ns.PRECISION / us.PRECISION; + Timestamp::SplitTime(ns.value, precision, us.value, nanos); + if (!Interval::TryAdd(us, interval, us)) { + return false; + } + return Timestamp::TryCombineUnits(us.value, nanos, precision, result.value); +} + dtime_t Interval::Add(dtime_t left, interval_t right, date_t &date) { int64_t diff = right.micros - ((right.micros / Interval::MICROS_PER_DAY) * Interval::MICROS_PER_DAY); left += diff; @@ -676,4 +691,11 @@ timestamp_t Interval::Add(timestamp_t left, interval_t right) { return Timestamp::FromDatetime(new_date, new_time); } +timestamp_ns_t Interval::Add(timestamp_ns_t ns, interval_t interval) { + if (!TryAdd(ns, interval, ns)) { + throw OutOfRangeException("Cannot add interval to timestamp_ns"); + } + return ns; +} + } // namespace duckdb diff --git a/src/duckdb/src/common/types/row/tuple_data_layout.cpp b/src/duckdb/src/common/types/row/tuple_data_layout.cpp index aa74d8d8e..5fa2ca27b 100644 --- a/src/duckdb/src/common/types/row/tuple_data_layout.cpp +++ b/src/duckdb/src/common/types/row/tuple_data_layout.cpp @@ -7,7 +7,8 @@ namespace duckdb { TupleDataLayout::TupleDataLayout() : sort_key_type(SortKeyType::INVALID), flag_width(0), data_width(0), aggr_width(0), row_width(0), - all_constant(true), heap_size_offset(0), validity_type(TupleDataValidityType::CAN_HAVE_NULL_VALUES) { + trailing_region_width(0), trailing_region_offset(0), all_constant(true), heap_size_offset(0), + validity_type(TupleDataValidityType::CAN_HAVE_NULL_VALUES) { } TupleDataLayout TupleDataLayout::Copy() const { @@ -27,6 +28,8 @@ TupleDataLayout TupleDataLayout::Copy() const { result.sort_width = this->sort_width; result.sort_skippable_bytes = this->sort_skippable_bytes; result.row_width = this->row_width; + result.trailing_region_width = this->trailing_region_width; + result.trailing_region_offset = this->trailing_region_offset; result.offsets = this->offsets; result.all_constant = this->all_constant; result.heap_size_offset = this->heap_size_offset; @@ -36,7 +39,8 @@ TupleDataLayout TupleDataLayout::Copy() const { } void TupleDataLayout::Initialize(vector types_p, Aggregates aggregates_p, - TupleDataValidityType validity_type_p, TupleDataNestednessType nestedness_type) { + TupleDataValidityType validity_type_p, TupleDataNestednessType nestedness_type, + idx_t trailing_region_width_p) { sort_key_type = SortKeyType::INVALID; offsets.clear(); aggr_destructor_idxs.clear(); @@ -129,6 +133,11 @@ void TupleDataLayout::Initialize(vector types_p, Aggregates aggrega } #endif + // The owner-managed trailing region sits after the aggregate states and their padding. + trailing_region_width = AlignValue(trailing_region_width_p); + trailing_region_offset = row_width; + row_width += trailing_region_width; + for (idx_t aggr_idx = 0; aggr_idx < aggregates.size(); aggr_idx++) { const auto &aggr = aggregates[aggr_idx]; if (aggr.function.HasStateDestructorCallback()) { @@ -159,6 +168,8 @@ void TupleDataLayout::Initialize(const vector &orders, const L sort_skippable_bytes.clear(); all_constant = true; heap_size_offset = DConstants::INVALID_INDEX; + trailing_region_width = 0; + trailing_region_offset = 0; aggr_destructor_idxs.clear(); validity_type = TupleDataValidityType::CAN_HAVE_NULL_VALUES; diff --git a/src/duckdb/src/common/types/time.cpp b/src/duckdb/src/common/types/time.cpp index 299708a0e..26732d3fd 100644 --- a/src/duckdb/src/common/types/time.cpp +++ b/src/duckdb/src/common/types/time.cpp @@ -16,6 +16,33 @@ namespace duckdb { static_assert(sizeof(dtime_t) == sizeof(int64_t), "dtime_t was padded"); +static bool OnlySpaceRemains(const char *buf, idx_t len, idx_t &pos) { + while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { + pos++; + } + return pos == len; +} + +// The offset is Z or ±HH[:MM[:SS]] (PG claims they don't support :SS but they do...) +static bool TryParseOffsetSuffix(const char *buf, idx_t len, idx_t &pos, int32_t &offset, bool &has_offset) { + has_offset = !OnlySpaceRemains(buf, len, pos); + int hh = 0; + int mm = 0; + int ss = 0; + if (has_offset && buf[pos] == 'Z') { + pos++; + } else if (has_offset && !Timestamp::TryParseUTCOffset(buf, pos, len, hh, mm, ss)) { + return false; + } + + // Offsets are in seconds in the open interval (-16:00:00, +16:00:00) + offset = ((hh * Interval::MINS_PER_HOUR) + mm) * Interval::SECS_PER_MINUTE + ss; + if (offset < dtime_tz_t::MIN_OFFSET || offset > dtime_tz_t::MAX_OFFSET) { + return false; + } + return OnlySpaceRemains(buf, len, pos); +} + // string format is hh:mm:ss.microsecondsZ // microseconds and Z are optional // ISO 8601 @@ -124,16 +151,8 @@ bool Time::TryConvertInternal(const char *buf, idx_t len, idx_t &pos, dtime_t &r } } - // in strict mode, check remaining string for non-space characters - if (strict) { - // skip trailing spaces - while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { - pos++; - } - // check position. if end was not reached, non-space chars remaining - if (pos < len) { - return false; - } + if (strict && !OnlySpaceRemains(buf, len, pos)) { + return false; } // a negative interval accumulates below zero, so its minimum fits @@ -173,6 +192,12 @@ bool Time::TryConvertTime(const char *buf, idx_t len, idx_t &pos, dtime_t &resul } return false; } + // a TIME drops a UTC offset, as the TIMESTAMP cast does; a strict parse has already rejected one + int32_t offset; + bool has_offset; + if (!TryParseOffsetSuffix(buf, len, pos, offset, has_offset)) { + return false; + } return result.value <= Interval::MICROS_PER_DAY; } @@ -200,40 +225,11 @@ bool Time::TryConvertTimeTZ(const char *buf, idx_t len, idx_t &pos, dtime_tz_t & return false; } - // skip optional whitespace before offset - while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { - pos++; - } - - // Get the ±HH[:MM[:SS]] part - // (PG claims they don't support :SS but they do...) - int hh = 0; - int mm = 0; - int ss = 0; - has_offset = (pos < len); - if (has_offset && !Timestamp::TryParseUTCOffset(buf, pos, len, hh, mm, ss)) { + int32_t offset; + if (!TryParseOffsetSuffix(buf, len, pos, offset, has_offset)) { return false; } - // Offsets are in seconds in the open interval (-16:00:00, +16:00:00) - int32_t offset = ((hh * Interval::MINS_PER_HOUR) + mm) * Interval::SECS_PER_MINUTE + ss; - - if (offset < dtime_tz_t::MIN_OFFSET || offset > dtime_tz_t::MAX_OFFSET) { - return false; - } - - // in strict mode, check remaining string for non-space characters - if (strict) { - // skip trailing spaces - while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { - pos++; - } - // check position. if end was not reached, non-space chars remaining - if (pos < len) { - return false; - } - } - result = dtime_tz_t(time_part, offset); return true; diff --git a/src/duckdb/src/common/types/uhugeint.cpp b/src/duckdb/src/common/types/uhugeint.cpp index 7469dd809..ea9679eed 100644 --- a/src/duckdb/src/common/types/uhugeint.cpp +++ b/src/duckdb/src/common/types/uhugeint.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/bit_utils.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/algorithm.hpp" @@ -317,9 +318,13 @@ bool Uhugeint::TryAddInPlace(uhugeint_t &lhs, uhugeint_t rhs) { } bool Uhugeint::TrySubtractInPlace(uhugeint_t &lhs, uhugeint_t rhs) { - uint64_t new_upper = lhs.upper - rhs.upper - ((lhs.lower - rhs.lower) > lhs.lower); - bool no_overflow = !(new_upper > lhs.upper); - lhs.lower -= rhs.lower; + uint64_t new_lower = lhs.lower - rhs.lower; + uint64_t borrow = new_lower > lhs.lower; + uint64_t new_upper = lhs.upper - rhs.upper - borrow; + // the result is out of range exactly when rhs > lhs, i.e. when the upper half underflows + // either directly or through the borrow of the lower half + bool no_overflow = !(rhs.upper > lhs.upper || (rhs.upper == lhs.upper && borrow)); + lhs.lower = new_lower; lhs.upper = new_upper; return no_overflow; } @@ -403,25 +408,42 @@ bool Uhugeint::TryCast(uhugeint_t input, hugeint_t &result) { return true; } -template <> -bool Uhugeint::TryCast(uhugeint_t input, float &result) { - double dbl_result; - Uhugeint::TryCast(input, dbl_result); - result = (float)dbl_result; - return true; -} - template bool CastUhugeintToFloating(uhugeint_t input, REAL_T &result) { - result = REAL_T(input.lower) + REAL_T(input.upper) * REAL_T(NumericLimits::Maximum()); + static constexpr REAL_T TWO_TO_THE_64 = REAL_T(18446744073709551616.0); + if (std::numeric_limits::digits >= 64) { + // Both halves convert exactly, so the sum is the only rounding. + result = REAL_T(input.upper) * TWO_TO_THE_64 + REAL_T(input.lower); + return true; + } + if (input.upper == 0) { + result = REAL_T(input.lower); + return true; + } + // The top 64 bits with every lower bit folded into the last one round to the mantissa as the whole value does. + const auto leading = CountZeros::Leading(input.upper); + // The lower half shifts in two steps because a shift by 64, when leading is 0, is undefined. + const uint64_t top = + (input.upper << leading) | ((input.lower >> 1) >> (63 - leading)) | uint64_t((input.lower << leading) != 0); + result = REAL_T(top) * REAL_T(uint64_t(1) << (63 - leading)) * REAL_T(2); return true; } +template <> +bool Uhugeint::TryCast(uhugeint_t input, float &result) { + return CastUhugeintToFloating(input, result); +} + template <> bool Uhugeint::TryCast(uhugeint_t input, double &result) { return CastUhugeintToFloating(input, result); } +template <> +bool Uhugeint::TryCast(uhugeint_t input, long double &result) { + return CastUhugeintToFloating(input, result); +} + template uhugeint_t UhugeintConvertInteger(DST input) { uhugeint_t result; @@ -512,8 +534,9 @@ bool ConvertFloatingToUhugeint(REAL_T value, uhugeint_t &result) { if (value < 0 || value >= 340282366920938463463374607431768211456.0) { return false; } - result.lower = (uint64_t)fmod(value, REAL_T(NumericLimits::Maximum())); - result.upper = (uint64_t)(value / REAL_T(NumericLimits::Maximum())); + static constexpr REAL_T TWO_TO_THE_64 = REAL_T(18446744073709551616.0); + result.lower = static_cast(std::fmod(value, TWO_TO_THE_64)); + result.upper = static_cast(value / TWO_TO_THE_64); return true; } diff --git a/src/duckdb/src/common/types/value.cpp b/src/duckdb/src/common/types/value.cpp index 4c91b91fc..a65a0eece 100644 --- a/src/duckdb/src/common/types/value.cpp +++ b/src/duckdb/src/common/types/value.cpp @@ -625,15 +625,15 @@ bool Value::StringIsValid(const char *str, idx_t length) { return utf_type != UnicodeType::INVALID; } -Value Value::DECIMAL(int16_t value, uint8_t width, uint8_t scale) { +Value Value::DECIMAL(int16_t value, uint32_t width, uint32_t scale) { return Value::DECIMAL(int64_t(value), width, scale); } -Value Value::DECIMAL(int32_t value, uint8_t width, uint8_t scale) { +Value Value::DECIMAL(int32_t value, uint32_t width, uint32_t scale) { return Value::DECIMAL(int64_t(value), width, scale); } -Value Value::DECIMAL(int64_t value, uint8_t width, uint8_t scale) { +Value Value::DECIMAL(int64_t value, uint32_t width, uint32_t scale) { auto decimal_type = LogicalType::DECIMAL(width, scale); Value result(decimal_type); switch (decimal_type.InternalType()) { @@ -655,7 +655,7 @@ Value Value::DECIMAL(int64_t value, uint8_t width, uint8_t scale) { return result; } -Value Value::DECIMAL(hugeint_t value, uint8_t width, uint8_t scale) { +Value Value::DECIMAL(hugeint_t value, uint32_t width, uint32_t scale) { D_ASSERT(width >= Decimal::MAX_WIDTH_INT64 && width <= Decimal::MAX_WIDTH_INT128); Value result(LogicalType::DECIMAL(width, scale)); result.value_.hugeint = 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 755844fbe..fd97289ce 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp @@ -240,87 +240,12 @@ vector GetChildIndices(const UnifiedVariantVectorData &variant, idx_t row return child_indices; } -static idx_t AnalyzeValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, - vector &offsets, optional_ptr shredding_state) { - idx_t total_size = 0; +//! The size of a primitive value, the value header included +static idx_t AnalyzePrimitiveValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + VariantLogicalType type_id) { //! Every value has at least a value header - total_size++; - - idx_t offset_size = offsets.size(); - VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; - if (variant.RowIsValid(row)) { - type_id = variant.GetTypeId(row, values_index); - } + idx_t total_size = 1; switch (type_id) { - case VariantLogicalType::OBJECT: { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - //! Calculate value and key offsets for all children - idx_t total_offset = 0; - uint32_t highest_keys_index = 0; - - auto child_indices = GetChildIndices(variant, row, nested_data, shredding_state); - if (nested_data.child_count && child_indices.empty()) { - //! All fields of the object are shredded, omit the object entirely - return 0; - } - - auto num_elements = child_indices.size(); - offsets.resize(offset_size + num_elements + 1); - - for (idx_t entry = 0; entry < child_indices.size(); entry++) { - auto i = child_indices[entry]; - auto keys_index = variant.GetKeysIndex(row, i + nested_data.children_idx); - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); - offsets[offset_size + entry] = NumericCast(total_offset); - - total_offset += AnalyzeValueData(variant, row, values_index, offsets, nullptr); - highest_keys_index = MaxValue(highest_keys_index, keys_index); - } - offsets[offset_size + num_elements] = NumericCast(total_offset); - - //! Calculate the sizes for the objects value data - auto field_id_size = CalculateByteLength(highest_keys_index); - auto field_offset_size = CalculateByteLength(total_offset); - const bool is_large = num_elements > NumericLimits::Maximum(); - - //! Now add the sizes for the objects value data - if (is_large) { - total_size += sizeof(uint32_t); - } else { - total_size += sizeof(uint8_t); - } - total_size += num_elements * field_id_size; - total_size += (num_elements + 1) * field_offset_size; - total_size += total_offset; - break; - } - case VariantLogicalType::ARRAY: { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - idx_t total_offset = 0; - offsets.resize(offset_size + nested_data.child_count + 1); - for (idx_t i = 0; i < nested_data.child_count; i++) { - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); - offsets[offset_size + i] = NumericCast(total_offset); - - total_offset += AnalyzeValueData(variant, row, values_index, offsets, nullptr); - } - offsets[offset_size + nested_data.child_count] = NumericCast(total_offset); - - auto field_offset_size = CalculateByteLength(total_offset); - auto num_elements = nested_data.child_count; - const bool is_large = num_elements > NumericLimits::Maximum(); - - if (is_large) { - total_size += sizeof(uint32_t); - } else { - total_size += sizeof(uint8_t); - } - total_size += (num_elements + 1) * field_offset_size; - total_size += total_offset; - break; - } case VariantLogicalType::BLOB: case VariantLogicalType::VARCHAR: { auto string_value = VariantUtils::DecodeStringData(variant, row, values_index); @@ -410,6 +335,107 @@ static idx_t AnalyzeValueData(const UnifiedVariantVectorData &variant, idx_t row return total_size; } +//! The size of the header of a nested value, the value header, the element count, the field ids and the field offsets +static idx_t NestedHeaderSize(idx_t num_elements, idx_t field_id_size, idx_t field_offset_size) { + idx_t total_size = 1; + if (num_elements > NumericLimits::Maximum()) { + total_size += sizeof(uint32_t); + } else { + total_size += sizeof(uint8_t); + } + total_size += num_elements * field_id_size; + total_size += (num_elements + 1) * field_offset_size; + return total_size; +} + +//! A nested value whose children are being measured. The explicit stack replaces recursion, so the nesting depth of +//! a value is not bounded by the thread stack +struct AnalyzeFrame { + VariantLogicalType type_id; + VariantNestedData nested_data; + //! The children of an object in the order of the Parquet value, unused for an array + vector child_indices; + idx_t num_elements = 0; + //! Where the field offsets of this value start in 'offsets' + idx_t offset_start = 0; + idx_t next_child = 0; + //! The size of the children measured so far + idx_t total_offset = 0; + uint32_t highest_keys_index = 0; +}; + +//! The caller keeps 'stack' across rows, so its capacity is reused +static idx_t AnalyzeValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + vector &offsets, optional_ptr shredding_state, + vector &stack) { + stack.clear(); + auto current = values_index; + for (;;) { + //! Measure 'current', entering it when it is nested + VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; + if (variant.RowIsValid(row)) { + type_id = variant.GetTypeId(row, current); + } + if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { + AnalyzeFrame frame; + frame.type_id = type_id; + frame.nested_data = VariantUtils::DecodeNestedData(variant, row, current); + if (type_id == VariantLogicalType::OBJECT) { + //! The shredding state only applies to the root + frame.child_indices = + GetChildIndices(variant, row, frame.nested_data, stack.empty() ? shredding_state : nullptr); + if (frame.nested_data.child_count && frame.child_indices.empty()) { + //! All fields of the object are shredded, omit the object entirely + D_ASSERT(stack.empty()); + return 0; + } + frame.num_elements = frame.child_indices.size(); + } else { + frame.num_elements = frame.nested_data.child_count; + } + frame.offset_start = offsets.size(); + offsets.resize(frame.offset_start + frame.num_elements + 1); + stack.push_back(std::move(frame)); + } else { + auto size = AnalyzePrimitiveValueData(variant, row, current, type_id); + if (stack.empty()) { + return size; + } + stack.back().total_offset += size; + } + //! Finish the nested values whose children are all measured, then move to the next child + for (;;) { + auto &frame = stack.back(); + if (frame.next_child < frame.num_elements) { + auto child = frame.type_id == VariantLogicalType::OBJECT ? frame.child_indices[frame.next_child] + : frame.next_child; + auto child_position = child + frame.nested_data.children_idx; + offsets[frame.offset_start + frame.next_child] = NumericCast(frame.total_offset); + if (frame.type_id == VariantLogicalType::OBJECT) { + frame.highest_keys_index = + MaxValue(frame.highest_keys_index, variant.GetKeysIndex(row, child_position)); + } + current = variant.GetValuesIndex(row, child_position); + frame.next_child++; + break; + } + //! All children are measured, the header sizes follow from them + offsets[frame.offset_start + frame.num_elements] = NumericCast(frame.total_offset); + idx_t field_id_size = 0; + if (frame.type_id == VariantLogicalType::OBJECT) { + field_id_size = CalculateByteLength(frame.highest_keys_index); + } + auto field_offset_size = CalculateByteLength(frame.total_offset); + auto size = NestedHeaderSize(frame.num_elements, field_id_size, field_offset_size) + frame.total_offset; + stack.pop_back(); + if (stack.empty()) { + return size; + } + stack.back().total_offset += size; + } + } +} + template void WritePrimitiveTypeHeader(data_ptr_t &value_data) { uint8_t value_header = 0; @@ -632,148 +658,166 @@ static void WritePrimitiveValueData(const UnifiedVariantVectorData &variant, idx } } -static void WriteValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, - data_ptr_t &value_data, const vector &offsets, idx_t &offset_index, - optional_ptr shredding_state) { - VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; - if (variant.RowIsValid(row)) { - type_id = variant.GetTypeId(row, values_index); - } - if (type_id == VariantLogicalType::OBJECT) { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - //! -- Object value header -- +//! A nested value whose children are being written +struct WriteFrame { + VariantLogicalType type_id; + VariantNestedData nested_data; + //! The children of an object in the order of the Parquet value, unused for an array + vector child_indices; + idx_t num_elements = 0; + idx_t field_offset_size = 0; + idx_t next_child = 0; + //! The size of the children written so far + idx_t total_offset = 0; + //! Where the next field offset is written + data_ptr_t offsets_ptr = nullptr; + //! Where the next child is written + data_ptr_t children_ptr = nullptr; + //! Where the child being written started + data_ptr_t child_start = nullptr; +}; - auto child_indices = GetChildIndices(variant, row, nested_data, shredding_state); - if (nested_data.child_count && child_indices.empty()) { +//! Writes the header of a nested value, the value header, the element count and for an object the field ids, and +//! leaves the frame ready to write the field offsets and the children +static WriteFrame WriteNestedHeader(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + VariantLogicalType type_id, data_ptr_t &value_data, const vector &offsets, + idx_t &offset_index, optional_ptr shredding_state) { + WriteFrame frame; + frame.type_id = type_id; + frame.nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); + idx_t field_id_size = 0; + if (type_id == VariantLogicalType::OBJECT) { + frame.child_indices = GetChildIndices(variant, row, frame.nested_data, shredding_state); + if (frame.nested_data.child_count && frame.child_indices.empty()) { throw InternalException( "The entire should be omitted, should have been handled by the Analyze step already"); } - auto num_elements = child_indices.size(); + frame.num_elements = frame.child_indices.size(); //! Determine the 'field_id_size' uint32_t highest_keys_index = 0; - for (auto &i : child_indices) { - auto keys_index = variant.GetKeysIndex(row, i + nested_data.children_idx); + for (auto &i : frame.child_indices) { + auto keys_index = variant.GetKeysIndex(row, i + frame.nested_data.children_idx); highest_keys_index = MaxValue(highest_keys_index, keys_index); } - auto field_id_size = CalculateByteLength(highest_keys_index); + field_id_size = CalculateByteLength(highest_keys_index); + } else { + frame.num_elements = frame.nested_data.child_count; + } - uint32_t last_offset = 0; - if (num_elements) { - last_offset = offsets[offset_index + num_elements]; - } - offset_index += num_elements + 1; - auto field_offset_size = CalculateByteLength(last_offset); + uint32_t last_offset = 0; + if (frame.num_elements) { + last_offset = offsets[offset_index + frame.num_elements]; + } + offset_index += frame.num_elements + 1; + frame.field_offset_size = CalculateByteLength(last_offset); - const bool is_large = num_elements > NumericLimits::Maximum(); + const bool is_large = frame.num_elements > NumericLimits::Maximum(); - uint8_t value_header = 0; + uint8_t value_header = 0; + if (type_id == VariantLogicalType::OBJECT) { value_header |= static_cast(VariantBasicType::OBJECT); value_header |= static_cast(is_large) << 6; value_header |= (static_cast(field_id_size) - 1) << 4; - value_header |= (static_cast(field_offset_size) - 1) << 2; - -#ifdef DEBUG - auto object_value_header = VariantValueMetadata::FromHeaderByte(value_header); - D_ASSERT(object_value_header.basic_type == VariantBasicType::OBJECT); - D_ASSERT(object_value_header.is_large == is_large); - D_ASSERT(object_value_header.field_offset_size == field_offset_size); - D_ASSERT(object_value_header.field_id_size == field_id_size); -#endif - - *value_data = value_header; - value_data++; - - //! Write the 'num_elements' - if (is_large) { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint32_t); - } else { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint8_t); - } - - //! Write the 'field_id' entries - for (auto &i : child_indices) { - auto keys_index = variant.GetKeysIndex(row, i + nested_data.children_idx); - memcpy(value_data, reinterpret_cast(&keys_index), field_id_size); - value_data += field_id_size; - } - - //! Write the 'field_offset' entries and the child 'value's - auto children_ptr = value_data + ((num_elements + 1) * field_offset_size); - idx_t total_offset = 0; - for (auto &i : child_indices) { - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); - - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - auto start_ptr = children_ptr; - WriteValueData(variant, row, values_index, children_ptr, offsets, offset_index, nullptr); - total_offset += NumericCast(children_ptr - start_ptr); - } - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - D_ASSERT(children_ptr - total_offset == value_data); - value_data = children_ptr; - } else if (type_id == VariantLogicalType::ARRAY) { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - //! -- Array value header -- - - uint32_t last_offset = 0; - if (nested_data.child_count) { - last_offset = offsets[offset_index + nested_data.child_count]; - } - offset_index += nested_data.child_count + 1; - auto field_offset_size = CalculateByteLength(last_offset); - - auto num_elements = nested_data.child_count; - const bool is_large = num_elements > NumericLimits::Maximum(); - - uint8_t value_header = 0; + value_header |= (static_cast(frame.field_offset_size) - 1) << 2; + } else { value_header |= static_cast(VariantBasicType::ARRAY); value_header |= static_cast(is_large) << 4; - value_header |= (static_cast(field_offset_size) - 1) << 2; + value_header |= (static_cast(frame.field_offset_size) - 1) << 2; + } #ifdef DEBUG - auto array_value_header = VariantValueMetadata::FromHeaderByte(value_header); - D_ASSERT(array_value_header.basic_type == VariantBasicType::ARRAY); - D_ASSERT(array_value_header.is_large == is_large); - D_ASSERT(array_value_header.field_offset_size == field_offset_size); + auto nested_value_header = VariantValueMetadata::FromHeaderByte(value_header); + D_ASSERT(nested_value_header.basic_type == + (type_id == VariantLogicalType::OBJECT ? VariantBasicType::OBJECT : VariantBasicType::ARRAY)); + D_ASSERT(nested_value_header.is_large == is_large); + D_ASSERT(nested_value_header.field_offset_size == frame.field_offset_size); + if (type_id == VariantLogicalType::OBJECT) { + D_ASSERT(nested_value_header.field_id_size == field_id_size); + } #endif - *value_data = value_header; - value_data++; + *value_data = value_header; + value_data++; - //! Write the 'num_elements' - if (is_large) { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint32_t); - } else { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint8_t); - } + //! Write the 'num_elements' + if (is_large) { + Store(static_cast(frame.num_elements), value_data); + value_data += sizeof(uint32_t); + } else { + Store(static_cast(frame.num_elements), value_data); + value_data += sizeof(uint8_t); + } - //! Write the 'field_offset' entries and the child 'value's - auto children_ptr = value_data + ((num_elements + 1) * field_offset_size); - idx_t total_offset = 0; - for (idx_t i = 0; i < nested_data.child_count; i++) { - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); + //! Write the 'field_id' entries + for (auto &i : frame.child_indices) { + auto keys_index = variant.GetKeysIndex(row, i + frame.nested_data.children_idx); + memcpy(value_data, reinterpret_cast(&keys_index), field_id_size); + value_data += field_id_size; + } - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - auto start_ptr = children_ptr; - WriteValueData(variant, row, values_index, children_ptr, offsets, offset_index, nullptr); - total_offset += NumericCast(children_ptr - start_ptr); + //! The 'field_offset' entries come next, the children follow them + frame.offsets_ptr = value_data; + frame.children_ptr = value_data + ((frame.num_elements + 1) * frame.field_offset_size); + return frame; +} + +//! The explicit stack replaces recursion, so the nesting depth of a value is not bounded by the thread stack. The +//! caller keeps it across rows, so its capacity is reused +static void WriteValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + data_ptr_t &value_data, const vector &offsets, idx_t &offset_index, + optional_ptr shredding_state, vector &stack) { + stack.clear(); + auto current = values_index; + auto cursor = value_data; + for (;;) { + //! Write 'current' at 'cursor', entering it when it is nested + VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; + if (variant.RowIsValid(row)) { + type_id = variant.GetTypeId(row, current); + } + if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { + //! The shredding state only applies to the root + stack.push_back(WriteNestedHeader(variant, row, current, type_id, cursor, offsets, offset_index, + stack.empty() ? shredding_state : nullptr)); + } else { + WritePrimitiveValueData(variant, row, current, cursor, offsets, offset_index); + if (stack.empty()) { + value_data = cursor; + return; + } + auto &parent = stack.back(); + parent.total_offset += NumericCast(cursor - parent.child_start); + parent.children_ptr = cursor; + } + //! Finish the nested values whose children are all written, then move to the next child + for (;;) { + auto &frame = stack.back(); + if (frame.next_child < frame.num_elements) { + auto child = frame.type_id == VariantLogicalType::OBJECT ? frame.child_indices[frame.next_child] + : frame.next_child; + memcpy(frame.offsets_ptr, reinterpret_cast(&frame.total_offset), frame.field_offset_size); + frame.offsets_ptr += frame.field_offset_size; + frame.child_start = frame.children_ptr; + cursor = frame.children_ptr; + current = variant.GetValuesIndex(row, child + frame.nested_data.children_idx); + frame.next_child++; + break; + } + //! All children are written, the last field offset is their total size + memcpy(frame.offsets_ptr, reinterpret_cast(&frame.total_offset), frame.field_offset_size); + frame.offsets_ptr += frame.field_offset_size; + D_ASSERT(frame.children_ptr - frame.total_offset == frame.offsets_ptr); + cursor = frame.children_ptr; + stack.pop_back(); + if (stack.empty()) { + value_data = cursor; + return; + } + auto &parent = stack.back(); + parent.total_offset += NumericCast(cursor - parent.child_start); + parent.children_ptr = cursor; } - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - D_ASSERT(children_ptr - total_offset == value_data); - value_data = children_ptr; - } else { - WritePrimitiveValueData(variant, row, values_index, value_data, offsets, offset_index); } } @@ -784,6 +828,8 @@ static void CreateValues(UnifiedVariantVectorData &variant, Vector &value, optio auto &validity = FlatVector::ValidityMutable(value); auto value_data = FlatVector::GetDataMutable(value); + vector analyze_stack; + vector write_stack; for (idx_t i = 0; i < count; i++) { uint32_t value_index = 0; if (value_index_sel) { @@ -815,7 +861,7 @@ static void CreateValues(UnifiedVariantVectorData &variant, Vector &value, optio //! The (relative) offsets for each value, in the case of nesting vector offsets; //! Determine the size of this 'value' blob - idx_t blob_length = AnalyzeValueData(variant, row, value_index, offsets, shredding_state); + idx_t blob_length = AnalyzeValueData(variant, row, value_index, offsets, shredding_state, analyze_stack); if (!blob_length) { //! This is only allowed to happen for a shredded OBJECT, where there are no excess fields to write for the //! OBJECT @@ -829,7 +875,7 @@ static void CreateValues(UnifiedVariantVectorData &variant, Vector &value, optio auto value_blob_data = reinterpret_cast(value_blob.GetDataWriteable()); idx_t offset_index = 0; - WriteValueData(variant, row, value_index, value_blob_data, offsets, offset_index, shredding_state); + WriteValueData(variant, row, value_index, value_blob_data, offsets, offset_index, shredding_state, write_stack); D_ASSERT(data_ptr_cast(value_blob.GetDataWriteable() + blob_length) == value_blob_data); value_blob.SetSizeAndFinalize(NumericCast(blob_length), blob_length); } 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 218458bdc..3aca09623 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp @@ -559,8 +559,8 @@ string_t ParquetVariantNode::GetString() const { VariantDecimalProperties ParquetVariantNode::GetDecimalProperties() const { if (kind == Kind::SHREDDED) { - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; view->typed_type.GetDecimalProperties(width, scale); return VariantDecimalProperties(width, scale); } diff --git a/src/duckdb/src/common/types/variant/variant_comparison.cpp b/src/duckdb/src/common/types/variant/variant_comparison.cpp index e2cd4382f..71d2f03b9 100644 --- a/src/duckdb/src/common/types/variant/variant_comparison.cpp +++ b/src/duckdb/src/common/types/variant/variant_comparison.cpp @@ -12,33 +12,58 @@ constexpr int64_t NANOS_PER_MILLI = 1000000; constexpr int64_t NANOS_PER_SEC = 1000000000; constexpr int64_t NANOS_PER_DAY = 86400LL * NANOS_PER_SEC; +//! Writes the decimal digits of value into the back of buffer (which must hold 20 characters) and +//! returns the offset of the first digit - so no length has to be computed up front. +idx_t UInt64Digits(uint64_t value, char *buffer) { + idx_t pos = 20; + while (value >= 10) { + buffer[--pos] = static_cast('0' + value % 10); + value /= 10; + } + buffer[--pos] = static_cast('0' + value); + return pos; +} + //! Build a number key from a sign, the decimal digits of the magnitude (no leading zeros, as e.g. -//! produced by Uhugeint::ToString) and a base-10 scale (value = magnitude / 10^scale) -VariantNumberKey BuildNumberKey(bool negative, const string &magnitude_digits, int64_t scale) { +//! produced by UInt64Digits) and a base-10 scale (value = magnitude / 10^scale) +VariantNumberKey BuildNumberKey(bool negative, const char *digits, idx_t count, int64_t scale) { VariantNumberKey key; - // find the first non-zero digit (magnitude strings have no leading zeros, but be defensive) + // find the first non-zero digit (magnitude digits have no leading zeros, but be defensive) idx_t first = 0; - while (first < magnitude_digits.size() && magnitude_digits[first] == '0') { + while (first < count && digits[first] == '0') { first++; } - if (first == magnitude_digits.size()) { + if (first == count) { // the value is zero key.number_class = 1; key.adjusted_exponent = 0; + key.digit_count = 0; return key; } key.number_class = negative ? 0 : 2; // position of the leading digit: (#digits after leading zeros - 1) - scale - key.adjusted_exponent = static_cast(magnitude_digits.size() - first) - 1 - scale; + key.adjusted_exponent = NumericCast(count - first) - 1 - scale; // strip trailing zeros (keep at least the leading digit) - idx_t last = magnitude_digits.size(); - while (last > first + 1 && magnitude_digits[last - 1] == '0') { + idx_t last = count; + while (last > first + 1 && digits[last - 1] == '0') { last--; } - key.digits = magnitude_digits.substr(first, last - first); + key.SetDigits(digits + first, last - first); return key; } +//! Build a number key from a 128-bit magnitude, using 64-bit arithmetic whenever the value fits +VariantNumberKey BuildNumberKey(bool negative, uhugeint_t magnitude, int64_t scale) { + if (magnitude.upper == 0) { + char buffer[20]; + auto offset = UInt64Digits(magnitude.lower, buffer); + return BuildNumberKey(negative, buffer + offset, 20 - offset, scale); + } + // magnitudes above 64 bits are rare, and are guaranteed to fit inline (39 digits) + auto magnitude_digits = Uhugeint::ToString(magnitude); + return BuildNumberKey(negative, magnitude_digits.data(), magnitude_digits.size(), scale); +} + //! Decompose a 128-bit signed value (hugeint) into (sign, magnitude) uhugeint_t HugeintMagnitude(const hugeint_t value, bool &negative) { negative = value.upper < 0; @@ -55,17 +80,8 @@ uhugeint_t HugeintMagnitude(const hugeint_t value, bool &negative) { return uhugeint_t(hi, lo); } -//! Decimal-digit string of a 128-bit magnitude. Uses a cheap 64-bit conversion when the value fits in -//! 64 bits, avoiding the slower 128-bit Uhugeint::ToString. -string MagnitudeToString(uhugeint_t magnitude) { - if (magnitude.upper == 0) { - return to_string(magnitude.lower); - } - return Uhugeint::ToString(magnitude); -} - -//! Build a number key from a native (<= 64-bit) integer value, computing the magnitude in 64-bit -//! arithmetic instead of widening every value to uhugeint_t. +//! Build a number key from a native (<= 64-bit) integer value, computing the magnitude and its +//! decimal digits in 64-bit arithmetic instead of widening every value to uhugeint_t. template VariantNumberKey IntegerNumberKey(T value) { bool negative = false; @@ -76,7 +92,9 @@ VariantNumberKey IntegerNumberKey(T value) { magnitude = static_cast(0) - magnitude; // unsigned negate -> |value| (also handles the minimum) } } - return BuildNumberKey(negative, to_string(magnitude), 0); + char buffer[20]; + auto offset = UInt64Digits(magnitude, buffer); + return BuildNumberKey(negative, buffer + offset, 20 - offset, 0); } } // namespace @@ -176,14 +194,14 @@ VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNo } bool negative; const auto magnitude = HugeintMagnitude(unscaled, negative); - return BuildNumberKey(negative, MagnitudeToString(magnitude), decimal_data.scale); + return BuildNumberKey(negative, magnitude, decimal_data.scale); } case VariantLogicalType::BIGNUM: { const auto bignum_blob = node.GetString(); const auto decimal_string = Bignum::BignumToVarchar(bignum_t(bignum_blob)); const bool negative = !decimal_string.empty() && decimal_string[0] == '-'; const idx_t offset = negative ? 1 : 0; - return BuildNumberKey(negative, decimal_string.substr(offset), 0); + return BuildNumberKey(negative, decimal_string.data() + offset, decimal_string.size() - offset, 0); } // integer types - use the native width for the magnitude, only widening to 128-bit when necessary case VariantLogicalType::INT8: @@ -205,10 +223,10 @@ VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNo case VariantLogicalType::INT128: { bool negative; const auto magnitude = HugeintMagnitude(Load(node.GetDataPointer()), negative); - return BuildNumberKey(negative, MagnitudeToString(magnitude), 0); + return BuildNumberKey(negative, magnitude, 0); } case VariantLogicalType::UINT128: - return BuildNumberKey(false, MagnitudeToString(Load(node.GetDataPointer())), 0); + return BuildNumberKey(false, Load(node.GetDataPointer()), 0); default: throw InternalException("VariantGetNumberKey called on non-number type %s", EnumUtil::ToString(type_id)); } diff --git a/src/duckdb/src/common/types/variant/variant_iterator.cpp b/src/duckdb/src/common/types/variant/variant_iterator.cpp index f67c11dd8..b89ddf043 100644 --- a/src/duckdb/src/common/types/variant/variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/variant_iterator.cpp @@ -72,6 +72,84 @@ bool ShreddedIsValid(const ShreddedVariantIterator &node, idx_t index) { return node.unified.validity.RowIsValid(node.unified.sel->get_index(index)); } +//! Resolve the type_id of a shredded layer up-front - it is the same for every value of the layer, +//! except for BOOLEAN (which is BOOL_TRUE or BOOL_FALSE per value) and the layers that are never read +//! as a scalar value (LIST/ARRAY/STRUCT), which are handled structurally by the iterator. +VariantLogicalType ResolveShreddedTypeId(const LogicalType &type, bool &resolved) { + resolved = true; + switch (type.id()) { + case LogicalTypeId::TINYINT: + return VariantLogicalType::INT8; + case LogicalTypeId::SMALLINT: + return VariantLogicalType::INT16; + case LogicalTypeId::INTEGER: + return VariantLogicalType::INT32; + case LogicalTypeId::BIGINT: + return VariantLogicalType::INT64; + case LogicalTypeId::HUGEINT: + return VariantLogicalType::INT128; + case LogicalTypeId::UTINYINT: + return VariantLogicalType::UINT8; + case LogicalTypeId::USMALLINT: + return VariantLogicalType::UINT16; + case LogicalTypeId::UINTEGER: + return VariantLogicalType::UINT32; + case LogicalTypeId::UBIGINT: + return VariantLogicalType::UINT64; + case LogicalTypeId::UHUGEINT: + return VariantLogicalType::UINT128; + case LogicalTypeId::FLOAT: + return VariantLogicalType::FLOAT; + case LogicalTypeId::DOUBLE: + return VariantLogicalType::DOUBLE; + case LogicalTypeId::DECIMAL: + return VariantLogicalType::DECIMAL; + case LogicalTypeId::VARCHAR: + return VariantLogicalType::VARCHAR; + case LogicalTypeId::BLOB: + return VariantLogicalType::BLOB; + case LogicalTypeId::UUID: + return VariantLogicalType::UUID; + case LogicalTypeId::DATE: + return VariantLogicalType::DATE; + case LogicalTypeId::TIME: + return VariantLogicalType::TIME_MICROS; + case LogicalTypeId::TIME_NS: + return VariantLogicalType::TIME_NANOS; + case LogicalTypeId::TIME_TZ: + return VariantLogicalType::TIME_MICROS_TZ; + case LogicalTypeId::TIMESTAMP_SEC: + return VariantLogicalType::TIMESTAMP_SEC; + case LogicalTypeId::TIMESTAMP_MS: + return VariantLogicalType::TIMESTAMP_MILIS; + case LogicalTypeId::TIMESTAMP: + return VariantLogicalType::TIMESTAMP_MICROS; + case LogicalTypeId::TIMESTAMP_NS: + return VariantLogicalType::TIMESTAMP_NANOS; + case LogicalTypeId::TIMESTAMP_TZ: + return VariantLogicalType::TIMESTAMP_MICROS_TZ; + case LogicalTypeId::TIMESTAMP_TZ_NS: + return VariantLogicalType::TIMESTAMP_NANOS_TZ; + case LogicalTypeId::INTERVAL: + return VariantLogicalType::INTERVAL; + case LogicalTypeId::BIGNUM: + return VariantLogicalType::BIGNUM; + case LogicalTypeId::BIT: + return VariantLogicalType::BITSTRING; + case LogicalTypeId::GEOMETRY: + return VariantLogicalType::GEOMETRY; + case LogicalTypeId::STRUCT: + return VariantLogicalType::OBJECT; + case LogicalTypeId::LIST: + return VariantLogicalType::ARRAY; + case LogicalTypeId::BOOLEAN: + // BOOLEAN resolves to BOOL_TRUE / BOOL_FALSE per value + default: + resolved = false; + return VariantLogicalType::VARIANT_NULL; + } +} + } // namespace //===--------------------------------------------------------------------===// @@ -104,6 +182,8 @@ VariantIterator::VariantIterator(const Vector &unshredded_vec, const Vector &shr void ShreddedVariantIterator::Build(const Vector &vec) { vec.ToUnifiedFormat(unified); logical_type = vec.GetType(); + type_size = GetTypeIdSize(unified.physical_type); + type_id = ResolveShreddedTypeId(logical_type, has_fixed_type_id); switch (vec.GetType().InternalType()) { case PhysicalType::LIST: @@ -300,78 +380,17 @@ VariantNode VariantNode::ResolveShredded(const VariantIterator &state, const Shr // Type resolution //===--------------------------------------------------------------------===// static VariantLogicalType ShreddedTypeId(const ShreddedVariantIterator &content, idx_t index) { - auto &type = content.logical_type; - switch (type.id()) { - case LogicalTypeId::STRUCT: - return VariantLogicalType::OBJECT; - case LogicalTypeId::LIST: - return VariantLogicalType::ARRAY; - case LogicalTypeId::BOOLEAN: - return content.unified.GetData()[content.unified.sel->get_index(index)] ? VariantLogicalType::BOOL_TRUE - : VariantLogicalType::BOOL_FALSE; - case LogicalTypeId::TINYINT: - return VariantLogicalType::INT8; - case LogicalTypeId::SMALLINT: - return VariantLogicalType::INT16; - case LogicalTypeId::INTEGER: - return VariantLogicalType::INT32; - case LogicalTypeId::BIGINT: - return VariantLogicalType::INT64; - case LogicalTypeId::HUGEINT: - return VariantLogicalType::INT128; - case LogicalTypeId::UTINYINT: - return VariantLogicalType::UINT8; - case LogicalTypeId::USMALLINT: - return VariantLogicalType::UINT16; - case LogicalTypeId::UINTEGER: - return VariantLogicalType::UINT32; - case LogicalTypeId::UBIGINT: - return VariantLogicalType::UINT64; - case LogicalTypeId::UHUGEINT: - return VariantLogicalType::UINT128; - case LogicalTypeId::FLOAT: - return VariantLogicalType::FLOAT; - case LogicalTypeId::DOUBLE: - return VariantLogicalType::DOUBLE; - case LogicalTypeId::DECIMAL: - return VariantLogicalType::DECIMAL; - case LogicalTypeId::VARCHAR: - return VariantLogicalType::VARCHAR; - case LogicalTypeId::BLOB: - return VariantLogicalType::BLOB; - case LogicalTypeId::UUID: - return VariantLogicalType::UUID; - case LogicalTypeId::DATE: - return VariantLogicalType::DATE; - case LogicalTypeId::TIME: - return VariantLogicalType::TIME_MICROS; - case LogicalTypeId::TIME_NS: - return VariantLogicalType::TIME_NANOS; - case LogicalTypeId::TIME_TZ: - return VariantLogicalType::TIME_MICROS_TZ; - case LogicalTypeId::TIMESTAMP_SEC: - return VariantLogicalType::TIMESTAMP_SEC; - case LogicalTypeId::TIMESTAMP_MS: - return VariantLogicalType::TIMESTAMP_MILIS; - case LogicalTypeId::TIMESTAMP: - return VariantLogicalType::TIMESTAMP_MICROS; - case LogicalTypeId::TIMESTAMP_NS: - return VariantLogicalType::TIMESTAMP_NANOS; - case LogicalTypeId::TIMESTAMP_TZ: - return VariantLogicalType::TIMESTAMP_MICROS_TZ; - case LogicalTypeId::TIMESTAMP_TZ_NS: - return VariantLogicalType::TIMESTAMP_NANOS_TZ; - case LogicalTypeId::INTERVAL: - return VariantLogicalType::INTERVAL; - case LogicalTypeId::BIGNUM: - return VariantLogicalType::BIGNUM; - case LogicalTypeId::BIT: - return VariantLogicalType::BITSTRING; - case LogicalTypeId::GEOMETRY: - return VariantLogicalType::GEOMETRY; - default: - throw NotImplementedException("Shredded VARIANT type '%s' is not supported by VariantNode", type.ToString()); + if (!content.has_fixed_type_id) { + // BOOLEAN is the only layer whose type_id depends on the value + if (content.logical_type.id() == LogicalTypeId::BOOLEAN) { + return content.unified.GetData()[content.unified.sel->get_index(index)] + ? VariantLogicalType::BOOL_TRUE + : VariantLogicalType::BOOL_FALSE; + } + throw NotImplementedException("Shredded VARIANT type '%s' is not supported by VariantNode", + content.logical_type.ToString()); } + return content.type_id; } VariantLogicalType VariantNode::GetTypeId() const { @@ -397,8 +416,7 @@ const_data_ptr_t VariantNode::GetDataPointer() const { } D_ASSERT(kind == Kind::SHREDDED); auto &content = *shredded_format; - auto type_size = GetTypeIdSize(content.unified.physical_type); - return content.unified.data + content.unified.sel->get_index(shredded_index) * type_size; + return content.unified.data + content.unified.sel->get_index(shredded_index) * content.type_size; } string_t VariantNode::GetString() const { @@ -419,8 +437,7 @@ VariantDecimalData VariantNode::GetDecimal() const { auto &type = content.logical_type; auto width = DecimalType::GetWidth(type); auto scale = DecimalType::GetScale(type); - auto type_size = GetTypeIdSize(content.unified.physical_type); - auto value_ptr = content.unified.data + content.unified.sel->get_index(shredded_index) * type_size; + auto value_ptr = content.unified.data + content.unified.sel->get_index(shredded_index) * content.type_size; return VariantDecimalData(width, scale, value_ptr); } diff --git a/src/duckdb/src/common/types/vector_buffer.cpp b/src/duckdb/src/common/types/vector_buffer.cpp index 751027350..12e2f7dd6 100644 --- a/src/duckdb/src/common/types/vector_buffer.cpp +++ b/src/duckdb/src/common/types/vector_buffer.cpp @@ -242,6 +242,26 @@ buffer_ptr VectorBuffer::SliceWithCache(SelCache &cache, const Log return Slice(type, sel, count); } +buffer_ptr VectorBuffer::ConstantReference(const Vector &source, idx_t index, count_t count) { + if (source.GetVectorType() == VectorType::SHREDDED_VECTOR) { + // unshred the source in place once, so that the constants of its rows share the unshredded data + source.Flatten(); + } + auto &buffer = source.Buffer(); + // a constant holds its entry at index zero + auto entry_index = buffer.GetVectorType() == VectorType::CONSTANT_VECTOR ? 0 : index; + auto result = buffer.ConstantReferenceInternal(source.GetType(), entry_index, count); + D_ASSERT(result->GetVectorType() == VectorType::CONSTANT_VECTOR); + D_ASSERT(result->Size() == count); + return result; +} + +buffer_ptr VectorBuffer::ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const { + Vector result(GetValue(type, index), count); + return result.GetBufferRef(); +} + buffer_ptr VectorBuffer::SliceInternal(const LogicalType &type, idx_t offset, idx_t end) { // we can slice the data directly only for standard vectors // for non-flat vectors slice using a selection vector instead diff --git a/src/duckdb/src/common/vector/array_vector.cpp b/src/duckdb/src/common/vector/array_vector.cpp index e88136782..48e5fc796 100644 --- a/src/duckdb/src/common/vector/array_vector.cpp +++ b/src/duckdb/src/common/vector/array_vector.cpp @@ -150,6 +150,25 @@ buffer_ptr VectorArrayBuffer::ConstantSliceInternal(const LogicalT return result; } +buffer_ptr VectorArrayBuffer::ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const { + if (!validity.RowIsValid(index)) { + // the elements of a NULL constant array are NULL as well + return VectorBuffer::ConstantReferenceInternal(type, index, count); + } + // the constant holds the elements of the array, flattened from the child + SelectionVector child_sel(array_size); + for (idx_t elem_idx = 0; elem_idx < array_size; elem_idx++) { + child_sel.set_index(elem_idx, index * array_size + elem_idx); + } + auto result_child = make_uniq(Vector::Ref(*child)); + result_child->Flatten(child_sel, array_size); + auto result = make_buffer(std::move(result_child), array_size, capacity_t(1ULL)); + result->SetVectorType(VectorType::CONSTANT_VECTOR); + result->SetVectorSize(count); + return result; +} + void VectorArrayBuffer::ReserveInternal(idx_t new_size) { // resize the validity validity.Resize(new_size); diff --git a/src/duckdb/src/common/vector/constant_vector.cpp b/src/duckdb/src/common/vector/constant_vector.cpp index d10d266a0..05d0244d4 100644 --- a/src/duckdb/src/common/vector/constant_vector.cpp +++ b/src/duckdb/src/common/vector/constant_vector.cpp @@ -141,98 +141,7 @@ const SelectionVector *ConstantVector::ZeroSelectionVector(idx_t count, Selectio void ConstantVector::Reference(Vector &vector, count_t count, const Vector &source, idx_t position, idx_t source_count) { - auto &source_type = source.GetType(); - switch (source_type.InternalType()) { - case PhysicalType::LIST: { - // retrieve the list entry from the source vector - auto entries = source.Values(); - auto entry = entries[position]; - - if (!entry.IsValid()) { - // list is null: create null value - SetNull(vector, count); - break; - } - - auto list_entry = entry.GetValue(); - - // add the list entry as the first element of "vector" - // FIXME: we only need to allocate space for 1 tuple here - auto target_data = FlatVector::GetDataMutable(vector); - target_data[0] = list_entry; - - // create a reference to the child list of the source vector - auto &child = ListVector::GetChildMutable(vector); - child.Reference(ListVector::GetChild(source)); - - ListVector::SetListSize(vector, ListVector::GetListSize(source)); - vector.SetVectorType(VectorType::CONSTANT_VECTOR); - auto &validity = vector.BufferMutable().GetValidityMask(); - validity.Set(0, true); - FlatVector::SetSize(vector, count); - break; - } - case PhysicalType::ARRAY: { - UnifiedVectorFormat vdata; - source.ToUnifiedFormat(vdata); - auto source_idx = vdata.sel->get_index(position); - if (!vdata.validity.RowIsValid(source_idx)) { - // list is null: create null value - SetNull(vector, count); - break; - } - - // Reference the child vector - auto &target_child = ArrayVector::GetChildMutable(vector); - auto &source_child = ArrayVector::GetChild(source); - target_child.Reference(source_child); - - // Only take the element at the given position - auto array_size = ArrayType::GetSize(source_type); - SelectionVector sel(array_size); - for (idx_t i = 0; i < array_size; i++) { - sel.set_index(i, array_size * source_idx + i); - } - target_child.Slice(sel, array_size); - target_child.Flatten(); // since its constant we only have to flatten this much - - vector.SetVectorType(VectorType::CONSTANT_VECTOR); - auto &validity = vector.BufferMutable().GetValidityMask(); - validity.Set(0, true); - FlatVector::SetSize(vector, count); - break; - } - case PhysicalType::STRUCT: { - UnifiedVectorFormat vdata; - source.ToUnifiedFormat(vdata); - - auto struct_index = vdata.sel->get_index(position); - if (!vdata.validity.RowIsValid(struct_index)) { - // null struct: create null value - SetNull(vector, count); - break; - } - - // struct: pass constant reference into child entries - auto &source_entries = StructVector::GetEntries(source); - auto &target_entries = StructVector::GetEntries(vector); - for (idx_t i = 0; i < source_entries.size(); i++) { - ConstantVector::Reference(target_entries[i], count, source_entries[i], position, source_count); - } - vector.SetVectorType(VectorType::CONSTANT_VECTOR); - auto &validity = vector.BufferMutable().GetValidityMask(); - validity.Set(0, true); - FlatVector::SetSize(vector, count); - break; - } - default: - // default behavior: get a value from the vector and reference it - // this is not that expensive for scalar types - auto value = source.GetValue(position); - vector.Reference(value, count); - D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR); - break; - } + vector.SetBuffer(VectorBuffer::ConstantReference(source, position, count)); } } // namespace duckdb diff --git a/src/duckdb/src/common/vector/dictionary_vector.cpp b/src/duckdb/src/common/vector/dictionary_vector.cpp index 2d9f866c1..a4a2607f4 100644 --- a/src/duckdb/src/common/vector/dictionary_vector.cpp +++ b/src/duckdb/src/common/vector/dictionary_vector.cpp @@ -132,6 +132,11 @@ buffer_ptr DictionaryBuffer::SliceInternal(const LogicalType &type return new_buffer; } +buffer_ptr DictionaryBuffer::ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const { + return ConstantReference(entry->data, sel_vector.get_index(index), count); +} + Value DictionaryBuffer::GetValue(const LogicalType &type, idx_t index) const { if (index >= Size()) { throw InternalException("DictionaryBuffer::GetValue out of range for selection vector"); diff --git a/src/duckdb/src/common/vector/flat_vector.cpp b/src/duckdb/src/common/vector/flat_vector.cpp index fa947dd72..8af80b39b 100644 --- a/src/duckdb/src/common/vector/flat_vector.cpp +++ b/src/duckdb/src/common/vector/flat_vector.cpp @@ -129,6 +129,25 @@ buffer_ptr StandardVectorBuffer::ConstantSliceInternal(const Logic return result; } +buffer_ptr StandardVectorBuffer::ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const { + // copy the entry, which for a string or a list shares the heap or the child of this buffer through CreateBuffer + auto stored_allocator = GetAllocator(); + auto &allocator = stored_allocator ? *stored_allocator : Allocator::DefaultAllocator(); + auto new_data = allocator.Allocate(type_size); + const auto is_valid = validity.RowIsValid(index); + if (is_valid) { + memcpy(new_data.get(), data_ptr + index * type_size, type_size); + } + auto result = CreateBuffer(std::move(new_data), count_t(1ULL)); + if (!is_valid) { + result->GetValidityMask().SetInvalid(0); + } + result->SetVectorType(VectorType::CONSTANT_VECTOR); + result->SetVectorSize(count); + return result; +} + buffer_ptr StandardVectorBuffer::SliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) { if (!sel.IsSet()) { diff --git a/src/duckdb/src/common/vector/fsst_vector.cpp b/src/duckdb/src/common/vector/fsst_vector.cpp index 343785466..f4e276734 100644 --- a/src/duckdb/src/common/vector/fsst_vector.cpp +++ b/src/duckdb/src/common/vector/fsst_vector.cpp @@ -37,6 +37,17 @@ Value VectorFSSTStringBuffer::GetValue(const LogicalType &type, idx_t index) con } } +buffer_ptr VectorFSSTStringBuffer::ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const { + // the compressed string cannot be shared, so the constant holds the decompressed string + auto source_index = UnsafeNumericCast(index); + SelectionVector sel(&source_index, 1); + auto result = FlattenSliceInternal(type, sel, 1); + result->SetVectorType(VectorType::CONSTANT_VECTOR); + result->SetVectorSize(count); + return result; +} + buffer_ptr VectorFSSTStringBuffer::FlattenSliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) const { auto result = make_buffer(capacity_t(count)); diff --git a/src/duckdb/src/common/vector/struct_vector.cpp b/src/duckdb/src/common/vector/struct_vector.cpp index e11f3a262..7a518e4e9 100644 --- a/src/duckdb/src/common/vector/struct_vector.cpp +++ b/src/duckdb/src/common/vector/struct_vector.cpp @@ -172,6 +172,22 @@ buffer_ptr VectorStructBuffer::ConstantSliceInternal(const Logical return result; } +buffer_ptr VectorStructBuffer::ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const { + if (!validity.RowIsValid(index)) { + // the children of a NULL constant struct are NULL as well + return VectorBuffer::ConstantReferenceInternal(type, index, count); + } + vector result_children; + for (auto &child : children) { + result_children.emplace_back(child.GetType(), ConstantReference(child, index, count)); + } + auto result = make_buffer(std::move(result_children), capacity_t(1ULL)); + result->SetVectorType(VectorType::CONSTANT_VECTOR); + result->SetVectorSize(count); + return result; +} + void VectorStructBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { if (vector_type == VectorType::CONSTANT_VECTOR) { format.sel = ConstantVector::ZeroSelectionVector(Size(), format.owned_sel); diff --git a/src/duckdb/src/common/vector_operations/vector_hash.cpp b/src/duckdb/src/common/vector_operations/vector_hash.cpp index 8a303ca2e..664a52015 100644 --- a/src/duckdb/src/common/vector_operations/vector_hash.cpp +++ b/src/duckdb/src/common/vector_operations/vector_hash.cpp @@ -131,12 +131,26 @@ void StructLoopHash(const Vector &input, Vector &hashes, const SelectionVector * } } -template -void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { - // FIXME: if we want to be more efficient we shouldn't flatten, but the logic here currently requires it +template +hash_t *FlattenHashesForCombine(Vector &hashes, const SelectionVector *rsel, idx_t count) { + const bool is_constant = hashes.GetVectorType() == VectorType::CONSTANT_VECTOR; + const hash_t constant_hash = is_constant ? *ConstantVector::GetData(hashes) : 0; hashes.Flatten(); FlatVector::SetSize(hashes, count_t(count)); auto hdata = FlatVector::GetDataMutable(hashes); + if (is_constant) { + // Flatten fills only the first Size() slots, but a selection reads and writes the hashes at its own positions. + for (idx_t i = 0; i < count; i++) { + hdata[HAS_RSEL ? rsel->get_index(i) : i] = constant_hash; + } + } + return hdata; +} + +template +void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { + // FIXME: if we want to be more efficient we shouldn't flatten, but the logic here currently requires it + auto hdata = FlattenHashesForCombine(hashes, rsel, count); UnifiedVectorFormat idata; input.ToUnifiedFormat(idata); @@ -225,9 +239,7 @@ void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rs template void ArrayLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { - hashes.Flatten(); - FlatVector::SetSize(hashes, count_t(count)); - auto hdata = FlatVector::GetDataMutable(hashes); + auto hdata = FlattenHashesForCombine(hashes, rsel, count); UnifiedVectorFormat idata; input.ToUnifiedFormat(idata); diff --git a/src/duckdb/src/common/virtual_file_system.cpp b/src/duckdb/src/common/virtual_file_system.cpp index 6dd55a17b..c037480ba 100644 --- a/src/duckdb/src/common/virtual_file_system.cpp +++ b/src/duckdb/src/common/virtual_file_system.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/virtual_file_system.hpp" #include "duckdb/common/compressed_file_system.hpp" @@ -13,6 +14,8 @@ #include "duckdb/main/database.hpp" #include "duckdb/main/extension_helper.hpp" +#include + namespace duckdb { struct FileSystemHandle { @@ -244,7 +247,11 @@ unique_ptr VirtualFileSystem::OpenFileExtended(const OpenFileInfo &f try { // Evaluate and apply compression option then. - const auto context = !flags.MultiClientAccess() ? FileOpener::TryGetClientContext(opener) : QueryContext(); + QueryContext context; + auto opener_context = FileOpener::TryGetContext(opener); + if (opener_context && !flags.MultiClientAccess()) { + context = QueryContext(*opener_context); + } if (file_handle->GetType() == FileType::FILE_TYPE_FIFO) { file_handle = PipeFileSystem::OpenPipe(context, std::move(file_handle)); } else { @@ -413,6 +420,17 @@ void VirtualFileSystem::SetDisabledFileSystems(const vector &names) { file_system_registry.atomic_store(new_registry); } +vector VirtualFileSystem::GetDisabledFileSystems() { + auto registry = file_system_registry.atomic_load(); + auto &disabled_file_systems = registry->disabled_file_systems; + vector names; + for (auto &name : disabled_file_systems) { + names.push_back(name); + } + std::sort(names.begin(), names.end()); + return names; +} + unique_ptr VirtualFileSystem::ExtractSubSystem(const string &name) { lock_guard guard(registry_lock); unique_ptr result; diff --git a/src/duckdb/src/execution/aggregate_hashtable.cpp b/src/duckdb/src/execution/aggregate_hashtable.cpp index df58b3893..f922e4535 100644 --- a/src/duckdb/src/execution/aggregate_hashtable.cpp +++ b/src/duckdb/src/execution/aggregate_hashtable.cpp @@ -55,7 +55,7 @@ GroupedAggregateHashTable::GroupedAggregateHashTable(ClientContext &context_p, A vector payload_types_p, vector aggregate_objects_p, idx_t initial_capacity, idx_t radix_bits, - TupleDataValidityType group_validity) + TupleDataValidityType group_validity, idx_t trailing_region_width) : BaseAggregateHashTable(context_p, allocator, aggregate_objects_p, std::move(payload_types_p)), context(context_p), radix_bits(radix_bits), count(0), capacity(0), aggregate_allocator(make_shared_ptr(allocator)), state(*aggregate_allocator) { @@ -71,7 +71,8 @@ GroupedAggregateHashTable::GroupedAggregateHashTable(ClientContext &context_p, A group_types_p.emplace_back(LogicalType::HASH); auto layout = make_shared_ptr(); - layout->Initialize(std::move(group_types_p), std::move(aggregate_objects_p), group_validity); + layout->Initialize(std::move(group_types_p), std::move(aggregate_objects_p), group_validity, + TupleDataNestednessType::TOP_LEVEL_LAYOUT, trailing_region_width); layout_ptr = std::move(layout); hash_offset = layout_ptr->GetOffsets()[layout_ptr->ColumnCount() - 1]; @@ -719,6 +720,8 @@ bool GroupedAggregateHashTable::UpdateAggregatesClustered(DataChunk &payload, co void GroupedAggregateHashTable::UpdateAggregates(DataChunk &payload, const unsafe_vector &filter, idx_t count, bool ht_offsets_valid) { + // evaluate every aggregate filter once for this chunk + filter_set.ApplyFilters(payload, filter); if (UpdateAggregatesClustered(payload, filter, count, ht_offsets_valid)) { Verify(); return; @@ -739,7 +742,7 @@ void GroupedAggregateHashTable::UpdateAggregates(DataChunk &payload, const unsaf if (aggr.aggr_type != AggregateType::DISTINCT && aggr.filter) { RowOperations::UpdateFilteredStates(state.row_state, filter_set.GetFilterData(i), aggr, state.addresses, - payload, payload_idx); + payload_idx); } else { RowOperations::UpdateStates(state.row_state, aggr, state.addresses, payload, payload_idx); } @@ -891,6 +894,7 @@ idx_t GroupedAggregateHashTable::FindOrCreateGroupsInternal(DataChunk &groups, V *FlatVector::IncrementalSelectionVector(), chunk_size); RowOperations::InitializeStates(*layout_ptr, state.partitioned_append_state.chunk_state.row_locations, *FlatVector::IncrementalSelectionVector(), chunk_size); + ZeroTrailingRegion(state.partitioned_append_state.chunk_state.row_locations, chunk_size); } const auto row_locations = @@ -961,6 +965,7 @@ idx_t GroupedAggregateHashTable::FindOrCreateGroupsInternal(DataChunk &groups, V data->AppendUnified(*append_state, state.group_chunk, empty_vector, new_entry_count); RowOperations::InitializeStates(*layout_ptr, append_state->chunk_state.row_locations, *FlatVector::IncrementalSelectionVector(), new_entry_count); + ZeroTrailingRegion(append_state->chunk_state.row_locations, new_entry_count); } // Set the entry pointers in the 1st part of the HT now that the data has been appended @@ -1196,6 +1201,18 @@ struct FlushMoveState { SelectionVector new_groups_sel; }; +void GroupedAggregateHashTable::ZeroTrailingRegion(Vector &row_locations, idx_t count) const { + const auto region_width = layout_ptr->GetTrailingRegionWidth(); + if (region_width == 0) { + return; + } + const auto region_offset = layout_ptr->GetTrailingRegionOffset(); + const auto locations = FlatVector::GetData(row_locations); + for (idx_t row_idx = 0; row_idx < count; row_idx++) { + memset(locations[row_idx] + region_offset, 0, region_width); + } +} + void GroupedAggregateHashTable::Combine(GroupedAggregateHashTable &other) { auto other_partitioned_data = other.AcquirePartitionedData(); auto other_data = other_partitioned_data->GetUnpartitioned(); @@ -1212,6 +1229,9 @@ void GroupedAggregateHashTable::Combine(TupleDataCollection &other_data, optiona D_ASSERT(other_data.GetLayout().GetAggrWidth() == layout_ptr->GetAggrWidth()); D_ASSERT(other_data.GetLayout().GetDataWidth() == layout_ptr->GetDataWidth()); D_ASSERT(other_data.GetLayout().GetRowWidth() == layout_ptr->GetRowWidth()); + // New groups copy whole source rows, so a trailing region arrives as the source left it: owners must only + // scatter region values into the table that survives the combine, never into the sources consumed here. + D_ASSERT(other_data.GetLayout().GetTrailingRegionWidth() == layout_ptr->GetTrailingRegionWidth()); if (other_data.Count() == 0) { return; diff --git a/src/duckdb/src/execution/expression_executor.cpp b/src/duckdb/src/execution/expression_executor.cpp index aeeeaefc7..d8ac438f6 100644 --- a/src/duckdb/src/execution/expression_executor.cpp +++ b/src/duckdb/src/execution/expression_executor.cpp @@ -140,6 +140,11 @@ void ExpressionExecutor::ExecuteExpression(idx_t expr_idx, Vector &result) { Execute(*expressions[expr_idx], states[expr_idx]->root_state.get(), nullptr, chunk ? chunk->size() : 1, result); } +void ExpressionExecutor::ExecuteExpression(idx_t expr_idx, Vector &result, const SelectionVector &sel, idx_t count) { + D_ASSERT(expr_idx < expressions.size()); + Execute(*expressions[expr_idx], states[expr_idx]->root_state.get(), &sel, count, result); +} + Value ExpressionExecutor::EvaluateScalar(ClientContext &context, const Expression &expr, bool allow_unfoldable) { D_ASSERT(allow_unfoldable || expr.IsFoldable()); D_ASSERT(expr.IsScalar()); @@ -342,6 +347,20 @@ idx_t ExpressionExecutor::DefaultSelect(const Expression &expr, ExpressionState Vector intermediate(LogicalType::BOOLEAN, data_ptr_cast(intermediate_bools), STANDARD_VECTOR_SIZE); Execute(expr, state, sel, count, intermediate); + if (!sel && intermediate.GetVectorType() == VectorType::FLAT_VECTOR && + !FlatVector::Validity(intermediate).CanHaveNull()) { + optional> true_output; + optional> false_output; + if (true_sel) { + true_output = array_ptr(true_sel->data(), true_sel->Capacity()); + } + if (false_sel) { + false_output = array_ptr(false_sel->data(), false_sel->Capacity()); + } + return SelectionVector::SelectFromBoolean(FlatVector::GetData(intermediate), nullptr, count, true_output, + false_output); + } + return UnaryExecutor::Select( intermediate, sel, count, [](uint8_t value) { return value > 0; }, true_sel, false_sel); } diff --git a/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp b/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp index 7a9414dde..2f2ba803c 100644 --- a/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp @@ -13,7 +13,7 @@ struct ConjunctionState : public ExpressionState { ConjunctionState(const Expression &expr, ExpressionExecutorState &root) : ExpressionState(expr, root) { adaptive_filter = make_uniq(expr); if (HasContext()) { - adaptive_filter->SetLogger(GetContext().logger); + adaptive_filter->SetLogger(GetContext().GetContext().GetLoggerPtr()); } } unique_ptr adaptive_filter; diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index e1d6127ce..a6f258713 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -723,6 +723,15 @@ void ART::ResetStorage(IndexLock &index_lock) { root_ptr.Clear(); } +void ART::DisownStorage(IndexLock &index_lock) { + index_lock.AssertHeld(*this); + D_ASSERT(owns_data); + for (auto &allocator : *allocators) { + allocator->DisownBuffers(); + } + root_ptr.Clear(); +} + idx_t ART::TryDelete(IndexLock &state, DataChunk &entries, Vector &row_ids, optional_ptr deleted_sel, optional_ptr non_deleted_sel) { state.AssertHeld(*this); diff --git a/src/duckdb/src/execution/index/bound_index.cpp b/src/duckdb/src/execution/index/bound_index.cpp index 4b22a7e57..813d092a6 100644 --- a/src/duckdb/src/execution/index/bound_index.cpp +++ b/src/duckdb/src/execution/index/bound_index.cpp @@ -61,6 +61,15 @@ void BoundIndex::ResetStorage() { ResetStorage(index_lock); } +void BoundIndex::DisownStorage(IndexLock &index_lock) { + // Indexes that do not reference on-disk blocks of their storage information have nothing to disown. +} + +void BoundIndex::DisownStorage() { + IndexLock index_lock(*this); + DisownStorage(index_lock); +} + idx_t BoundIndex::TryDelete(DataChunk &entries, Vector &row_identifiers, optional_ptr deleted_sel, optional_ptr non_deleted_sel) { IndexLock state(*this); diff --git a/src/duckdb/src/execution/index/fixed_size_allocator.cpp b/src/duckdb/src/execution/index/fixed_size_allocator.cpp index a1f9af99d..feec2bd04 100644 --- a/src/duckdb/src/execution/index/fixed_size_allocator.cpp +++ b/src/duckdb/src/execution/index/fixed_size_allocator.cpp @@ -144,6 +144,13 @@ void FixedSizeAllocator::Reset() { total_segment_count = 0; } +void FixedSizeAllocator::DisownBuffers() { + for (auto &buffer : buffers) { + buffer.second->DisownBlock(); + } + Reset(); +} + idx_t FixedSizeAllocator::GetInMemorySize() const { idx_t memory_usage = 0; for (auto &buffer : buffers) { @@ -375,8 +382,9 @@ void FixedSizeAllocator::Init(const FixedSizeAllocatorInfo &info) { // create the FixedSizeBuffer if (info.transient_block_handles) { D_ASSERT(info.transient_block_handles->size() == info.buffer_ids.size()); + // The storage information keeps its handle, so that a bind that fails after this point can be retried. buffers[buffer_id] = make_shared_ptr(block_manager, segment_count, allocation_size, - std::move((*info.transient_block_handles)[i])); + (*info.transient_block_handles)[i]); } else { buffers[buffer_id] = make_shared_ptr(block_manager, segment_count, allocation_size, buffer_block_pointer); diff --git a/src/duckdb/src/execution/index/fixed_size_buffer.cpp b/src/duckdb/src/execution/index/fixed_size_buffer.cpp index a13316f1a..f9052f29c 100644 --- a/src/duckdb/src/execution/index/fixed_size_buffer.cpp +++ b/src/duckdb/src/execution/index/fixed_size_buffer.cpp @@ -46,7 +46,7 @@ FixedSizeBuffer::FixedSizeBuffer(BlockManager &block_manager, const idx_t segmen : block_manager(block_manager), readers(0), segment_count(segment_count), allocation_size(allocation_size), dirty(false), vacuum(false), loaded(false), block_pointer(block_pointer) { D_ASSERT(block_pointer.IsValid()); - block_handle = block_manager.RegisterBlock(block_pointer.block_id, MemoryTag::ART_INDEX); + block_handle = block_manager.RegisterBlock(block_pointer.block_id, MemoryTag::BASE_TABLE); D_ASSERT(block_handle->BlockId() < MAXIMUM_BLOCK); } @@ -69,6 +69,11 @@ FixedSizeBuffer::~FixedSizeBuffer() { } } +void FixedSizeBuffer::DisownBlock() { + lock_guard l(lock); + block_pointer = BlockPointer(); +} + void FixedSizeBuffer::Finalize(shared_ptr block_handle_p, uint32_t offset) { D_ASSERT(readers == 0); D_ASSERT(!buffer_handle.IsValid()); @@ -102,7 +107,7 @@ shared_ptr FixedSizeBuffer::Persist(PartialBlockManager &partia D_ASSERT(new_block_pointer); // 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::ART_INDEX); + result->block_handle = block_manager.RegisterBlock(new_block_pointer->block_id, MemoryTag::BASE_TABLE); return result; } diff --git a/src/duckdb/src/execution/index/unbound_index.cpp b/src/duckdb/src/execution/index/unbound_index.cpp index 66b9c8a84..2e7996a8e 100644 --- a/src/duckdb/src/execution/index/unbound_index.cpp +++ b/src/duckdb/src/execution/index/unbound_index.cpp @@ -61,10 +61,18 @@ IndexCheckpointResult UnboundIndex::Checkpoint(PartialBlockManager &, StorageVer unique_ptr UnboundIndex::Bind(IndexBinder &binder, const vector &physical_column_types) { auto bound_index = binder.BindIndex(*this); - storage_reclaimed = true; + // The bound index references the blocks of storage_info from here on, but this index keeps owning them until + // the buffered rows are replayed, so that a bind that fails during the replay leaves this index intact for a + // retry. Destroying the bound index would otherwise free the blocks this index still references. if (HasBufferedReplays()) { - bound_index->ApplyBufferedReplays(physical_column_types, buffered_replays, mapped_column_ids); + try { + bound_index->ApplyBufferedReplays(physical_column_types, buffered_replays, mapped_column_ids); + } catch (...) { + bound_index->DisownStorage(); + throw; + } } + storage_reclaimed = true; return bound_index; } diff --git a/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp b/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp index 31ae1cc91..12896a69d 100644 --- a/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp +++ b/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp @@ -1,5 +1,7 @@ #include "duckdb/execution/operator/aggregate/aggregate_object.hpp" +#include "duckdb/common/algorithm.hpp" +#include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" @@ -40,20 +42,21 @@ vector AggregateObject::CreateAggregateObjects(const vector &payload_types) - : filter_executor(context, &filter_expr), true_sel(STANDARD_VECTOR_SIZE) { - if (payload_types.empty()) { - return; - } - filtered_payload.Initialize(Allocator::Get(context), payload_types); + DataChunk &filtered_payload) + : filter_executor(context, &filter_expr), filtered_payload(filtered_payload), true_sel(STANDARD_VECTOR_SIZE) { } -idx_t AggregateFilterData::ApplyFilter(DataChunk &payload) { - filtered_payload.Reset(); +idx_t AggregateFilterData::Select(DataChunk &chunk) { + selected_count = filter_executor.SelectExpression(chunk, true_sel); + return selected_count; +} - auto count = filter_executor.SelectExpression(payload, true_sel); - filtered_payload.Slice(payload, true_sel, count); - return count; +idx_t AggregateFilterData::ApplyFilter(DataChunk &payload) { + Select(payload); + for (auto col_idx : sliced_columns) { + filtered_payload.data[col_idx].Slice(payload.data[col_idx], true_sel, selected_count); + } + return selected_count; } AggregateFilterDataSet::AggregateFilterDataSet() { @@ -72,18 +75,55 @@ void AggregateFilterDataSet::Initialize(ClientContext &context, const vector(); + filtered_payload->InitializeEmpty(payload_types); + aggregate_filter_idx.resize(aggregates.size(), DConstants::INVALID_INDEX); + expression_map_t filter_indexes; + idx_t payload_idx = 0; for (idx_t aggr_idx = 0; aggr_idx < aggregates.size(); aggr_idx++) { auto &aggr = aggregates[aggr_idx]; if (aggr.filter) { - filter_data[aggr_idx] = make_uniq(context, *aggr.filter, payload_types); + // aggregates with an identical filter share the filter data + auto entry = filter_indexes.find(*aggr.filter); + if (entry == filter_indexes.end()) { + entry = filter_indexes.emplace(*aggr.filter, filter_data.size()).first; + filter_data.push_back(make_uniq(context, *aggr.filter, *filtered_payload)); + } + aggregate_filter_idx[aggr_idx] = entry->second; + if (!aggr.IsDistinct()) { + auto &data = *filter_data[entry->second]; + data.aggregates.push_back(aggr_idx); + for (idx_t i = 0; i < aggr.child_count; i++) { + data.sliced_columns.push_back(payload_idx + i); + } + } } + payload_idx += aggr.child_count; } } AggregateFilterData &AggregateFilterDataSet::GetFilterData(idx_t aggr_idx) { - D_ASSERT(aggr_idx < filter_data.size()); - D_ASSERT(filter_data[aggr_idx]); - return *filter_data[aggr_idx]; + D_ASSERT(aggr_idx < aggregate_filter_idx.size()); + D_ASSERT(aggregate_filter_idx[aggr_idx] != DConstants::INVALID_INDEX); + return *filter_data[aggregate_filter_idx[aggr_idx]]; } + +static bool UsesFilter(const unsafe_vector &aggregate_indices, const AggregateFilterData &data) { + for (auto aggr_idx : data.aggregates) { + if (std::find(aggregate_indices.begin(), aggregate_indices.end(), aggr_idx) != aggregate_indices.end()) { + return true; + } + } + return false; +} + +void AggregateFilterDataSet::ApplyFilters(DataChunk &payload, + optional_ptr> aggregate_indices) { + for (auto &data : filter_data) { + if (!aggregate_indices || UsesFilter(*aggregate_indices, *data)) { + data->ApplyFilter(payload); + } + } +} + } // namespace duckdb 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 04e9350c8..bd464d56d 100644 --- a/src/duckdb/src/execution/operator/aggregate/grouped_aggregate_data.cpp +++ b/src/duckdb/src/execution/operator/aggregate/grouped_aggregate_data.cpp @@ -1,5 +1,7 @@ #include "duckdb/execution/operator/aggregate/grouped_aggregate_data.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" + namespace duckdb { idx_t GroupedAggregateData::GroupCount() const { @@ -14,7 +16,6 @@ void GroupedAggregateData::InitializeGroupby(vector> grou vector> expressions, vector> grouping_functions) { InitializeGroupbyGroups(std::move(groups)); - vector payload_types_filters; SetGroupingFunctions(grouping_functions); @@ -29,18 +30,33 @@ void GroupedAggregateData::InitializeGroupby(vector> grou for (auto &child : aggr.GetChildren()) { payload_types.push_back(child->GetReturnType()); } - if (aggr.GetFilter()) { - filter_count++; - payload_types_filters.push_back(aggr.GetFilter()->GetReturnType()); - } if (!aggr.Function().HasStateCombineCallback()) { throw InternalException("Aggregate function %s is missing a combine method", aggr.Function().GetName()); } aggregates.push_back(std::move(expr)); } - for (const auto &pay_filters : payload_types_filters) { - payload_types.push_back(pay_filters); +} + +unordered_map GroupedAggregateData::AddFilterColumns(const vector> &aggregates, + vector &payload_types) { + // identical filters reference the same input column and share one payload column + unordered_map payload_columns; + unordered_map filter_columns; + for (auto &aggregate : aggregates) { + auto &aggr = aggregate->Cast(); + if (!aggr.GetFilter()) { + continue; + } + auto &filter_ref = aggr.GetFilterMutable()->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; } + return filter_columns; } void GroupedAggregateData::InitializeDistinct(const unique_ptr &aggregate, diff --git a/src/duckdb/src/execution/operator/aggregate/physical_hash_aggregate.cpp b/src/duckdb/src/execution/operator/aggregate/physical_hash_aggregate.cpp index d15518047..9ecb2e4da 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_hash_aggregate.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_hash_aggregate.cpp @@ -96,7 +96,7 @@ static vector CreateGroupChunkTypes(vector> } bool PhysicalHashAggregate::CanSkipRegularSink() const { - if (!filter_indexes.empty()) { + if (!filter_columns.empty()) { // If we have filters, we can't skip the regular sink, because we might lose groups otherwise. return false; } @@ -149,13 +149,9 @@ PhysicalHashAggregate::PhysicalHashAggregate(PhysicalPlan &physical_plan, Client std::move(grouping_functions_p)); auto &aggregates = grouped_aggregate_data.aggregates; - // filter_indexes must be pre-built, not lazily instantiated in parallel... - // Because everything that lives in this class should be read-only at execution time - idx_t aggregate_input_idx = 0; for (idx_t i = 0; i < aggregates.size(); i++) { auto &aggregate = aggregates[i]; auto &aggr = aggregate->Cast(); - aggregate_input_idx += aggr.GetChildren().size(); if (aggr.GetAggregateType() == AggregateType::DISTINCT) { distinct_filter.push_back(i); } else if (aggr.GetAggregateType() == AggregateType::NON_DISTINCT) { @@ -165,20 +161,8 @@ PhysicalHashAggregate::PhysicalHashAggregate(PhysicalPlan &physical_plan, Client } // LCOV_EXCL_STOP } - for (idx_t i = 0; i < aggregates.size(); i++) { - auto &aggregate = aggregates[i]; - auto &aggr = aggregate->Cast(); - if (aggr.GetFilter()) { - auto &filter_ref = *aggr.GetFilter(); - auto &bound_ref_expr = filter_ref.Cast(); - if (!filter_indexes.count(filter_ref)) { - // Replace the bound reference expression's index with the corresponding index of the payload chunk - filter_indexes[filter_ref] = bound_ref_expr.Index(); - bound_ref_expr.IndexMutable() = aggregate_input_idx; - } - aggregate_input_idx++; - } - } + // filter_columns must be pre-built: everything that lives in this class is read-only at execution time + filter_columns = GroupedAggregateData::AddFilterColumns(aggregates, grouped_aggregate_data.payload_types); distinct_collection_info = DistinctAggregateCollectionInfo::Create(grouped_aggregate_data.aggregates); @@ -199,18 +183,7 @@ class HashAggregateGlobalSinkState : public GlobalSinkState { auto &grouping = op.groupings[i]; grouping_states.emplace_back(grouping, context); } - vector filter_types; - for (auto &aggr : op.grouped_aggregate_data.aggregates) { - auto &aggregate = aggr->Cast(); - for (auto &child : aggregate.GetChildren()) { - payload_types.push_back(child->GetReturnType()); - } - if (aggregate.GetFilter()) { - filter_types.push_back(aggregate.GetFilter()->GetReturnType()); - } - } - payload_types.reserve(payload_types.size() + filter_types.size()); - payload_types.insert(payload_types.end(), filter_types.begin(), filter_types.end()); + payload_types = op.grouped_aggregate_data.payload_types; } const PhysicalHashAggregate &op; @@ -286,12 +259,20 @@ class HashAggregateLocalSinkState : public LocalSinkState { } filter_set.Initialize(context.client, aggregate_objects, payload_types); + if (op.distinct_collection_info) { + distinct_filter_chunk.InitializeEmpty(payload_types); + distinct_filtered_input.InitializeEmpty(op.children[0].get().GetTypes()); + } } const PhysicalHashAggregate &op; DataChunk aggregate_input_chunk; vector grouping_states; AggregateFilterDataSet filter_set; + //! Holds the FILTER column of a DISTINCT aggregate at its payload index + DataChunk distinct_filter_chunk; + //! Holds the filtered group columns of a DISTINCT aggregate's hash table at their input index + DataChunk distinct_filtered_input; bool SupportsReuse() const override { return true; @@ -377,46 +358,27 @@ void PhysicalHashAggregate::SinkDistinctGrouping(ExecutionContext &context, Data OperatorSinkInput sink_input {radix_global_sink, radix_local_sink, interrupt_state}; if (aggregate.GetFilter()) { - DataChunk filter_chunk; + // the filter references its payload column: point that column of the filter chunk at the input auto &filtered_data = sink.filter_set.GetFilterData(idx); - filter_chunk.InitializeEmpty(filtered_data.filtered_payload.GetTypes()); - - // Add the filter Vector (BOOL) - auto &filter_ref = *aggregate.GetFilter(); - auto it = filter_indexes.find(filter_ref); - D_ASSERT(it != filter_indexes.end()); + auto &filter_chunk = sink.distinct_filter_chunk; + auto filter_idx = aggregate.GetFilter()->Cast().Index(); + auto it = filter_columns.find(filter_idx); + D_ASSERT(it != filter_columns.end()); D_ASSERT(it->second < chunk.data.size()); - auto &filter_bound_ref = filter_ref.Cast(); - filter_chunk.data[filter_bound_ref.Index()].Reference(chunk.data[it->second]); - - // We cant use the AggregateFilterData::ApplyFilter method, because the chunk we need to - // apply the filter to also has the groups, and the filtered_data.filtered_payload does not have those. - SelectionVector sel_vec(STANDARD_VECTOR_SIZE); - idx_t count = filtered_data.filter_executor.SelectExpression(filter_chunk, sel_vec); - + filter_chunk.data[filter_idx].Reference(chunk.data[it->second]); + filter_chunk.SetCardinalityUnsafe(chunk.size()); + idx_t count = filtered_data.Select(filter_chunk); if (count == 0) { continue; } - // Because the 'input' chunk needs to be re-used after this, we need to create - // a duplicate of it, that we can apply the filter to - DataChunk filtered_input; - filtered_input.InitializeEmpty(chunk.GetTypes()); - - for (idx_t group_idx = 0; group_idx < grouped_aggregate_data.groups.size(); group_idx++) { - auto &group = grouped_aggregate_data.groups[group_idx]; - auto &bound_ref = group->Cast(); - auto &col = filtered_input.data[bound_ref.Index()]; - col.Reference(chunk.data[bound_ref.Index()]); - col.Slice(sel_vec, count); - } - for (idx_t child_idx = 0; child_idx < aggregate.GetChildren().size(); child_idx++) { - auto &child = aggregate.GetChildren()[child_idx]; - auto &bound_ref = child->Cast(); - auto &col = filtered_input.data[bound_ref.Index()]; - col.Reference(chunk.data[bound_ref.Index()]); - col.Slice(sel_vec, count); + // the input chunk is reused after this: slice the columns the hash table groups on into a separate chunk + auto &filtered_input = sink.distinct_filtered_input; + for (auto &group : distinct_data->grouped_aggregate_data[table_idx]->groups) { + auto col_idx = group->Cast().Index(); + filtered_input.data[col_idx].Slice(chunk.data[col_idx], filtered_data.true_sel, count); } + filtered_input.SetCardinalityUnsafe(count); radix_table.Sink(context, filtered_input, sink_input, empty_chunk, empty_filter); } else { @@ -458,15 +420,10 @@ SinkResultType PhysicalHashAggregate::Sink(ExecutionContext &context, DataChunk aggregate_input_chunk.data[aggregate_input_idx++].Reference(chunk.data[bound_ref_expr.Index()]); } } - // Populate the filter vectors - for (auto &aggregate : aggregates) { - auto &aggr = aggregate->Cast(); - if (aggr.GetFilter()) { - auto it = filter_indexes.find(*aggr.GetFilter()); - D_ASSERT(it != filter_indexes.end()); - D_ASSERT(it->second < chunk.data.size()); - aggregate_input_chunk.data[aggregate_input_idx++].Reference(chunk.data[it->second]); - } + // Populate the filter vectors: one per distinct filter, following the children + for (auto &entry : filter_columns) { + D_ASSERT(entry.first >= aggregate_input_idx && entry.second < chunk.data.size()); + aggregate_input_chunk.data[entry.first].Reference(chunk.data[entry.second]); } aggregate_input_chunk.SetChildCardinality(chunk.size()); diff --git a/src/duckdb/src/execution/operator/aggregate/physical_perfecthash_aggregate.cpp b/src/duckdb/src/execution/operator/aggregate/physical_perfecthash_aggregate.cpp index 8f8d3f944..6b0841fa7 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_perfecthash_aggregate.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_perfecthash_aggregate.cpp @@ -1,11 +1,11 @@ #include "duckdb/execution/operator/aggregate/physical_perfecthash_aggregate.hpp" +#include "duckdb/execution/operator/aggregate/grouped_aggregate_data.hpp" #include "duckdb/execution/perfect_aggregate_hashtable.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/storage/buffer_manager.hpp" -#include "duckdb/common/reference_map.hpp" #include "duckdb/main/client_context.hpp" namespace duckdb { @@ -32,7 +32,6 @@ PhysicalPerfectHashAggregate::PhysicalPerfectHashAggregate(PhysicalPlan &physica } vector bindings; - vector payload_types_filters; for (auto &expr : aggregates) { D_ASSERT(expr->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE); D_ASSERT(expr->IsAggregate()); @@ -44,35 +43,10 @@ PhysicalPerfectHashAggregate::PhysicalPerfectHashAggregate(PhysicalPlan &physica for (auto &child : aggr.GetChildren()) { payload_types.push_back(child->GetReturnType()); } - if (aggr.GetFilter()) { - payload_types_filters.push_back(aggr.GetFilter()->GetReturnType()); - } - } - for (const auto &pay_filters : payload_types_filters) { - payload_types.push_back(pay_filters); } + // filter_columns must be pre-built: everything that lives in this class is read-only at execution time + filter_columns = GroupedAggregateData::AddFilterColumns(aggregates, payload_types); aggregate_objects = AggregateObject::CreateAggregateObjects(bindings); - - // filter_indexes must be pre-built, not lazily instantiated in parallel... - idx_t aggregate_input_idx = 0; - for (auto &aggregate : aggregates) { - auto &aggr = aggregate->Cast(); - aggregate_input_idx += aggr.GetChildren().size(); - } - for (auto &aggregate : aggregates) { - auto &aggr = aggregate->Cast(); - if (aggr.GetFilter()) { - auto &filter_ref = *aggr.GetFilter(); - auto &bound_ref_expr = filter_ref.Cast(); - auto it = filter_indexes.find(filter_ref); - if (it == filter_indexes.end()) { - filter_indexes[filter_ref] = bound_ref_expr.Index(); - bound_ref_expr.IndexMutable() = aggregate_input_idx++; - } else { - ++aggregate_input_idx; - } - } - } } unique_ptr PhysicalPerfectHashAggregate::CreateHT(Allocator &allocator, @@ -141,13 +115,9 @@ SinkResultType PhysicalPerfectHashAggregate::Sink(ExecutionContext &context, Dat aggregate_input_chunk.data[aggregate_input_idx++].Reference(chunk.data[bound_ref_expr.Index()]); } } - for (auto &aggregate : aggregates) { - auto &aggr = aggregate->Cast(); - if (aggr.GetFilter()) { - auto it = filter_indexes.find(*aggr.GetFilter()); - D_ASSERT(it != filter_indexes.end()); - aggregate_input_chunk.data[aggregate_input_idx++].Reference(chunk.data[it->second]); - } + for (auto &entry : filter_columns) { + D_ASSERT(entry.first >= aggregate_input_idx && entry.second < chunk.data.size()); + aggregate_input_chunk.data[entry.first].Reference(chunk.data[entry.second]); } group_chunk.Verify(context.client.db); diff --git a/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp b/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp index 414e3f8a4..a0aef15b0 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp @@ -206,6 +206,13 @@ void UngroupedAggregateExecuteState::Reset() { void UngroupedAggregateExecuteState::Sink(LocalUngroupedAggregateState &state, DataChunk &input) { DataChunk &payload_chunk = aggregate_input_chunk; + child_executor.SetChunk(input); + // evaluate each filter once per chunk (filters used only by distinct aggregates are applied in SinkDistinct) + for (auto &filter : filter_set.filter_data) { + if (!filter->aggregates.empty()) { + filter->Select(input); + } + } idx_t payload_idx = 0; idx_t next_payload_idx = 0; @@ -220,23 +227,26 @@ void UngroupedAggregateExecuteState::Sink(LocalUngroupedAggregateState &state, D continue; } - idx_t payload_cnt = 0; - idx_t chunk_count; // resolve the filter (if any) + idx_t chunk_count = input.size(); + optional_ptr sel; if (aggregate.GetFilter()) { auto &filtered_data = filter_set.GetFilterData(aggr_idx); - chunk_count = filtered_data.ApplyFilter(input); - - child_executor.SetChunk(filtered_data.filtered_payload); - } else { - chunk_count = input.size(); - child_executor.SetChunk(input); + chunk_count = filtered_data.selected_count; + sel = &filtered_data.true_sel; + } + if (chunk_count == 0) { + continue; } - // resolve the child expressions of the aggregate (if any) + // resolve the child expressions of the aggregate (if any) on the selected rows for (idx_t i = 0; i < aggregate.GetChildren().size(); ++i) { - child_executor.ExecuteExpression(payload_idx + payload_cnt, payload_chunk.data[payload_idx + payload_cnt]); - payload_cnt++; + auto &result = payload_chunk.data[payload_idx + i]; + if (sel) { + child_executor.ExecuteExpression(payload_idx + i, result, *sel, chunk_count); + } else { + child_executor.ExecuteExpression(payload_idx + i, result); + } } state.Sink(payload_chunk, payload_idx, aggr_idx, chunk_count); @@ -344,14 +354,17 @@ void PhysicalUngroupedAggregate::SinkDistinct(ExecutionContext &context, DataChu OperatorSinkInput sink_input {radix_global_sink, radix_local_sink, input.interrupt_state}; if (aggregate.GetFilter()) { - // The hashtable can apply a filter, but only on the payload - // And in our case, we need to filter the groups (the distinct aggr children) - - // Apply the filter before inserting into the hashtable + // the hash table groups on the aggregate's children: filter those columns before sinking auto &filtered_data = sink.execute_state.filter_set.GetFilterData(idx); - filtered_data.ApplyFilter(chunk); + auto count = filtered_data.Select(chunk); + auto &filtered_payload = filtered_data.filtered_payload; + for (auto &group : distinct_data->grouped_aggregate_data[table_idx]->groups) { + auto col_idx = group->Cast().Index(); + filtered_payload.data[col_idx].Slice(chunk.data[col_idx], filtered_data.true_sel, count); + } + filtered_payload.SetCardinalityUnsafe(count); - radix_table.Sink(context, filtered_data.filtered_payload, sink_input, empty_chunk, distinct_filter); + radix_table.Sink(context, filtered_payload, sink_input, empty_chunk, distinct_filter); } else { radix_table.Sink(context, chunk, sink_input, empty_chunk, distinct_filter); } diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer.cpp index 8972d94c8..6cc042afe 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer.cpp @@ -6,7 +6,7 @@ namespace duckdb { CSVBuffer::CSVBuffer(ClientContext &context, idx_t buffer_size_p, CSVFileHandle &file_handle, const idx_t &global_csv_current_position) - : context(context), requested_size(buffer_size_p), is_pipe(file_handle.IsPipe()) { + : context(context), requested_size(buffer_size_p) { global_csv_start = global_csv_current_position; Load(file_handle); } @@ -14,14 +14,14 @@ CSVBuffer::CSVBuffer(ClientContext &context, idx_t buffer_size_p, CSVFileHandle CSVBuffer::CSVBuffer(CSVFileHandle &file_handle, ClientContext &context, idx_t buffer_size, idx_t global_csv_current_position, idx_t buffer_idx_p) : context(context), requested_size(buffer_size), global_csv_start(global_csv_current_position), - is_pipe(file_handle.IsPipe()), buffer_idx(buffer_idx_p) { + buffer_idx(buffer_idx_p) { Load(file_handle); } CSVBuffer::CSVBuffer(ClientContext &context, idx_t requested_size_p, idx_t actual_size, idx_t global_csv_start_p, idx_t buffer_idx_p, bool last_buffer_p) : last_buffer(last_buffer_p), context(context), actual_buffer_size(actual_size), requested_size(requested_size_p), - global_csv_start(global_csv_start_p), is_pipe(false), random_access(true), buffer_idx(buffer_idx_p) { + global_csv_start(global_csv_start_p), random_access(true), buffer_idx(buffer_idx_p) { } void CSVBuffer::Load(CSVFileHandle &file_handle) { @@ -35,13 +35,7 @@ void CSVBuffer::Load(CSVFileHandle &file_handle) { last_buffer = file_handle.FinishedReading(); } -shared_ptr CSVBuffer::Next(CSVFileHandle &file_handle, idx_t buffer_size, bool &has_seeked) const { - if (has_seeked) { - // This means that at some point a reload was done, and we are currently on the incorrect position in our file - // handle - file_handle.Seek(global_csv_start + actual_buffer_size); - has_seeked = false; - } +shared_ptr CSVBuffer::Next(CSVFileHandle &file_handle, idx_t buffer_size) const { auto next_csv_buffer = make_shared_ptr(file_handle, context, buffer_size, global_csv_start + actual_buffer_size, buffer_idx + 1); if (next_csv_buffer->GetBufferSize() == 0) { @@ -53,7 +47,8 @@ shared_ptr CSVBuffer::Next(CSVFileHandle &file_handle, idx_t buffer_s void CSVBuffer::AllocateBuffer(idx_t buffer_size) { auto &buffer_manager = BufferManager::GetBufferManager(context); - bool can_destroy = !is_pipe; + // Only random-access buffers can be re-read from the file; sequential buffers are spilled instead + const bool can_destroy = random_access; handle = buffer_manager.Allocate(MemoryTag::CSV_READER, MaxValue(buffer_manager.GetBlockSize(), buffer_size), can_destroy); block = handle.GetBlockHandle(); @@ -63,13 +58,6 @@ idx_t CSVBuffer::GetBufferSize() const { return actual_buffer_size; } -void CSVBuffer::Reload(CSVFileHandle &file_handle) { - AllocateBuffer(actual_buffer_size); - // If we can seek, we seek and return the correct pointers - file_handle.Seek(global_csv_start); - file_handle.Read(handle.GetDataMutable(), actual_buffer_size); -} - void CSVBuffer::LoadRandomAccess(CSVFileHandle &file_handle) { D_ASSERT(random_access); AllocateBuffer(actual_buffer_size); @@ -78,18 +66,14 @@ void CSVBuffer::LoadRandomAccess(CSVFileHandle &file_handle) { } } -shared_ptr CSVBuffer::Pin(CSVFileHandle &file_handle, bool &has_seeked) { +shared_ptr CSVBuffer::Pin(CSVFileHandle &file_handle) { lock_guard guard(load_lock); while (true) { if (!IsInMemory()) { - // We have to reload it from disk + // Only random-access buffers can be destroyed, re-read the byte range from the file + D_ASSERT(random_access); block = nullptr; - if (random_access) { - LoadRandomAccess(file_handle); - } else { - Reload(file_handle); - has_seeked = true; - } + LoadRandomAccess(file_handle); } auto pinned = CreatePin(); if (pinned->handle.IsValid()) { diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer_manager.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer_manager.cpp index 518f537be..b3636caf9 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer_manager.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_buffer_manager.cpp @@ -54,6 +54,7 @@ idx_t CSVBufferManager::GetBufferSize() const { } idx_t CSVBufferManager::BufferCount() const { + lock_guard parallel_lock(main_mutex); return cached_buffers.size(); } diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp index 8e922902b..6259de5ed 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp @@ -61,6 +61,8 @@ bool CSVFileHandle::OnDiskFile() const { void CSVFileHandle::Reset() { file_handle->Reset(); + stored_bytes_untaken = 0; + stored_bytes_counted = 0; encoder.Reset(); finished = false; requested_bytes = 0; @@ -93,6 +95,7 @@ idx_t CSVFileHandle::Read(void *buffer, idx_t nr_bytes) { } requested_bytes += nr_bytes; + const idx_t encoded_before = encoder.EncodedBytesRead(); // if this is a plain file source OR we can seek we are not caching anything idx_t bytes_read = 0; if (encoder.encoding_name == "utf-8") { @@ -100,6 +103,22 @@ idx_t CSVFileHandle::Read(void *buffer, idx_t nr_bytes) { } else { bytes_read = encoder.Encode(*file_handle, static_cast(buffer), nr_bytes); } + // the position in the stored file: the compressed bytes consumed for a compressed file (a gzip header included), + // and the bytes before decoding for an encoding other than utf-8 + idx_t stored_position; + if (compression_type != FileCompressionType::UNCOMPRESSED) { + stored_position = file_handle->GetProgress(); + } else if (can_seek) { + stored_position = file_handle->SeekPosition(); + } else if (encoder.encoding_name == "utf-8") { + stored_position = stored_bytes_counted + bytes_read; + } else { + stored_position = stored_bytes_counted + encoder.EncodedBytesRead() - encoded_before; + } + if (stored_position > stored_bytes_counted) { + stored_bytes_untaken += stored_position - stored_bytes_counted; + stored_bytes_counted = stored_position; + } if (!finished) { finished = bytes_read == 0; } diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_random_access_buffer_manager.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_random_access_buffer_manager.cpp index 7aff4f891..6b1d272c1 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_random_access_buffer_manager.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_random_access_buffer_manager.cpp @@ -13,10 +13,20 @@ CSVRandomAccessBufferManager::CSVRandomAccessBufferManager(ClientContext &contex void CSVRandomAccessBufferManager::Initialize() { const idx_t buffer_count = KnownBufferCount(); cached_buffers.resize(buffer_count); - cached_buffers[0] = make_shared_ptr(context, buffer_size, KnownBufferSize(0), 0, 0, buffer_count == 1); + created.assign(buffer_count, false); + cached_buffers[0] = CreateBuffer(0); cached_buffers[0]->LoadRandomAccess(*file_handle); } +shared_ptr CSVRandomAccessBufferManager::CreateBuffer(idx_t pos) { + if (!created[pos]) { + created[pos] = true; + file_handle->AddStoredBytesRead(KnownBufferSize(pos)); + } + return make_shared_ptr(context, buffer_size, KnownBufferSize(pos), pos * buffer_size, pos, + pos + 1 == cached_buffers.size()); +} + shared_ptr CSVRandomAccessBufferManager::GetBuffer(const idx_t pos) { shared_ptr buffer; { @@ -25,15 +35,13 @@ shared_ptr CSVRandomAccessBufferManager::GetBuffer(const idx_t return nullptr; } if (!cached_buffers[pos]) { - cached_buffers[pos] = make_shared_ptr(context, buffer_size, KnownBufferSize(pos), - pos * buffer_size, pos, pos + 1 == cached_buffers.size()); + cached_buffers[pos] = CreateBuffer(pos); } buffer = cached_buffers[pos]; } // the load of a fresh or evicted buffer runs inside Pin, under the buffer's own lock, // so loads of different buffers proceed in parallel - bool has_seeked = false; - return buffer->Pin(*file_handle, has_seeked); + return buffer->Pin(*file_handle); } CSVBufferResidency CSVRandomAccessBufferManager::GetBufferResidency(const idx_t pos, diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_sequential_buffer_manager.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_sequential_buffer_manager.cpp index 11016e8da..0856d6cd1 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_sequential_buffer_manager.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_sequential_buffer_manager.cpp @@ -22,7 +22,7 @@ bool CSVSequentialBufferManager::ReadNextAndCacheIt() { D_ASSERT(last_buffer); for (idx_t i = 0; i < 2; i++) { if (!last_buffer->IsCSVFileLastBuffer()) { - auto maybe_last_buffer = last_buffer->Next(*file_handle, buffer_size, has_seeked); + auto maybe_last_buffer = last_buffer->Next(*file_handle, buffer_size); if (!maybe_last_buffer) { last_buffer->last_buffer = true; return false; @@ -55,7 +55,7 @@ shared_ptr CSVSequentialBufferManager::GetBuffer(const idx_t po } } UnpinPrevious(pos); - return cached_buffers[pos]->Pin(*file_handle, has_seeked); + return cached_buffers[pos]->Pin(*file_handle); } void CSVSequentialBufferManager::UnpinPrevious(const idx_t pos) { @@ -77,7 +77,7 @@ CSVBufferResidency CSVSequentialBufferManager::GetBufferResidency(const idx_t po return CSVBufferResidency::NEEDS_LOAD; } UnpinPrevious(pos); - handle = cached_buffers[pos]->Pin(*file_handle, has_seeked); + handle = cached_buffers[pos]->Pin(*file_handle); return CSVBufferResidency::IN_MEMORY; } if (!cached_buffers.empty() && cached_buffers.back() && cached_buffers.back()->last_buffer) { @@ -127,6 +127,7 @@ void CSVSequentialBufferManager::ResetBuffer(const idx_t buffer_idx) { } bool CSVSequentialBufferManager::Done() const { + lock_guard parallel_lock(main_mutex); return done; } diff --git a/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp b/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp index 7e5207277..b11b77564 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp @@ -84,6 +84,7 @@ void CSVEncoder::Reset() { encoded_buffer.last_buffer = false; remaining_bytes_buffer.Reset(); has_pass_on_byte = false; + encoded_bytes_read = 0; } idx_t CSVEncoder::Encode(FileHandle &file_handle_input, char *output_buffer, const idx_t decoded_buffer_size) { @@ -126,12 +127,14 @@ idx_t CSVEncoder::Encode(FileHandle &file_handle_input, char *output_buffer, con const idx_t bytes_to_read = encoded_buffer.GetCapacity() - pass_on_buffer.size() - has_pass_on_byte; auto actual_encoded_bytes = static_cast(file_handle_input.Read( context, encoded_buffer.Ptr() + pass_on_buffer.size() + has_pass_on_byte, bytes_to_read)); + encoded_bytes_read += actual_encoded_bytes; encoded_buffer.SetSize(actual_encoded_bytes + pass_on_buffer.size() + has_pass_on_byte); if (actual_encoded_bytes < bytes_to_read) { encoded_buffer.last_buffer = true; has_pass_on_byte = false; } else { auto bytes_read = static_cast(file_handle_input.Read(context, &pass_on_byte, 1)); + encoded_bytes_read += bytes_read; if (bytes_read == 0) { encoded_buffer.last_buffer = true; has_pass_on_byte = false; 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 24ccfc2a0..606cf9290 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 @@ -749,11 +749,9 @@ bool LineError::HandleErrors(StringValueResult &result) { result.current_line_position.begin.GetGlobalPosition(result.requested_size, first_nl), line_pos.GetGlobalPosition(result.requested_size), result.path); } - // the file types are those of the projected columns - auto &file_types = result.csv_file_scan->file_types; - if (cur_error.chunk_idx < file_types.size() && - !StringValueScanner::CanDirectlyCast(file_types[cur_error.chunk_idx], result.icu_loaded)) { - result.number_of_rows--; + // the value is invalid: make it NULL so that casting the column does not report a second error for it + if (cur_error.chunk_idx < result.validity_mask.size()) { + result.validity_mask[cur_error.chunk_idx]->SetInvalid(static_cast(result.number_of_rows)); } break; } diff --git a/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_detection.cpp b/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_detection.cpp index 076fd8b53..8d4fd918e 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_detection.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_detection.cpp @@ -247,7 +247,7 @@ bool CSVSniffer::CanYouCastIt(ClientContext &context, const string_t value, cons return Time::TryConvertTime(value_ptr, value_size, pos, dummy_value, true); } case LogicalTypeId::DECIMAL: { - uint8_t width, scale; + uint32_t width, scale; type.GetDecimalProperties(width, scale); if (decimal_separator == ',') { switch (type.InternalType()) { 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 794f43b8d..0fc650862 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 @@ -1,4 +1,5 @@ #include "duckdb/execution/operator/csv_scanner/csv_file_scanner.hpp" +#include "duckdb/main/query_profiler.hpp" #include "duckdb/execution/operator/csv_scanner/sniffer/csv_sniffer.hpp" #include "duckdb/execution/operator/csv_scanner/skip_scanner.hpp" @@ -80,6 +81,15 @@ CSVFileScan::CSVFileScan(ClientContext &context, const OpenFileInfo &file_p, con SetStart(); } +void CSVFileScan::CountBytesScanned(CSVBufferManager &manager) { + auto bytes = manager.file_handle->TakeStoredBytesRead(); + if (bytes == 0) { + return; + } + bytes_scanned_unreported += bytes; + QueryProfiler::Get(manager.context).TrackBytesScanned(bytes); +} + void CSVFileScan::SetStart() { idx_t rows_to_skip = options.GetSkipRows() + state_machine->dialect_options.header.GetValue(); @@ -155,6 +165,9 @@ void CSVFileScan::InitializeProjection() { } void CSVFileScan::Finish() { + if (buffer_manager) { + CountBytesScanned(*buffer_manager); + } buffer_manager.reset(); } diff --git a/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_schema_discovery.cpp b/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_schema_discovery.cpp index b370d62a9..83feb8e85 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_schema_discovery.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/table_function/csv_schema_discovery.cpp @@ -23,7 +23,7 @@ CSVSchema CSVSchemaDiscovery::SchemaDiscovery(ClientContext &context, shared_ptr idx_t current_file = 0; options.file_path = file_paths[current_file].path; - buffer_manager = CSVBufferManager::Open(context, options, options.file_path, false); + buffer_manager = CSVBufferManager::Open(context, options, file_paths[current_file], false); idx_t only_header_or_empty_files = 0; { @@ -49,7 +49,7 @@ CSVSchema CSVSchemaDiscovery::SchemaDiscovery(ClientContext &context, shared_ptr while (total_number_of_rows < required_number_of_lines && current_file < files_to_sniff) { auto option_copy = option_og; option_copy.file_path = file_paths[current_file].path; - auto file_buffer_manager = CSVBufferManager::Open(context, option_copy, option_copy.file_path, false); + auto file_buffer_manager = CSVBufferManager::Open(context, option_copy, file_paths[current_file], false); // TODO: We could cache the sniffer to be reused during scanning. Currently that's an exercise left to the // reader CSVSniffer sniffer(option_copy, file_options, file_buffer_manager, CSVStateMachineCache::Get(context)); diff --git a/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp b/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp index 38a41c6e8..0f768c747 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp @@ -93,7 +93,7 @@ static void SniffCSVFile(ClientContext &context, ReadSingleCSVFileData &result, const MultiFileOptions &file_options, vector &return_types, vector &names) { auto &options = result.options; - result.buffer_manager = CSVBufferManager::Open(context, options, options.file_path, false); + result.buffer_manager = CSVBufferManager::Open(context, options, result.file, false); auto &state_machine_cache = CSVStateMachineCache::Get(context); if (file_schema.Empty()) { // the columns of this file are fixed - only its dialect is sniffed @@ -433,6 +433,8 @@ static void ReadSingleCSVFileFunction(ClientContext &context, TableFunctionInput auto &csv_reader = *lstate.state.csv_reader; if (csv_reader.IsSuspended() || !csv_reader.FinishedIterator()) { csv_reader.Flush(output); + // through the scanner's own reference to the buffer manager, which the file scan drops once it finishes + gstate.file_scan->CountBytesScanned(*csv_reader.buffer_manager); if (csv_reader.IsSuspended()) { // the scanner needs a buffer that is not in memory - load it and resume csv_reader.buffer_manager->GetBuffer(csv_reader.PendingBufferIdx()); @@ -464,6 +466,17 @@ static double ReadSingleCSVFileProgress(ClientContext &context, const FunctionDa return gstate.file_scan->GetProgressInFile(context); } +//! The bytes scanned are drained, so each is reported once - the profiler sums what every thread reports +static void ReadSingleCSVFileGetMetrics(TableFunctionGetMetricsInput &input) { + if (!input.global_state) { + return; + } + auto &gstate = input.global_state->Cast(); + if (gstate.file_scan) { + input.operator_metrics.bytes_scanned += gstate.file_scan->bytes_scanned_unreported.exchange(0); + } +} + static unique_ptr ReadSingleCSVFileCardinality(ClientContext &context, const FunctionData *bind_data) { auto &csv_data = bind_data->Cast(); // determined through the scientific method as the average amount of rows in a CSV file @@ -487,6 +500,7 @@ TableFunction ReadCSVTableFunction::GetSingleFileFunction() { ReadSingleCSVFileInitLocal); read_csv.table_scan_progress = ReadSingleCSVFileProgress; read_csv.cardinality = ReadSingleCSVFileCardinality; + read_csv.get_metrics = ReadSingleCSVFileGetMetrics; read_csv.projection_pushdown = true; ReadCSVAddNamedParameters(read_csv); return read_csv; @@ -509,6 +523,7 @@ TableFunction ReadCSVTableFunction::GetMultiFileFunction(Identifier name) { settings.schedule_io = ReadSingleCSVFileScheduleIO; // the scanner converts to the types the scan asks for while parsing, rather than casting its output settings.supports_cast_map = true; + settings.reports_bytes_scanned = true; return TableFunctionMultiFileWrapper::CreateFunction(GetSingleFileFunction(), std::move(name), std::move(settings)); } diff --git a/src/duckdb/src/execution/operator/helper/physical_vacuum.cpp b/src/duckdb/src/execution/operator/helper/physical_vacuum.cpp index e7b63b9bb..fd15132ef 100644 --- a/src/duckdb/src/execution/operator/helper/physical_vacuum.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_vacuum.cpp @@ -1,10 +1,11 @@ #include "duckdb/execution/operator/helper/physical_vacuum.hpp" +#include "duckdb/storage/storage_lock.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/storage/statistics/distinct_statistics.hpp" +#include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" -#include "duckdb/catalog/catalog_entry/type_catalog_entry.hpp" namespace duckdb { @@ -15,6 +16,8 @@ PhysicalVacuum::PhysicalVacuum(PhysicalPlan &physical_plan, unique_ptr table) : hashes(LogicalType::HASH) { @@ -32,10 +35,6 @@ class VacuumLocalSinkState : public LocalSinkState { Vector hashes; }; -unique_ptr PhysicalVacuum::GetLocalSinkState(ExecutionContext &context) const { - return make_uniq(*info, table); -} - class VacuumGlobalSinkState : public GlobalSinkState { public: explicit VacuumGlobalSinkState(VacuumInfo &info, optional_ptr table) { @@ -53,6 +52,12 @@ class VacuumGlobalSinkState : public GlobalSinkState { vector> column_distinct_stats; }; +} // namespace + +unique_ptr PhysicalVacuum::GetLocalSinkState(ExecutionContext &context) const { + return make_uniq(*info, table); +} + unique_ptr PhysicalVacuum::GetGlobalSinkState(ClientContext &context) const { return make_uniq(*info, table); } @@ -96,6 +101,8 @@ SinkFinalizeType PhysicalVacuum::Finalize(Pipeline &pipeline, Event &event, Clie } auto tbl = table; + // Scan tasks have released their local state; only the live mutations need checkpoint exclusion. + auto checkpoint_lock = DuckTransaction::Get(context, tbl->ParentCatalog()).GetCheckpointLockForStatement(); for (idx_t col_idx = 0; col_idx < sink.column_distinct_stats.size(); col_idx++) { tbl->GetStorage().SetDistinct(column_id_map.at(col_idx), std::move(sink.column_distinct_stats[col_idx])); } 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 b55235e73..923ef48a5 100644 --- a/src/duckdb/src/execution/operator/join/physical_hash_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_hash_join.cpp @@ -441,16 +441,16 @@ class HashJoinGlobalSinkState : public GlobalSinkState { public: HashJoinGlobalSinkState(const PhysicalHashJoin &op_p, ClientContext &context_p) : context(context_p), op(op_p), num_threads(TaskScheduler::GetScheduler(context).NumberOfThreads()), - temporary_memory_state(TemporaryMemoryManager::Get(context).Register(context)), initial_radix_bits(4), - finalized(false), active_local_states(0), total_size(0), max_partition_size(0), max_partition_count(0), - probe_side_requirement(0), scanned_data(false) { + temporary_memory_state(TemporaryMemoryManager::Get(context.GetContext()).Register(context.GetContext())), + initial_radix_bits(4), finalized(false), active_local_states(0), total_size(0), max_partition_size(0), + max_partition_count(0), probe_side_requirement(0), scanned_data(false) { hash_table = op.InitializeHashTable(context, initial_radix_bits); // Reserve the initial partition buffers before upstream hash tables are finalized. auto minimum_reservation = MinValue(temporary_memory_state->GetMinimumReservation(), GetBuildSpaceRequirement(context, *hash_table, num_threads)); temporary_memory_state->SetMinimumReservation(minimum_reservation); temporary_memory_state->SetRemainingSize(minimum_reservation); - temporary_memory_state->UpdateReservation(context); + temporary_memory_state->UpdateReservation(context.GetContext()); // Multiple build producers can change dictionaries after the layout has been published. build_side_multi_source = BuildSideHasMultipleSources(op.children[1].get()); @@ -1000,7 +1000,7 @@ static bool FinalizeSingleThreaded(const HashJoinGlobalSinkState &sink, const bo } // if we want to verify parallelism, finalize parallel - if (sink.context.config.verify_parallelism) { + if (ClientConfig::GetConfig(sink.context).verify_parallelism) { return false; } @@ -1520,7 +1520,7 @@ class HashJoinRepartitionEvent : public BasePipelineEvent { sink.temporary_memory_state->SetMinimumReservation(sink.max_partition_size + sink.hash_table->PointerTableSize(sink.max_partition_count) + sink.probe_side_requirement); - sink.temporary_memory_state->UpdateReservation(executor.context); + sink.temporary_memory_state->UpdateReservation(executor.context.GetContext()); FinalizeExternalRuntimeFilters(sink.context, op, sink); @@ -2084,7 +2084,7 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl // the filter covers the whole build side once Sink is done ht.SealBloomFilter(); - sink.temporary_memory_state->UpdateReservation(context); + sink.temporary_memory_state->UpdateReservation(context.GetContext()); sink.external = sink.temporary_memory_state->GetReservation() < sink.total_size; if (sink.external) { // For external join we reduce the load factor, this may even prevent the external join altogether @@ -2098,7 +2098,7 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl if (temp_total_size < sink.temporary_memory_state->GetReservation()) { // We prevented the external join by reducing the load factor. Update the state accordingly sink.temporary_memory_state->SetMinimumReservation(temp_total_size); - sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation(context, temp_total_size); + sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation(context.GetContext(), temp_total_size); sink.total_size = temp_total_size; sink.max_partition_size = temp_max_partition_size; @@ -2485,7 +2485,7 @@ class HashJoinGlobalSourceState : public GlobalSourceState { probe_chunk_done = 0; external_progress.Reset(); probe_count = op.children[0].get().estimated_cardinality; - parallel_scan_chunk_count = context.config.verify_parallelism ? 1 : 120; + parallel_scan_chunk_count = ClientConfig::GetConfig(context).verify_parallelism ? 1 : 120; full_outer_chunk_idx = DConstants::INVALID_INDEX; full_outer_chunk_count = 0; full_outer_chunk_done = 0; @@ -2647,8 +2647,8 @@ void HashJoinGlobalSourceState::PrepareBuild(HashJoinGlobalSinkState &sink) { auto &ht = *sink.hash_table; // Update remaining size - sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation(sink.context, ht.GetRemainingSize() + - sink.probe_side_requirement); + sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation( + sink.context.GetContext(), ht.GetRemainingSize() + sink.probe_side_requirement); // Try to put the next partitions in the block collection of the HT if (!sink.external || !ht.PrepareExternalFinalize(sink.GetMaxExternalHTSize())) { @@ -2667,7 +2667,7 @@ void HashJoinGlobalSourceState::PrepareBuild(HashJoinGlobalSinkState &sink) { build_chunk_count = data_collection.ChunkCount(); build_chunk_done = 0; - if (sink.context.config.verify_parallelism) { + if (ClientConfig::GetConfig(sink.context).verify_parallelism) { build_chunks_per_thread = 1; } else { if (KeysAreSkewed(sink)) { diff --git a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp index 1f5818b38..d26102722 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp @@ -416,7 +416,7 @@ static void VerifyOnConflictCondition(ExecutionContext &context, DataChunk &comb throw InternalException("VerifyAppendConstraints was expected to throw but didn't"); } - auto &indexes = local_storage.GetIndexes(context.client, data_table); + auto &indexes = local_storage.GetIndexes(data_table); auto storage = local_storage.GetStorage(data_table); indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, tuples, nullptr); throw InternalException("VerifyUniqueIndexes was expected to throw but didn't"); @@ -439,7 +439,7 @@ static idx_t HandleInsertConflicts(DuckTableEntry &table, ExecutionContext &cont auto &constraint_state = lstate.GetConstraintState(data_table, table); data_table.VerifyAppendConstraints(constraint_state, context.client, tuples, storage, &conflict_manager); } else { - auto &indexes = local_storage.GetIndexes(context.client, data_table); + auto &indexes = local_storage.GetIndexes(data_table); indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, tuples, &conflict_manager); } @@ -530,7 +530,7 @@ idx_t PhysicalInsert::OnConflictHandling(DuckTableEntry &table, ExecutionContext // We care about every index that applies to the table if no ON CONFLICT (...) target is given matching_index_columns = global_indexes.GetConflictTargetColumns(conflict_info); - const auto &local_indexes = local_storage.GetIndexes(context.client, data_table); + const auto &local_indexes = local_storage.GetIndexes(data_table); auto local_index_columns = local_indexes.GetConflictTargetColumns(conflict_info); for (auto &column_set : local_index_columns) { matching_index_columns.push_back(std::move(column_set)); diff --git a/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp b/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp index cb82d41ac..6d096a0b8 100644 --- a/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp +++ b/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp @@ -51,7 +51,7 @@ unique_ptr PhysicalTableInOutFunction::GetOperatorState(Execution TableFunctionInitInput input(bind_data.get(), column_ids, projection_ids, table_filters.get()); result->local_state = function.init_local(context, input, gstate.global_state.get()); } - if (!projected_input.empty()) { + if (!projected_input.empty() || (ordinality_idx.IsValid() && !table_input)) { vector input_types; auto &child_types = children[0].get().GetTypes(); idx_t input_length = child_types.size() - projected_input.size(); @@ -89,10 +89,11 @@ OperatorResultType PhysicalTableInOutFunction::Execute(ExecutionContext &context auto &gstate = gstate_p.Cast(); auto &state = state_p.Cast(); TableFunctionInput data(bind_data.get(), state.local_state.get(), gstate.global_state.get()); - if (projected_input.empty()) { + if (projected_input.empty() && (!this->ordinality_idx.IsValid() || table_input)) { // straightforward case - no need to project input auto result = function.in_out_function(context, data, input, chunk); if (this->ordinality_idx.IsValid()) { + // a TABLE parameter's rows form one invocation: the numbering continues across them const idx_t ordinality = chunk.size(); SetOrdinality(chunk, this->ordinality_idx, state.current_ordinality_idx, ordinality); state.current_ordinality_idx += ordinality; @@ -100,7 +101,8 @@ OperatorResultType PhysicalTableInOutFunction::Execute(ExecutionContext &context chunk.SetChildCardinality(chunk.size()); return result; } - // when project_input is set we execute the input function row-by-row + // with project_input or ordinality over scalar parameters we execute the input function row-by-row + // (the ordinality numbering restarts for every input row) if (state.new_row) { if (state.row_index >= input.size()) { // finished processing this chunk diff --git a/src/duckdb/src/execution/operator/scan/physical_column_data_scan.cpp b/src/duckdb/src/execution/operator/scan/physical_column_data_scan.cpp index eb6d228f5..d8caaa00e 100644 --- a/src/duckdb/src/execution/operator/scan/physical_column_data_scan.cpp +++ b/src/duckdb/src/execution/operator/scan/physical_column_data_scan.cpp @@ -273,6 +273,8 @@ void PhysicalColumnDataScan::BuildPipelines(Pipeline ¤t, MetaPipeline &met if (cte.ShouldUseBufferedConsumer(current)) { cte.RegisterBufferedConsumer(current, source.consumer_idx); current.AddDataflowDependency(cte_dependency); + D_ASSERT(collection); + state.AddBufferedConsumer(current, *this, cte_dependency, cte, source.consumer_idx); DUCKDB_LOG(current.GetClientContext(), PhysicalOperatorLogType, cte, "PhysicalCTE", "SelectConsumer", {{"consumer", to_string(source.consumer_idx)}, {"mode", "BUFFERED"}}); state.SetPipelineSource(current, *cte_source); diff --git a/src/duckdb/src/execution/operator/set/physical_cte.cpp b/src/duckdb/src/execution/operator/set/physical_cte.cpp index 4e3222f33..5904189d9 100644 --- a/src/duckdb/src/execution/operator/set/physical_cte.cpp +++ b/src/duckdb/src/execution/operator/set/physical_cte.cpp @@ -508,6 +508,11 @@ void PhysicalCTE::RegisterMaterializedConsumer(idx_t consumer_idx) { exchange->SelectMaterializedConsumer(consumer_idx); } +void PhysicalCTE::DemoteBufferedConsumer(idx_t consumer_idx) { + D_ASSERT(exchange); + exchange->DemoteBufferedConsumerToMaterialized(consumer_idx); +} + CTEExecutionMode PhysicalCTE::GetExecutionMode() const { if (!exchange) { return CTEExecutionMode::MATERIALIZED; diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte.cpp index 228b0df08..fa6a1a698 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte.cpp @@ -91,7 +91,8 @@ SinkCombineResultType PhysicalRecursiveCTE::Combine(ExecutionContext &context, O SourceResultType PhysicalRecursiveCTE::GetDataInternal(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const { auto &gstate = sink_state->Cast(); - return gstate.GetData(context, chunk, input.global_state.Cast()); + return gstate.GetData(context, chunk, input.global_state.Cast(), + input.interrupt_state); } unique_ptr PhysicalRecursiveCTE::GetGlobalSourceState(ClientContext &context) const { diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp index c24070b04..6939f4309 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp @@ -8,9 +8,11 @@ namespace duckdb { -static vector GetPreviousStateTypes(const PhysicalRecursiveCTE &op) { +static vector GetPreviousStateTypes(const PhysicalRecursiveCTE &op, bool address_only) { vector types {LogicalType::POINTER}; - types.insert(types.end(), op.payload_types.begin(), op.payload_types.end()); + if (!address_only) { + types.insert(types.end(), op.payload_types.begin(), op.payload_types.end()); + } return types; } @@ -78,19 +80,21 @@ bool RecursiveCTEGroupAddressSet::Contains(data_ptr_t address) const { return false; } -RecursiveCTEKeyDeltaState::RecursiveCTEKeyDeltaState(ClientContext &context, const PhysicalRecursiveCTE &op) - : previous_rows(context, GetPreviousStateTypes(op)), new_keys(context, op.hash_key_types), - matched_addresses(LogicalType::POINTER), finalize_addresses(LogicalType::POINTER), - found_groups(STANDARD_VECTOR_SIZE), missing_groups(STANDARD_VECTOR_SIZE), changed_groups(STANDARD_VECTOR_SIZE), +RecursiveCTEKeyDeltaState::RecursiveCTEKeyDeltaState(ClientContext &context, const PhysicalRecursiveCTE &op, + bool address_only_previous) + : previous_rows(context, GetPreviousStateTypes(op, address_only_previous)), new_keys(context, op.hash_key_types), + pending_finalized(context, op.aggregate_types), matched_addresses(LogicalType::POINTER), + finalize_addresses(LogicalType::POINTER), found_groups(STANDARD_VECTOR_SIZE), + missing_groups(STANDARD_VECTOR_SIZE), changed_groups(STANDARD_VECTOR_SIZE), changed_column_groups(STANDARD_VECTOR_SIZE), equal_groups_a(STANDARD_VECTOR_SIZE), equal_groups_b(STANDARD_VECTOR_SIZE), arena(Allocator::Get(context)), row_state(arena) { selected_keys.Initialize(Allocator::Get(context), op.hash_key_types); aggregate_rows.Initialize(Allocator::Get(context), op.aggregate_types); updated_aggregate_rows.Initialize(Allocator::Get(context), op.aggregate_types); result_rows.Initialize(Allocator::Get(context), op.GetTypes()); - previous_state_rows.Initialize(Allocator::Get(context), GetPreviousStateTypes(op)); + previous_state_rows.Initialize(Allocator::Get(context), GetPreviousStateTypes(op, address_only_previous)); changed_rows.Initialize(Allocator::Get(context), op.GetTypes()); - previous_scan_rows.Initialize(Allocator::Get(context), GetPreviousStateTypes(op)); + previous_scan_rows.Initialize(Allocator::Get(context), GetPreviousStateTypes(op, address_only_previous)); key_scan_rows.Initialize(Allocator::Get(context), op.hash_key_types); vector comparison_types; comparison_types.reserve(op.payload_types.size() * 2); @@ -192,8 +196,10 @@ void RecursiveCTEKeyedState::AppendPreviousUsingKeyDeltaRows(Vector &addresses, delta.PrepareCollections(); delta.previous_state_rows.Reset(); delta.previous_state_rows.data[0].Reference(addresses); - for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size(); payload_idx++) { - delta.previous_state_rows.data[1 + payload_idx].Reference(delta.aggregate_rows.data[payload_idx]); + if (!finalized.Enabled()) { + for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size(); payload_idx++) { + delta.previous_state_rows.data[1 + payload_idx].Reference(delta.aggregate_rows.data[payload_idx]); + } } delta.previous_state_rows.CheckCardinality(count); delta.previous_rows.Append(delta.previous_append_state, delta.previous_state_rows); @@ -206,6 +212,20 @@ void RecursiveCTEKeyedState::SnapshotExistingUsingKeyDeltaAddresses(Vector &addr return; } CopySelectedAddresses(addresses, *FlatVector::IncrementalSelectionVector(), count, delta.finalize_addresses); + if (finalized.Enabled()) { + // The rows still hold the finalized values of the previous commit, so the old values stay readable + // from the rows until the commit's own scatter and need neither a finalize nor a copy here. + if (defer_append) { + delta.aggregate_rows.Reset(); + finalized.Gather(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), count, + delta.aggregate_rows); + delta.deferred_previous_rows = true; + delta.deferred_count = count; + return; + } + AppendPreviousUsingKeyDeltaRows(addresses, count); + return; + } FinalizeAggregateRows(delta.row_state, delta.finalize_addresses, delta.aggregate_rows, count); if (defer_append) { delta.deferred_previous_rows = true; @@ -223,8 +243,16 @@ void RecursiveCTEKeyedState::SnapshotUsingKeyDelta(const Vector &group_addresses const auto skip_new_group_addresses = allow_candidate_reuse && op.keyed.can_reuse_new_group_candidates && partial_key_indexes.empty() && new_group_count == candidate_count && row_count == candidate_count; + // When the candidates can stand in for the finalized rows, publish them for every new group here: the + // candidate-reuse commits skip the delta finalization that would otherwise write the finalized values. + const auto scatter_new_group_candidates = + finalized.Enabled() && allow_candidate_reuse && op.keyed.can_reuse_new_group_candidates; if (skip_new_group_addresses) { D_ASSERT(partial_key_indexes.empty() && new_group_count == row_count); + if (scatter_new_group_candidates) { + finalized.ScatterCandidates(group_addresses, *FlatVector::IncrementalSelectionVector(), new_group_count, + payload_rows); + } delta.new_count += new_group_count; delta.touched_count += new_group_count; return; @@ -239,11 +267,18 @@ void RecursiveCTEKeyedState::SnapshotUsingKeyDelta(const Vector &group_addresses auto partial_index_addresses = update_partial_indexes ? FlatVector::GetDataMutable(new_group_addresses) : nullptr; if (!update_partial_indexes && !delta.HasNewGroupAddressSet() && new_group_count == row_count) { + if (scatter_new_group_candidates) { + finalized.ScatterCandidates(group_addresses, *FlatVector::IncrementalSelectionVector(), new_group_count, + payload_rows); + } delta.AppendNewGroupAddresses(source_addresses, new_group_count); delta.new_count += new_group_count; delta.touched_count += new_group_count; return; } + if (scatter_new_group_candidates && new_group_count > 0) { + finalized.ScatterCandidates(group_addresses, new_groups, new_group_count, payload_rows); + } for (idx_t new_group_idx = 0; new_group_idx < new_group_count; new_group_idx++) { const auto input_idx = new_groups.get_index_unsafe(new_group_idx); const auto address = source_addresses[input_idx]; @@ -308,6 +343,11 @@ void RecursiveCTEKeyedState::ValidateDeferredUsingKeyCandidateReuse(DataChunk &c } delta.changed_count = changed_count; delta.deferred_candidate_reuse = true; + if (finalized.Enabled()) { + // The reuse succeeds, so this validation finalize is the one that publishes the new values. + finalized.Scatter(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), delta.deferred_count, + delta.updated_aggregate_rows); + } } void RecursiveCTEKeyedState::SnapshotPreaggregatedUsingKeyDeltaGroups(DataChunk &keys) { @@ -377,6 +417,13 @@ bool RecursiveCTEKeyedState::TryReuseChangedGroupCandidates(idx_t candidate_coun ColumnDataScanState candidate_scan_state; delta.previous_rows.InitializeScan(previous_scan_state); intermediate_table.InitializeScan(candidate_scan_state); + // With materialized values the new finalized rows are buffered until the reuse proof succeeds, so a failed + // validation leaves every row's old value in place for the regular delta finalization. + const auto buffer_finalized = finalized.Enabled(); + if (buffer_finalized) { + delta.pending_finalized.ResetForReuse(); + delta.pending_finalized.InitializeAppend(delta.pending_finalized_append_state); + } idx_t changed_count = 0; while (delta.previous_rows.Scan(previous_scan_state, delta.previous_scan_rows)) { if (!intermediate_table.Scan(candidate_scan_state, update_rows) || @@ -387,15 +434,26 @@ bool RecursiveCTEKeyedState::TryReuseChangedGroupCandidates(idx_t candidate_coun auto &group_addresses = delta.previous_scan_rows.data[0]; CopySelectedAddresses(group_addresses, *FlatVector::IncrementalSelectionVector(), row_count, delta.finalize_addresses); + if (buffer_finalized) { + delta.updated_aggregate_rows.Reset(); + finalized.Gather(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), row_count, + delta.updated_aggregate_rows); + } FinalizeAggregateRows(delta.row_state, delta.finalize_addresses, delta.aggregate_rows, row_count); if (!FinalizedPayloadsEqualCandidates(delta, op, delta.aggregate_rows, update_rows, row_count)) { return false; } - // The previous rows carry the group address in their first column - changed_count += - CountChangedPayloadRows(delta, op, delta.previous_scan_rows, 1, delta.aggregate_rows, row_count); + if (buffer_finalized) { + changed_count += + CountChangedPayloadRows(delta, op, delta.updated_aggregate_rows, 0, delta.aggregate_rows, row_count); + delta.pending_finalized.Append(delta.pending_finalized_append_state, delta.aggregate_rows); + } else { + // The previous rows carry the group address in their first column + changed_count += + CountChangedPayloadRows(delta, op, delta.previous_scan_rows, 1, delta.aggregate_rows, row_count); + } } if (intermediate_table.Scan(candidate_scan_state, update_rows)) { return false; @@ -404,6 +462,23 @@ bool RecursiveCTEKeyedState::TryReuseChangedGroupCandidates(idx_t candidate_coun return false; } delta.changed_count = changed_count; + if (buffer_finalized) { + ColumnDataScanState address_scan_state; + ColumnDataScanState finalized_scan_state; + delta.previous_rows.InitializeScan(address_scan_state); + delta.pending_finalized.InitializeScan(finalized_scan_state); + while (delta.previous_rows.Scan(address_scan_state, delta.previous_scan_rows)) { + if (!delta.pending_finalized.Scan(finalized_scan_state, delta.aggregate_rows) || + delta.aggregate_rows.size() != delta.previous_scan_rows.size()) { + throw InternalException("USING KEY candidate reuse buffered a mismatched finalized chunk"); + } + const auto row_count = delta.previous_scan_rows.size(); + CopySelectedAddresses(delta.previous_scan_rows.data[0], *FlatVector::IncrementalSelectionVector(), + row_count, delta.finalize_addresses); + finalized.Scatter(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), row_count, + delta.aggregate_rows); + } + } return true; } @@ -421,14 +496,23 @@ idx_t RecursiveCTEKeyedState::FinalizeUsingKeyDelta(bool update_partial_indexes, delta.key_scan_rows); CopySelectedAddresses(group_addresses, *FlatVector::IncrementalSelectionVector(), row_count, delta.finalize_addresses); - FinalizeStateRows(delta.row_state, delta.finalize_addresses, delta.key_scan_rows, delta.aggregate_rows, - delta.result_rows); - const idx_t previous_payload_offset = 1; + // With materialized values the rows still hold the previous commit's finalized values: read the old + // values before this chunk's scatter overwrites them. + const auto read_old_from_rows = finalized.Enabled(); + if (read_old_from_rows) { + delta.updated_aggregate_rows.Reset(); + finalized.Gather(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), row_count, + delta.updated_aggregate_rows); + } + FinalizeStateRowsFromStates(delta.row_state, delta.finalize_addresses, delta.key_scan_rows, + delta.aggregate_rows, delta.result_rows); + auto &previous_payloads = read_old_from_rows ? delta.updated_aggregate_rows : delta.previous_scan_rows; + const idx_t previous_payload_offset = read_old_from_rows ? 0 : 1; if (op.keyed.has_payload_comparisons) { delta.comparison_rows.Reset(); for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size(); payload_idx++) { delta.comparison_rows.data[payload_idx].Reference( - delta.previous_scan_rows.data[previous_payload_offset + payload_idx]); + previous_payloads.data[previous_payload_offset + payload_idx]); delta.comparison_rows.data[op.payload_idx.size() + payload_idx].Reference( delta.result_rows.data[op.payload_idx[payload_idx]]); } @@ -446,7 +530,7 @@ idx_t RecursiveCTEKeyedState::FinalizeUsingKeyDelta(bool update_partial_indexes, delta.comparison_rows, delta.changed_column_groups, next_equal_groups, equal_groups, equal_count); } else { changed_column_count = - SelectDistinctPayloadRows(delta.previous_scan_rows.data[previous_payload_offset + payload_idx], + SelectDistinctPayloadRows(previous_payloads.data[previous_payload_offset + payload_idx], delta.result_rows.data[op.payload_idx[payload_idx]], equal_groups, equal_count, delta.changed_column_groups, next_equal_groups); } @@ -457,6 +541,11 @@ idx_t RecursiveCTEKeyedState::FinalizeUsingKeyDelta(bool update_partial_indexes, equal_count -= changed_column_count; equal_groups = &next_equal_groups; } + if (finalized.Enabled()) { + // Every touched group's new value is published, whether or not it joins the frontier. + finalized.Scatter(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), row_count, + delta.aggregate_rows); + } if (changed_count > 0) { delta.changed_count += changed_count; delta.changed_rows.Reset(); @@ -487,8 +576,12 @@ idx_t RecursiveCTEKeyedState::FinalizeUsingKeyDelta(bool update_partial_indexes, } CopySelectedAddresses(group_addresses, *FlatVector::IncrementalSelectionVector(), row_count, delta.finalize_addresses); - FinalizeStateRows(delta.row_state, delta.finalize_addresses, delta.key_scan_rows, delta.aggregate_rows, - delta.result_rows); + FinalizeStateRowsFromStates(delta.row_state, delta.finalize_addresses, delta.key_scan_rows, + delta.aggregate_rows, delta.result_rows); + if (finalized.Enabled()) { + finalized.Scatter(delta.finalize_addresses, *FlatVector::IncrementalSelectionVector(), row_count, + delta.aggregate_rows); + } op.working_table->Append(working_append_state, delta.result_rows); }; diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp index 61af6ef10..69a0f6255 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp @@ -1,7 +1,10 @@ #include "duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte_delta.hpp" +#include "duckdb/common/types/string_heap.hpp" +#include "duckdb/common/types/vector_buffer.hpp" #include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/common/vector/string_vector.hpp" #include "duckdb/execution/operator/scan/physical_column_data_scan.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -68,9 +71,322 @@ RecursiveCTEKeyedProperties RecursiveCTEKeyedProperties::Derive(const PhysicalRe break; } } + // Key-only recursion has no payload values to materialize and must not reserve an empty region. + result.materialize_finalized_values = !op.aggregate_types.empty(); + for (auto &aggregate_type : op.aggregate_types) { + const auto physical_type = aggregate_type.InternalType(); + if (!TypeIsConstantSize(physical_type) && physical_type != PhysicalType::VARCHAR) { + result.materialize_finalized_values = false; + break; + } + } + // The candidate-reuse paths skip the commit finalization, so the candidates themselves must be scatterable + // into the finalized values through each aggregate's first input. + if (result.materialize_finalized_values && result.can_reuse_new_group_candidates) { + for (auto &payload_aggregate : op.payload_aggregates) { + if (payload_aggregate->Cast().GetChildren().empty()) { + result.materialize_finalized_values = false; + break; + } + } + } return result; } +//===--------------------------------------------------------------------===// +// Finalized Values +//===--------------------------------------------------------------------===// +static idx_t FinalizedValueSlotWidth(const LogicalType &type) { + return GetTypeIdSize(type.InternalType()); +} + +RecursiveCTEFinalizedValues::RecursiveCTEFinalizedValues(ClientContext &context, const PhysicalRecursiveCTE &op) { + enabled = op.UsingKey() && op.keyed.materialize_finalized_values; + if (!enabled) { + return; + } + // One validity byte per aggregate, then the value slots in aggregate order. + idx_t offset = op.aggregate_types.size(); + value_types.reserve(op.aggregate_types.size()); + value_offsets.reserve(op.aggregate_types.size()); + identity_source_columns.reserve(op.aggregate_types.size()); + for (auto &aggregate_type : op.aggregate_types) { + identity_source_columns.push_back(value_types.size()); + value_types.push_back(aggregate_type.InternalType()); + value_offsets.push_back(offset); + offset += FinalizedValueSlotWidth(aggregate_type); + } + region_width = offset; + // The scratch tables size their trailing region through RegionWidthFor, so the layouts must agree. + D_ASSERT(region_width == RegionWidthFor(op)); + // The buffer allocator keeps the finalized strings inside the memory accounting, like the states they mirror. + auto heap_holder = make_uniq(BufferAllocator::Get(context)); + string_heap = heap_holder->heap; + string_arena = make_buffer(); + string_arena->data.push_back(std::move(heap_holder)); + idx_t child_offset = 0; + for (auto &payload_aggregate : op.payload_aggregates) { + auto &children = payload_aggregate->Cast().GetChildren(); + if (children.empty()) { + candidate_source_columns.clear(); + break; + } + candidate_source_columns.push_back(child_offset); + child_offset += children.size(); + } +} + +idx_t RecursiveCTEFinalizedValues::RegionWidthFor(const PhysicalRecursiveCTE &op) { + if (!op.UsingKey() || !op.keyed.materialize_finalized_values) { + return 0; + } + idx_t width = op.aggregate_types.size(); + for (auto &aggregate_type : op.aggregate_types) { + width += FinalizedValueSlotWidth(aggregate_type); + } + return width; +} + +void RecursiveCTEFinalizedValues::BindLayout(const TupleDataLayout &layout) { + D_ASSERT(enabled && layout.GetTrailingRegionWidth() >= region_width); + region_offset = layout.GetTrailingRegionOffset(); +} + +string_t RecursiveCTEFinalizedValues::CopyStringToArena(string_t value) { + D_ASSERT(!value.IsInlined()); + string_live_bytes += value.GetSize(); + return string_heap->AddBlob(value); +} + +template +static void ScatterFixedSlots(const data_ptr_t *address_data, const SelectionVector &sel, idx_t count, + const UnifiedVectorFormat &source_format, idx_t region_offset, idx_t slot_offset, + idx_t agg_idx) { + const auto source_data = source_format.data; + for (idx_t row_idx = 0; row_idx < count; row_idx++) { + const auto value_idx = sel.get_index(row_idx); + const auto region = address_data[value_idx] + region_offset; + const auto source_idx = source_format.sel->get_index(value_idx); + if (!source_format.validity.RowIsValid(source_idx)) { + region[agg_idx] = 0; + continue; + } + memcpy(region + slot_offset, source_data + source_idx * WIDTH, WIDTH); + region[agg_idx] = 1; + } +} + +void RecursiveCTEFinalizedValues::ScatterColumns(const Vector &addresses, const SelectionVector &sel, idx_t count, + DataChunk &values, const vector &source_columns) { + if (count == 0) { + return; + } + D_ASSERT(addresses.GetVectorType() == VectorType::FLAT_VECTOR); + auto address_data = FlatVector::GetData(addresses); + for (idx_t agg_idx = 0; agg_idx < value_types.size(); agg_idx++) { + auto &source = values.data[source_columns[agg_idx]]; + const auto slot_offset = value_offsets[agg_idx]; + const auto slot_width = GetTypeIdSize(value_types[agg_idx]); + UnifiedVectorFormat source_format; + source.ToUnifiedFormat(source_format); + if (value_types[agg_idx] == PhysicalType::VARCHAR) { + const auto source_data = source_format.data; + for (idx_t row_idx = 0; row_idx < count; row_idx++) { + const auto value_idx = sel.get_index(row_idx); + const auto region = address_data[value_idx] + region_offset; + const auto source_idx = source_format.sel->get_index(value_idx); + const auto slot_valid = region[agg_idx] != 0; + if (!source_format.validity.RowIsValid(source_idx)) { + if (slot_valid) { + // Account for the string bytes this slot stops referencing. + const auto previous = Load(region + slot_offset); + if (!previous.IsInlined()) { + const auto previous_size = previous.GetSize(); + string_garbage_bytes += previous_size; + string_live_bytes -= MinValue(string_live_bytes, previous_size); + } + } + region[agg_idx] = 0; + continue; + } + auto value = reinterpret_cast(source_data)[source_idx]; + if (slot_valid) { + const auto previous = Load(region + slot_offset); + // A byte-equal refresh keeps the stored string, so unchanged values near a fixpoint cause + // no arena growth and no garbage; compaction still migrates these slots like any other. + if (previous == value) { + continue; + } + if (!previous.IsInlined()) { + const auto previous_size = previous.GetSize(); + string_garbage_bytes += previous_size; + string_live_bytes -= MinValue(string_live_bytes, previous_size); + } + } + if (!value.IsInlined()) { + value = CopyStringToArena(value); + } + Store(value, region + slot_offset); + region[agg_idx] = 1; + } + continue; + } + switch (slot_width) { + case 1: + ScatterFixedSlots<1>(address_data, sel, count, source_format, region_offset, slot_offset, agg_idx); + break; + case 2: + ScatterFixedSlots<2>(address_data, sel, count, source_format, region_offset, slot_offset, agg_idx); + break; + case 4: + ScatterFixedSlots<4>(address_data, sel, count, source_format, region_offset, slot_offset, agg_idx); + break; + case 8: + ScatterFixedSlots<8>(address_data, sel, count, source_format, region_offset, slot_offset, agg_idx); + break; + case 16: + ScatterFixedSlots<16>(address_data, sel, count, source_format, region_offset, slot_offset, agg_idx); + break; + default: + throw InternalException("Unsupported finalized value slot width"); + } + } +} + +void RecursiveCTEFinalizedValues::Scatter(const Vector &addresses, const SelectionVector &sel, idx_t count, + DataChunk &values) { + D_ASSERT(enabled && values.ColumnCount() == value_types.size()); + ScatterColumns(addresses, sel, count, values, identity_source_columns); +} + +void RecursiveCTEFinalizedValues::ScatterCandidates(const Vector &addresses, const SelectionVector &sel, idx_t count, + DataChunk &payload) { + D_ASSERT(enabled && !candidate_source_columns.empty()); + ScatterColumns(addresses, sel, count, payload, candidate_source_columns); +} + +template +static void GatherFixedSlots(const data_ptr_t *address_data, const SelectionVector &sel, idx_t count, + data_ptr_t target_data, ValidityMask &target_validity, idx_t region_offset, + idx_t slot_offset, idx_t agg_idx) { + for (idx_t row_idx = 0; row_idx < count; row_idx++) { + const auto region = address_data[sel.get_index(row_idx)] + region_offset; + if (region[agg_idx] == 0) { + target_validity.SetInvalid(row_idx); + continue; + } + memcpy(target_data + row_idx * WIDTH, region + slot_offset, WIDTH); + } +} + +void RecursiveCTEFinalizedValues::Gather(const Vector &addresses, const SelectionVector &sel, idx_t count, + DataChunk &values) { + D_ASSERT(enabled && values.ColumnCount() == value_types.size()); + D_ASSERT(addresses.GetVectorType() == VectorType::FLAT_VECTOR); + auto address_data = FlatVector::GetData(addresses); + for (idx_t agg_idx = 0; agg_idx < value_types.size(); agg_idx++) { + auto &target = values.data[agg_idx]; + target.SetVectorType(VectorType::FLAT_VECTOR); + auto &target_validity = FlatVector::ValidityMutable(target); + const auto slot_offset = value_offsets[agg_idx]; + const auto slot_width = GetTypeIdSize(value_types[agg_idx]); + const auto target_data = FlatVector::GetDataMutable(target); + if (value_types[agg_idx] == PhysicalType::VARCHAR) { + bool references_arena = false; + for (idx_t row_idx = 0; row_idx < count; row_idx++) { + const auto region = address_data[sel.get_index(row_idx)] + region_offset; + if (region[agg_idx] == 0) { + target_validity.SetInvalid(row_idx); + continue; + } + const auto value = Load(region + slot_offset); + reinterpret_cast(target_data)[row_idx] = value; + references_arena = references_arena || !value.IsInlined(); + } + FlatVector::SetSize(target, count); + // The emitted strings point into the shared heap, so the vector takes a reference that outlives + // any compaction swap. + if (references_arena) { + StringVector::AddAuxiliaryData(target, make_uniq(string_arena)); + } + continue; + } + switch (slot_width) { + case 1: + GatherFixedSlots<1>(address_data, sel, count, target_data, target_validity, region_offset, slot_offset, + agg_idx); + break; + case 2: + GatherFixedSlots<2>(address_data, sel, count, target_data, target_validity, region_offset, slot_offset, + agg_idx); + break; + case 4: + GatherFixedSlots<4>(address_data, sel, count, target_data, target_validity, region_offset, slot_offset, + agg_idx); + break; + case 8: + GatherFixedSlots<8>(address_data, sel, count, target_data, target_validity, region_offset, slot_offset, + agg_idx); + break; + case 16: + GatherFixedSlots<16>(address_data, sel, count, target_data, target_validity, region_offset, slot_offset, + agg_idx); + break; + default: + throw InternalException("Unsupported finalized value slot width"); + } + FlatVector::SetSize(target, count); + } + values.CheckCardinality(count); +} + +void RecursiveCTEFinalizedValues::MaybeCompact(GroupedAggregateHashTable &target) { + if (!enabled || string_garbage_bytes <= string_live_bytes || string_garbage_bytes < 262144) { + return; + } + auto fresh_holder = make_uniq(string_heap->GetAllocator().GetUnderlyingAllocator()); + auto &fresh_heap = fresh_holder->heap; + idx_t live_bytes = 0; + AggregateHTScanState scan_state; + // The scan reads the group columns without the trailing hash column. + auto key_types = target.GetLayout().GetTypes(); + key_types.pop_back(); + DataChunk keys; + keys.Initialize(Allocator::DefaultAllocator(), key_types); + target.InitializeScan(scan_state); + while (target.ScanGroups(scan_state, keys)) { + const auto row_count = keys.size(); + if (row_count == 0) { + continue; + } + auto row_locations = FlatVector::GetData(scan_state.scan_states.chunk_state.row_locations); + for (idx_t agg_idx = 0; agg_idx < value_types.size(); agg_idx++) { + if (value_types[agg_idx] != PhysicalType::VARCHAR) { + continue; + } + const auto slot_offset = value_offsets[agg_idx]; + for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { + const auto region = row_locations[row_idx] + region_offset; + if (region[agg_idx] == 0) { + continue; + } + auto value = Load(region + slot_offset); + if (value.IsInlined()) { + continue; + } + // Every live slot migrates, including the byte-equal refreshes that kept their old pointer. + Store(fresh_heap.AddBlob(value), region + slot_offset); + live_bytes += value.GetSize(); + } + } + } + string_heap = fresh_holder->heap; + string_arena = make_buffer(); + string_arena->data.push_back(std::move(fresh_holder)); + string_live_bytes = live_bytes; + string_garbage_bytes = 0; +} + RecursiveCTEKeyedCandidateExtractor::RecursiveCTEKeyedCandidateExtractor(ClientContext &context, const PhysicalRecursiveCTE &op) : op(op), payload_executor(context) { @@ -120,9 +436,9 @@ void RecursiveCTEKeyedCandidateExtractor::EvaluatePayload(DataChunk &source, Dat // Sink //===--------------------------------------------------------------------===// RecursiveCTEKeyedState::RecursiveCTEKeyedState(ClientContext &context, const PhysicalRecursiveCTE &op) - : RecursiveCTEState(context, op), extractor(context, op), new_group_addresses(LogicalType::POINTER), - new_groups(STANDARD_VECTOR_SIZE), intermediate_table(context, op.internal_types), - preaggregation_hashes(LogicalType::HASH, nullptr, 0) { + : RecursiveCTEState(context, op), finalized(context, op), extractor(context, op), + new_group_addresses(LogicalType::POINTER), new_groups(STANDARD_VECTOR_SIZE), + intermediate_table(context, op.internal_types), preaggregation_hashes(LogicalType::HASH, nullptr, 0) { for (idx_t i = 0; i < op.payload_aggregates.size(); i++) { D_ASSERT(op.payload_aggregates[i]->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE); auto &bound_aggr_expr = op.payload_aggregates[i]->Cast(); @@ -139,6 +455,12 @@ RecursiveCTEKeyedState::RecursiveCTEKeyedState(ClientContext &context, const Phy } ht = CreateUsingKeyHashTable(); + if (finalized.Enabled()) { + finalized.BindLayout(ht->GetLayout()); + } + if (!op.UnionAll()) { + key_delta = make_uniq(context, op, finalized.Enabled()); + } for (auto &spec : op.partial_key_index_specs) { partial_key_indexes.push_back( make_uniq(Allocator::Get(context), op.hash_key_types, spec.Indices())); @@ -146,9 +468,6 @@ RecursiveCTEKeyedState::RecursiveCTEKeyedState(ClientContext &context, const Phy if (op.keyed.can_preaggregate) { preaggregation_hashes.Initialize(); } - if (!op.UnionAll()) { - key_delta = make_uniq(context, op); - } distinct_rows.Initialize(Allocator::DefaultAllocator(), op.hash_key_types); update_rows.Initialize(Allocator::DefaultAllocator(), op.internal_types); source_distinct_rows.Initialize(Allocator::DefaultAllocator(), op.hash_key_types); @@ -163,7 +482,9 @@ RecursiveCTEKeyedState::~RecursiveCTEKeyedState() { unique_ptr RecursiveCTEKeyedState::CreateUsingKeyHashTable() const { return make_uniq(context, BufferAllocator::Get(context), op.hash_key_types, - op.aggregate_types, payload_aggregate_objects); + op.aggregate_types, payload_aggregate_objects, + GroupedAggregateHashTable::InitialCapacity(), 0, + TupleDataValidityType::CAN_HAVE_NULL_VALUES, finalized.RegionWidth()); } const RecursiveCTEPartialKeyIndex &RecursiveCTEKeyedState::GetPartialKeyIndex(const vector &key_indices) const { @@ -246,10 +567,26 @@ void RecursiveCTEKeyedState::AssembleStateRows(DataChunk &keys, DataChunk &aggre void RecursiveCTEKeyedState::FinalizeStateRows(RowOperationsState &row_state, Vector &addresses, DataChunk &keys, DataChunk &aggregates, DataChunk &result) { + if (finalized.Enabled()) { + ReadStateRows(addresses, keys, aggregates, result); + return; + } + FinalizeStateRowsFromStates(row_state, addresses, keys, aggregates, result); +} + +void RecursiveCTEKeyedState::FinalizeStateRowsFromStates(RowOperationsState &row_state, Vector &addresses, + DataChunk &keys, DataChunk &aggregates, DataChunk &result) { FinalizeAggregateRows(row_state, addresses, aggregates, keys.size()); AssembleStateRows(keys, aggregates, result); } +void RecursiveCTEKeyedState::ReadStateRows(const Vector &addresses, DataChunk &keys, DataChunk &aggregates, + DataChunk &result) { + aggregates.Reset(); + finalized.Gather(addresses, *FlatVector::IncrementalSelectionVector(), keys.size(), aggregates); + AssembleStateRows(keys, aggregates, result); +} + void RecursiveCTEKeyedState::FinalizeAggregateRows(RowOperationsState &row_state, Vector &addresses, DataChunk &aggregates, idx_t count) { aggregates.Reset(); @@ -310,8 +647,11 @@ class RecursiveCTELocalPreaggregationState { } unique_ptr Preaggregate(ColumnDataCollection &candidates) { - auto result = make_uniq(context, BufferAllocator::Get(context), op.hash_key_types, - op.aggregate_types, aggregates); + // The scratch layout must match the persistent table's for Combine, so it carries the region bytes. + auto result = make_uniq( + context, BufferAllocator::Get(context), op.hash_key_types, op.aggregate_types, aggregates, + GroupedAggregateHashTable::InitialCapacity(), 0, TupleDataValidityType::CAN_HAVE_NULL_VALUES, + RecursiveCTEFinalizedValues::RegionWidthFor(op)); ColumnDataScanState scan_state; candidates.InitializeScan(scan_state); while (candidates.Scan(scan_state, input)) { @@ -842,6 +1182,8 @@ void RecursiveCTEKeyedState::CommitUsingKeyUpdates() { } else { CommitUsingKeyUpdatesInternal(); } + // No readers exist between the commit and the next iteration, so replaced strings can be reclaimed here. + finalized.MaybeCompact(*ht); } SinkResultType RecursiveCTEKeyedState::Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) { @@ -900,19 +1242,21 @@ idx_t RecursiveCTEKeyedState::RecurringStateChunks() const { } SourceResultType RecursiveCTEKeyedState::GetData(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source) { + RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state) { if (source_phase == RecursiveCTESourcePhase::INITIAL) { source_phase = RecursiveCTESourcePhase::RECURSING_KEY; } if (metrics.Enabled()) { - return GetUsingKeyDataInternal(context, chunk, source); + return GetUsingKeyDataInternal(context, chunk, source, interrupt_state); } - return GetUsingKeyDataInternal(context, chunk, source); + return GetUsingKeyDataInternal(context, chunk, source, interrupt_state); } template SourceResultType RecursiveCTEKeyedState::GetUsingKeyDataInternal(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source) { + RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state) { while (true) { switch (source_phase) { case RecursiveCTESourcePhase::RECURSING_KEY: { @@ -940,23 +1284,39 @@ SourceResultType RecursiveCTEKeyedState::GetUsingKeyDataInternal(ExecutionContex } } - op.ExecuteRecursivePipelines(context); + source_phase = RecursiveCTESourcePhase::EXECUTING_RECURSION; + break; + } + case RecursiveCTESourcePhase::EXECUTING_RECURSION: { + if (op.ExecuteRecursivePipelines(context, interrupt_state) == RecursiveEpochResult::BLOCKED) { + // the epoch waits for blocked inner work; the interrupt state re-enters this source + return SourceResultType::BLOCKED; + } const auto next_count = op.UnionAll() ? intermediate_table.Count() : op.working_table->Count(); if (next_count == 0) { ht->InitializeScan(ht_scan_state); source.StartFinalDrain(ht->Count()); source_phase = RecursiveCTESourcePhase::DRAINING_FINAL_KEY_STATE; + } else { + source_phase = RecursiveCTESourcePhase::RECURSING_KEY; } break; } case RecursiveCTESourcePhase::DRAINING_FINAL_KEY_STATE: { const auto drain_start = COLLECT_METRICS ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point(); - while (ht->Scan(ht_scan_state, source_distinct_rows, source_aggregate_rows)) { + while (finalized.Enabled() ? ht->ScanGroups(ht_scan_state, source_distinct_rows) + : ht->Scan(ht_scan_state, source_distinct_rows, source_aggregate_rows)) { if (source_distinct_rows.size() == 0) { continue; } - AssembleStateRows(source_distinct_rows, source_aggregate_rows, chunk); + if (finalized.Enabled()) { + // The last commit left the finalized values current, so the drain is a plain read. + ReadStateRows(ht_scan_state.scan_states.chunk_state.row_locations, source_distinct_rows, + source_aggregate_rows, chunk); + } else { + AssembleStateRows(source_distinct_rows, source_aggregate_rows, chunk); + } source.AddEmittedRows(chunk.size()); if constexpr (COLLECT_METRICS) { metrics.RecordFinalStateRows(chunk.size()); @@ -999,13 +1359,16 @@ class RecursiveCTEStateScanGlobalState : public GlobalSourceState { class RecursiveCTEStateScanLocalState : public LocalSourceState { public: RecursiveCTEStateScanLocalState(ClientContext &context, const PhysicalRecursiveCTE &op) - : found_groups(STANDARD_VECTOR_SIZE), arena(Allocator::Get(context)), row_state(arena) { + : scan_addresses(LogicalType::POINTER), found_groups(STANDARD_VECTOR_SIZE), arena(Allocator::Get(context)), + row_state(arena) { distinct_rows.Initialize(Allocator::Get(context), op.hash_key_types); aggregate_rows.Initialize(Allocator::Get(context), op.aggregate_types); } DataChunk distinct_rows; DataChunk aggregate_rows; + //! Row addresses of the scanned groups, copied out of the shared scan state under its lock + Vector scan_addresses; AggregateHTLookupState lookup_state; SelectionVector found_groups; ArenaAllocator arena; @@ -1058,6 +1421,7 @@ SourceResultType PhysicalRecursiveCTEStateScan::GetDataFromState(DataChunk &chun RecursiveCTEKeyedState &recursive_state) const { auto &gstate = input.global_state.Cast(); auto &lstate = input.local_state.Cast(); + const auto read_finalized = recursive_state.UsesFinalizedValues(); while (true) { { lock_guard guard(gstate.lock); @@ -1070,10 +1434,25 @@ SourceResultType PhysicalRecursiveCTEStateScan::GetDataFromState(DataChunk &chun return SourceResultType::FINISHED; } gstate.scanned_groups.fetch_add(lstate.distinct_rows.size(), std::memory_order_relaxed); + if (read_finalized && lstate.distinct_rows.size() > 0) { + // The shared scan state owns the row addresses, so copy them out while still under the lock. + auto &row_locations = gstate.scan_state.scan_states.chunk_state.row_locations; + lstate.scan_addresses.SetVectorType(VectorType::FLAT_VECTOR); + memcpy(data_ptr_cast(FlatVector::GetDataMutable(lstate.scan_addresses)), + const_data_ptr_cast(FlatVector::GetData(row_locations)), + lstate.distinct_rows.size() * sizeof(data_ptr_t)); + } } if (lstate.distinct_rows.size() == 0) { continue; } + if (read_finalized) { + recursive_state.ReadStateRows(lstate.scan_addresses, lstate.distinct_rows, lstate.aggregate_rows, chunk); + if (recursive_state.GetMetrics().Enabled()) { + recursive_state.GetMetrics().RecordRecurringScanRows(chunk.size()); + } + return SourceResultType::HAVE_MORE_OUTPUT; + } const auto group_count = lstate.distinct_rows.size(); const auto found_count = recursive_state.GetHashTable().LookupGroups(lstate.distinct_rows, lstate.lookup_state, lstate.found_groups); diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_runtime.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_runtime.cpp index b77baaa32..35ccd3e99 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_runtime.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_runtime.cpp @@ -9,6 +9,7 @@ #include "duckdb/execution/operator/join/physical_recursive_cte_key_join.hpp" #include "duckdb/execution/operator/scan/physical_column_data_scan.hpp" #include "duckdb/execution/operator/set/physical_cte.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/parallel/base_pipeline_event.hpp" #include "duckdb/parallel/event.hpp" #include "duckdb/parallel/meta_pipeline.hpp" @@ -176,22 +177,38 @@ static idx_t GetRecursivePipelineMaxThreads(Pipeline &pipeline, idx_t worker_lim return MinValue(max_threads, worker_limit); } -static void ExecuteRecursivePipelineInline(PipelineExecutor &pipeline_executor) { - auto signal_state = make_shared_ptr(); - pipeline_executor.SetInterruptState(InterruptState(weak_ptr(signal_state))); - while (true) { - auto result = pipeline_executor.Execute(); - switch (result) { - case PipelineExecuteResult::FINISHED: - return; - case PipelineExecuteResult::NOT_FINISHED: - throw InternalException("Execute without limit should not return NOT_FINISHED"); - case PipelineExecuteResult::INTERRUPTED: - signal_state->Await(); - break; +//! Wakes the recursive CTE source that returned BLOCKED up the stack: fires the outer task's +//! interrupt callback once every dependency has finished, so the regular executor flow reschedules +//! the operator. Arm() decides atomically whether the callback will fire. It returns true when the +//! dependencies were still outstanding at arming time, so the caller must return BLOCKED and will +//! be woken. It returns false when they had already finished: the caller proceeds synchronously +//! and no callback fires. Calling Arm() again after the callback fired returns false, so a resumed +//! caller uses the same call to observe completion. +class RecursiveCTEWakeEvent : public Event { +public: + RecursiveCTEWakeEvent(Executor &executor_p, InterruptState interrupt_state_p) + : Event(executor_p), interrupt_state(std::move(interrupt_state_p)) { + } + + void Schedule() override { + } + + void FinalizeFinish() override { + if (wake_state.exchange(WakeState::FINISHED) == WakeState::ARMED) { + interrupt_state.Callback(); } } -} + + bool Arm() { + return wake_state.exchange(WakeState::ARMED) != WakeState::FINISHED; + } + +private: + enum class WakeState : uint8_t { PENDING, ARMED, FINISHED }; + + InterruptState interrupt_state; + atomic wake_state {WakeState::PENDING}; +}; template struct RecursiveCTETaskMetrics { @@ -330,59 +347,18 @@ class RecursiveCTEPipelineEvent : public BasePipelineEvent { } }; -//! Inline finish event for the single-thread recursive fast path. -//! PipelineFinishEvent is correct for the general scheduler, but it is intentionally scheduler-centric: -//! it expects finish work to go back through the task/event machinery. In the single-thread recursive -//! path that would mostly bounce control back into the scheduler just to run the finish work on the -//! current thread. This event preserves the same finalize contract, including BLOCKED handling, while -//! keeping the finish step inline with the cached execute/prepare stages. -class RecursiveCTEFinishEvent : public BasePipelineEvent { +//! Bookkeeping event for an inline finish stage. The finalize loop runs on the operator's source +//! thread and passes this event to the finalize calls, so an inserted replacement event (e.g. +//! parallel sort materialization) adopts this event's parents. The wake event attached as a parent +//! therefore fires only once inserted work has finished as well. +class RecursiveCTEInlineFinishEvent : public BasePipelineEvent { public: - explicit RecursiveCTEFinishEvent(shared_ptr pipeline_p) : BasePipelineEvent(std::move(pipeline_p)) { + explicit RecursiveCTEInlineFinishEvent(Pipeline &pipeline_p) : BasePipelineEvent(pipeline_p) { + total_tasks = 1; } void Schedule() override { - // This event is only used by the single-thread inline recursive fast path. - // Blocking here is safe because the caller runs it synchronously and explicitly waits for completion. - D_ASSERT(total_tasks == 0); - total_tasks = 1; - - auto signal_state = make_shared_ptr(); - InterruptState interrupt_state {weak_ptr(signal_state)}; - auto sink = pipeline->GetSink(); - auto &operators = pipeline->GetIntermediateOperators(); - idx_t operator_idx = 0; - - while (true) { - bool blocked = false; - for (; operator_idx < operators.size(); operator_idx++) { - auto &op = operators[operator_idx].get(); - if (!op.RequiresOperatorFinalize()) { - continue; - } - OperatorFinalizeInput op_finalize_input {*op.op_state, interrupt_state}; - auto op_state = op.OperatorFinalize(*pipeline, *this, executor.context, op_finalize_input); - if (op_state == OperatorFinalResultType::BLOCKED) { - signal_state->Await(); - blocked = true; - break; - } - } - if (blocked) { - continue; - } - - OperatorSinkFinalizeInput finalize_input {*sink->sink_state, interrupt_state}; - auto sink_state = sink->Finalize(*pipeline, *this, executor.context, finalize_input); - if (sink_state == SinkFinalizeType::BLOCKED) { - signal_state->Await(); - continue; - } - - sink->sink_state->state = sink_state; - FinishTask(); - return; - } + throw InternalException("RecursiveCTEInlineFinishEvent cannot be scheduled"); } }; @@ -409,8 +385,9 @@ BuildRecursivePipelineSchedulePlan(const vector> &meta_ for (auto &meta_pipeline : meta_pipelines) { auto metric_type = RecursiveCTEPipelineMetricType::RECURSIVE; bool is_invariant_build = false; - if (recursive_cte.invariant_meta_pipelines.find(*meta_pipeline) != - recursive_cte.invariant_meta_pipelines.end()) { + const auto is_invariant = + recursive_cte.invariant_meta_pipelines.find(*meta_pipeline) != recursive_cte.invariant_meta_pipelines.end(); + if (is_invariant) { auto sink = meta_pipeline->GetSink(); is_invariant_build = !sink || sink->type != PhysicalOperatorType::CTE; metric_type = sink && sink->type == PhysicalOperatorType::CTE @@ -424,6 +401,7 @@ BuildRecursivePipelineSchedulePlan(const vector> &meta_ if (is_invariant_build) { invariant_build_pipelines.insert(*pipeline); } + plan->pipelines.emplace_back(*pipeline, is_invariant); } } // Retained invariant meta-pipelines are absent after the first epoch, so build the induced schedule for @@ -714,25 +692,6 @@ FindInvariantRecursiveMetaPipelines(const vector> &meta return result; } -static vector> GetActiveRecursiveMetaPipelines(const PhysicalRecursiveCTE &op, - RecursiveCTEState &state) { - vector> meta_pipelines; - op.recursive_meta_pipeline->GetMetaPipelines(meta_pipelines, true, false); - if (!state.AllowsExecutorReuse() || !state.HasMaterializedInvariantPipelines() || - op.invariant_meta_pipelines.empty()) { - return meta_pipelines; - } - - vector> active_meta_pipelines; - active_meta_pipelines.reserve(meta_pipelines.size()); - for (auto &meta_pipeline : meta_pipelines) { - if (op.invariant_meta_pipelines.find(*meta_pipeline) == op.invariant_meta_pipelines.end()) { - active_meta_pipelines.push_back(meta_pipeline); - } - } - return active_meta_pipelines; -} - static void ConfigureInvariantRecursiveBuildReuse(const PhysicalRecursiveCTE &op, bool preserve_build) { for (auto &meta_pipeline_ref : op.invariant_meta_pipelines) { auto sink = meta_pipeline_ref.get().GetSink(); @@ -760,41 +719,9 @@ static bool InvariantRecursiveBuildsRemainReusable(const PhysicalRecursiveCTE &o return true; } -static void ProcessRecursiveExecutorTasks(Executor &executor) { - // Only drain the recursive executor here. Re-entering the outer query executor while waiting for - // recursive work can run unrelated tasks and used to break recursive completion tracking. - if (!executor.WorkOnTasks()) { - executor.WaitForTask(); - } - if (executor.HasError()) { - executor.ThrowException(); - } -} - -static void WaitForRecursiveEvents(Executor &executor, vector> &events) { - while (true) { - ProcessRecursiveExecutorTasks(executor); - bool finished = true; - for (auto &event : events) { - if (!event->IsFinished()) { - finished = false; - break; - } - } - if (finished) { - break; - } - } -} - -static void WaitForRecursiveEvent(Executor &executor, Event &event) { - while (!event.IsFinished()) { - ProcessRecursiveExecutorTasks(executor); - } -} - static void ScheduleRecursivePlan(const RecursiveCTEPipelineSchedulePlan &plan, RecursiveCTEState &state, - vector> &events, const RecursiveCTEParallelism ¶llelism) { + vector> &events, const RecursiveCTEParallelism ¶llelism, + Event &wake_event) { for (auto &pipeline : plan.initialize_on_schedule_pipelines) { pipeline.get().ResetSource(true); } @@ -829,6 +756,12 @@ static void ScheduleRecursivePlan(const RecursiveCTEPipelineSchedulePlan &plan, } } + // The wake event depends on every event of the schedule. Its edges must be wired before any + // event can run: AddDependency is not safe against a concurrently finishing event. + for (auto &event : events) { + wake_event.AddDependency(*event); + } + for (idx_t stage_idx = 0; stage_idx < plan.stages.size(); stage_idx++) { auto &event = events[stage_idx]; if (event->HasDependencies()) { @@ -844,87 +777,149 @@ static void ScheduleRecursivePlan(const RecursiveCTEPipelineSchedulePlan &plan, } } -static void ExecuteRecursivePipelineFinishInline(Pipeline &pipeline, Executor &executor) { - auto finish_event = make_shared_ptr(pipeline.shared_from_this()); - auto complete_event = make_shared_ptr(executor, false); - complete_event->AddDependency(*finish_event); - finish_event->Schedule(); - if (!complete_event->IsFinished()) { - WaitForRecursiveEvent(executor, *complete_event); - } -} - +//! Drives the cached inline dependency plan, resuming from the suspended position in the epoch +//! progress. Returns false when a stage suspended on blocked work: the operator's source then +//! returns BLOCKED up the stack and the registered interrupt state re-enters it. template -static void ExecuteRecursiveInlinePlan(RecursiveCTEState &state, Executor &executor, - const RecursiveCTEPipelineSchedulePlan &plan) { - for (auto &pipeline : plan.initialize_on_schedule_pipelines) { - pipeline.get().ResetSource(true); - } - - state.GetScheduler().InitializeInlinePlan(plan); - - for (idx_t ready_idx = 0; ready_idx < state.GetScheduler().ReadyStageCount(); ready_idx++) { - auto stage_idx = state.GetScheduler().ReadyStage(ready_idx); +static bool DriveRecursiveInlinePlan(RecursiveCTEState &state, Executor &executor, + const RecursiveCTEPipelineSchedulePlan &plan, + const InterruptState &interrupt_state) { + auto &progress = state.GetEpochProgress(); + auto &scheduler = state.GetScheduler(); + + while (progress.ready_idx < scheduler.ReadyStageCount()) { + const auto stage_idx = scheduler.ReadyStage(progress.ready_idx); auto &stage = plan.stages[stage_idx]; auto &pipeline = stage.pipeline.get(); switch (stage.type) { case PipelineScheduleStageType::EXECUTE: { - // Stages become ready in dependency order, so missing operator state is created here - // through the same initialization path the ordinary scheduler and the event schedule - // use; state shared with an earlier stage is already initialized and kept. - pipeline.InitializeOperatorState(); - pipeline.ResetSourceForReschedule(); - // Invariant builds have independent source work even when the recursive frontier is tiny. - const auto worker_limit = - stage.is_invariant_build ? TaskScheduler::GetScheduler(executor.context).NumberOfThreads() : idx_t(1); - const auto max_threads = GetRecursivePipelineMaxThreads(pipeline, worker_limit); - if (max_threads > 1) { - auto event = make_shared_ptr(pipeline.shared_from_this(), state, - worker_limit, stage.metric_type); - event->SchedulePrepared(max_threads); - WaitForRecursiveEvent(executor, *event); - break; - } - D_ASSERT(max_threads == 1); - AdjustRecursiveSinkWorkers(pipeline, max_threads); - state.GetScheduler().PrepareExecutors(pipeline, max_threads); - auto &executors = state.GetScheduler().GetExecutors(pipeline); - D_ASSERT(executors.size() >= max_threads); - executors[0]->PrepareForExecution(); - if constexpr (COLLECT_METRICS) { - state.GetMetrics().RecordTasks(1); + if (progress.step == RecursiveCTEStageStep::START) { + // Stages become ready in dependency order, so missing operator state is created here + // through the same initialization path the ordinary scheduler and the event schedule + // use; state shared with an earlier stage is already initialized and kept. + pipeline.InitializeOperatorState(); + pipeline.ResetSourceForReschedule(); + // Invariant builds have independent source work even when the recursive frontier is tiny. + const auto worker_limit = stage.is_invariant_build + ? TaskScheduler::GetScheduler(executor.context).NumberOfThreads() + : idx_t(1); + const auto max_threads = GetRecursivePipelineMaxThreads(pipeline, worker_limit); + if (max_threads > 1) { + auto event = make_shared_ptr(pipeline.shared_from_this(), state, + worker_limit, stage.metric_type); + auto wake = make_shared_ptr(executor, interrupt_state); + wake->AddDependency(*event); + progress.stage_event = event; + progress.wake_event = std::move(wake); + event->SchedulePrepared(max_threads); + progress.step = RecursiveCTEStageStep::EVENT_WAIT; + } else { + D_ASSERT(max_threads == 1); + AdjustRecursiveSinkWorkers(pipeline, max_threads); + scheduler.PrepareExecutors(pipeline, max_threads); + auto &executors = scheduler.GetExecutors(pipeline); + D_ASSERT(executors.size() >= max_threads); + executors[0]->PrepareForExecution(); + // a blocked operator registers the source's interrupt state and re-enters it + executors[0]->SetInterruptState(interrupt_state); + if constexpr (COLLECT_METRICS) { + state.GetMetrics().RecordTasks(1); + } + progress.step = RecursiveCTEStageStep::PIPELINE_RUNNING; + } } - const auto execute_start = - COLLECT_METRICS ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point(); - ExecuteRecursivePipelineInline(*executors[0]); - if constexpr (COLLECT_METRICS) { - const auto execute_end = std::chrono::steady_clock::now(); - state.GetEpochMetrics().RecordPipelineExecution( - stage.metric_type, - NumericCast( - std::chrono::duration_cast(execute_end - execute_start).count())); + if (progress.step == RecursiveCTEStageStep::PIPELINE_RUNNING) { + auto &executors = scheduler.GetExecutors(pipeline); + const auto execute_start = + COLLECT_METRICS ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point(); + const auto result = executors[0]->Execute(); + if constexpr (COLLECT_METRICS) { + const auto execute_end = std::chrono::steady_clock::now(); + state.GetEpochMetrics().RecordPipelineExecution( + stage.metric_type, + NumericCast( + std::chrono::duration_cast(execute_end - execute_start).count())); + } + if (result == PipelineExecuteResult::INTERRUPTED) { + return false; + } + if (result != PipelineExecuteResult::FINISHED) { + throw InternalException("Execute without limit should not return NOT_FINISHED"); + } + } else if (progress.step == RecursiveCTEStageStep::EVENT_WAIT) { + if (progress.wake_event->Cast().Arm()) { + return false; + } } break; } case PipelineScheduleStageType::PREPARE_FINISH: pipeline.PrepareFinalize(); break; - case PipelineScheduleStageType::FINISH: - ExecuteRecursivePipelineFinishInline(pipeline, executor); + case PipelineScheduleStageType::FINISH: { + if (progress.step == RecursiveCTEStageStep::START) { + progress.stage_event = make_shared_ptr(pipeline); + auto wake = make_shared_ptr(executor, interrupt_state); + wake->AddDependency(*progress.stage_event); + progress.wake_event = std::move(wake); + progress.finish_operator_idx = 0; + progress.step = RecursiveCTEStageStep::FINISH_FINALIZE; + } + if (progress.step == RecursiveCTEStageStep::FINISH_FINALIZE) { + auto &finish_event = *progress.stage_event; + auto sink = pipeline.GetSink(); + auto &operators = pipeline.GetIntermediateOperators(); + // the finalize inputs take a mutable reference; a blocked finalize stores a copy + InterruptState finalize_interrupt = interrupt_state; + for (; progress.finish_operator_idx < operators.size(); progress.finish_operator_idx++) { + auto &op = operators[progress.finish_operator_idx].get(); + if (!op.RequiresOperatorFinalize()) { + continue; + } + OperatorFinalizeInput op_finalize_input {*op.op_state, finalize_interrupt}; + if (op.OperatorFinalize(pipeline, finish_event, executor.context, op_finalize_input) == + OperatorFinalResultType::BLOCKED) { + // the blocked finalize holds the interrupt state; the resume re-enters it here + return false; + } + } + OperatorSinkFinalizeInput finalize_input {*sink->sink_state, finalize_interrupt}; + auto sink_state = sink->Finalize(pipeline, finish_event, executor.context, finalize_input); + if (sink_state == SinkFinalizeType::BLOCKED) { + return false; + } + sink->sink_state->state = sink_state; + finish_event.FinishTask(); + progress.step = RecursiveCTEStageStep::FINISH_EVENT_WAIT; + } + if (progress.step == RecursiveCTEStageStep::FINISH_EVENT_WAIT) { + // a finalize may have inserted a replacement event, which adopted the bookkeeping + // event's parents: the wake only fires once that work has finished as well + if (progress.wake_event->Cast().Arm()) { + return false; + } + } break; + } default: throw InternalException("Unsupported recursive inline stage"); } - state.GetScheduler().CompleteInlineStage(plan, stage_idx); + progress.stage_event.reset(); + progress.wake_event.reset(); + progress.step = RecursiveCTEStageStep::START; + scheduler.CompleteInlineStage(plan, stage_idx); + progress.ready_idx++; } - if (state.GetScheduler().ReadyStageCount() != plan.stages.size()) { + if (scheduler.ReadyStageCount() != plan.stages.size()) { throw InternalException("Recursive inline plan did not schedule every stage"); } + return true; } -void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) const { +RecursiveEpochResult PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context, + const InterruptState &interrupt_state) const { if (!recursive_meta_pipeline) { throw InternalException("Missing meta pipeline for recursive CTE"); } @@ -932,18 +927,8 @@ void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) auto &gstate = sink_state->Cast(); auto &executor = recursive_meta_pipeline->GetExecutor(); - const auto allow_reuse = gstate.AllowsExecutorReuse(); + auto &progress = gstate.GetEpochProgress(); const auto collect_metrics = gstate.GetMetrics().Enabled(); - auto active_meta_pipelines = GetActiveRecursiveMetaPipelines(*this, gstate); - auto can_cache_invariant_meta_pipelines = allow_reuse && !invariant_meta_pipelines.empty(); - if (collect_metrics && gstate.HasMaterializedInvariantPipelines()) { - for (auto &meta_pipeline : invariant_meta_pipelines) { - auto sink = meta_pipeline.get().GetSink(); - if (sink && sink->type == PhysicalOperatorType::CTE) { - gstate.GetMetrics().RecordRetainedCTEReuse(); - } - } - } // The generic executor path would rebuild the recursive event graph and allocate fresh // PipelineExecutors/tasks every iteration. Recursive execution keeps the already-built recursive @@ -951,58 +936,69 @@ void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) // after they have been materialized once, and then picks between: // - a cached inline dependency plan when the iteration is effectively single-threaded // - a custom recursive Event graph when the iteration still benefits from parallel execution + // The epoch suspends on blocked inner work by returning BLOCKED up the stack; this function is + // then re-entered through the interrupt state and resumes from the stored progress. + // The plan choice only changes in the epilogue below, so it is stable across suspensions. const auto &schedule_plan = gstate.HasMaterializedInvariantPipelines() ? invariant_recursive_schedule_plan : recursive_schedule_plan; if (!schedule_plan) { throw InternalException("Missing recursive pipeline schedule"); } - const auto scheduler_input_rows = GetRecursiveInputRows(gstate); - const auto direct_probe_work_units = recursive_references.direct_probe_work_units; - const auto row_limit = MaxValue(GetRecursiveRowLimit(scheduler_input_rows), direct_probe_work_units); - idx_t work_units = 1; - RecursiveCTEParallelism parallelism(1); - if (row_limit > 1) { - work_units = GetRecursiveWorkUnits(gstate, direct_probe_work_units); - if (work_units > 1) { - parallelism = GetRecursiveParallelism(gstate, work_units, row_limit, *schedule_plan); + if (!progress.active) { + // Epoch prologue: mutates shared sink and operator state, so it must run exactly once per + // epoch, before any recursive work is scheduled. + const auto allow_reuse = gstate.AllowsExecutorReuse(); + const auto can_cache_invariant_meta_pipelines = allow_reuse && !invariant_meta_pipelines.empty(); + if (collect_metrics && gstate.HasMaterializedInvariantPipelines()) { + for (auto &meta_pipeline : invariant_meta_pipelines) { + auto sink = meta_pipeline.get().GetSink(); + if (sink && sink->type == PhysicalOperatorType::CTE) { + gstate.GetMetrics().RecordRetainedCTEReuse(); + } + } } - } - // Establish a conservative per-sink worker bound before any sink state is mutated: several - // producer pipelines can share one sink, so the bound is the maximum over all of its producers. - // A producer's bound defaults to its epoch worker limit, where invariant meta pipelines keep the - // configured thread count because their source work is independent of the recursive frontier. - // Frontier and recurring-table contents are final for this iteration at this point, so a producer - // scanning them refines its bound to that scan's parallelism. Any other source, such as a - // materialized CTE that this iteration refills, stays at the epoch limit. - const auto configured_threads = TaskScheduler::GetScheduler(executor.context).NumberOfThreads(); - reference_map_t sink_worker_bounds; - for (auto &meta_pipeline : active_meta_pipelines) { - const auto is_invariant = invariant_meta_pipelines.find(*meta_pipeline) != invariant_meta_pipelines.end(); - const auto worker_limit = is_invariant ? configured_threads : parallelism.MaxWorkerCount(); - vector> pipelines; - meta_pipeline->GetPipelines(pipelines, false); - for (auto &pipeline : pipelines) { - auto sink = pipeline->GetSink(); + const auto scheduler_input_rows = GetRecursiveInputRows(gstate); + const auto direct_probe_work_units = recursive_references.direct_probe_work_units; + const auto row_limit = MaxValue(GetRecursiveRowLimit(scheduler_input_rows), direct_probe_work_units); + idx_t work_units = 1; + RecursiveCTEParallelism parallelism(1); + if (row_limit > 1) { + work_units = GetRecursiveWorkUnits(gstate, direct_probe_work_units); + if (work_units > 1) { + parallelism = GetRecursiveParallelism(gstate, work_units, row_limit, *schedule_plan); + } + } + + // Establish a conservative per-sink worker bound before any sink state is mutated: several + // producer pipelines can share one sink, so the bound is the maximum over all of its producers. + // A producer's bound defaults to its epoch worker limit, where invariant meta pipelines keep the + // configured thread count because their source work is independent of the recursive frontier. + // Frontier and recurring-table contents are final for this iteration at this point, so a producer + // scanning them refines its bound to that scan's parallelism. Any other source, such as a + // materialized CTE that this iteration refills, stays at the epoch limit. + const auto configured_threads = TaskScheduler::GetScheduler(executor.context).NumberOfThreads(); + reference_map_t sink_worker_bounds; + for (auto &entry : schedule_plan->pipelines) { + auto &pipeline = entry.pipeline.get(); + auto sink = pipeline.GetSink(); if (sink.get() != this) { + const auto worker_limit = entry.is_invariant ? configured_threads : parallelism.MaxWorkerCount(); auto &sink_bound = sink_worker_bounds[*sink]; sink_bound.worker_bound = - MaxValue(sink_bound.worker_bound, GetRecursiveProducerWorkerBound(*pipeline, worker_limit)); + MaxValue(sink_bound.worker_bound, GetRecursiveProducerWorkerBound(pipeline, worker_limit)); sink_bound.producer_count++; } } - } - // Reset sink state from the main thread so recursive iterations can reuse or recreate - // pipeline-local global sinks without tearing down the rest of the runtime state graph. A sink - // with a single producer additionally learns the exact worker count at schedule time. - for (auto &meta_pipeline : active_meta_pipelines) { - vector> pipelines; - meta_pipeline->GetPipelines(pipelines, false); - for (auto &pipeline : pipelines) { - auto sink = pipeline->GetSink(); + // Reset sink state from the main thread so recursive iterations can reuse or recreate + // pipeline-local global sinks without tearing down the rest of the runtime state graph. A sink + // with a single producer additionally learns the exact worker count at schedule time. + for (auto &entry : schedule_plan->pipelines) { + auto &pipeline = entry.pipeline.get(); + auto sink = pipeline.GetSink(); if (sink.get() != this) { auto &sink_bound = sink_worker_bounds[*sink]; if (sink_bound.reset_done) { @@ -1010,101 +1006,112 @@ void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) continue; } sink_bound.reset_done = true; - pipeline->ResetSinkForReschedule(sink_bound.worker_bound, sink_bound.producer_count == 1); + pipeline.ResetSinkForReschedule(sink_bound.worker_bound, sink_bound.producer_count == 1); } } - } - // Invalidate global operator state from the main thread while nothing executes: reusable - // state is reset in place, everything else is destroyed. Both recursive schedules recreate - // missing state through the ordinary create-if-absent initialization once a pipeline's - // dependencies have finished, because state construction may consume dependency-produced - // sink state. The plan's deduplicated list visits each shared operator exactly once. - for (auto &op_ref : schedule_plan->invalidate_operators) { - Pipeline::InvalidateOperatorStateForReschedule(context.client, op_ref.get()); - } + // Invalidate global operator state from the main thread while nothing executes: reusable + // state is reset in place, everything else is destroyed. Both recursive schedules recreate + // missing state through the ordinary create-if-absent initialization once a pipeline's + // dependencies have finished, because state construction may consume dependency-produced + // sink state. The plan's deduplicated list visits each shared operator exactly once. + for (auto &op_ref : schedule_plan->invalidate_operators) { + Pipeline::InvalidateOperatorStateForReschedule(context.client, op_ref.get()); + } - ConfigureInvariantRecursiveBuildReuse(*this, can_cache_invariant_meta_pipelines); + ConfigureInvariantRecursiveBuildReuse(*this, can_cache_invariant_meta_pipelines); - if (!allow_reuse) { - gstate.GetScheduler().ClearExecutors(); - } + if (!allow_reuse) { + gstate.GetScheduler().ClearExecutors(); + } - const auto prepare_cached_executor_entries = !allow_reuse || !gstate.GetScheduler().HasExecutorEntries(); + const auto prepare_cached_executor_entries = !allow_reuse || !gstate.GetScheduler().HasExecutorEntries(); - // Materialize every state-local cache entry before events can run concurrently. Individual - // pipelines grow their stable executor vector after their source state has been reset. Reusable - // entries only need to be registered once for each recursive state. - if (prepare_cached_executor_entries) { - reference_set_t prepared_pipelines; - for (auto &meta_pipeline : active_meta_pipelines) { - vector> pipelines; - meta_pipeline->GetPipelines(pipelines, false); - for (auto &pipeline : pipelines) { - if (prepared_pipelines.insert(*pipeline).second) { - gstate.GetScheduler().PrepareExecutorEntry(*pipeline); + // Materialize every state-local cache entry before events can run concurrently. Individual + // pipelines grow their stable executor vector after their source state has been reset. Reusable + // entries only need to be registered once for each recursive state. + if (prepare_cached_executor_entries) { + reference_set_t prepared_pipelines; + for (auto &entry : schedule_plan->pipelines) { + if (prepared_pipelines.insert(entry.pipeline.get()).second) { + gstate.GetScheduler().PrepareExecutorEntry(entry.pipeline.get()); } } } - } - idx_t frontier_rows = 0; - idx_t frontier_chunks = 0; - idx_t frontier_storage_bytes = 0; - idx_t frontier_allocation_bytes = 0; - idx_t epoch_task_start = 0; - if (collect_metrics) { - const auto &frontier = static_cast(gstate).CurrentInputTable(); - frontier_rows = frontier.Count(); - frontier_chunks = frontier.ChunkCount(); - frontier_storage_bytes = frontier.SizeInBytes(); - frontier_allocation_bytes = frontier.AllocationSize(); - epoch_task_start = gstate.GetMetrics().TaskCount(); - } - if (!UsingKey() && UnionAll()) { - auto &union_state = gstate.Cast(); - const auto source_tasks_write_recursive_output = parallelism.frontier_worker_count == 1 && - parallelism.source_task_worker_count > 1 && - schedule_plan->source_tasks_write_recursive_output; - // Materialized fan-out already provides pipeline concurrency; private output multiplies collections per scan. - const auto has_materialized_fanout = schedule_plan->cte_scan_pipeline_count > 1; - union_state.SetUseLocalUnionAllOutput(source_tasks_write_recursive_output || - (parallelism.frontier_worker_count > 1 && !has_materialized_fanout && - work_units / parallelism.frontier_worker_count >= 2)); - if (!union_state.UsesLocalUnionAllOutput()) { - union_state.InitializeSharedOutputAppend(); - } - } - const auto max_worker_count = parallelism.MaxWorkerCount(); - if (max_worker_count > 1 && !UsingKey() && !UnionAll()) { - const auto partition_count = MinValue(NextPowerOfTwo(max_worker_count), 4); - gstate.Cast().PromoteDistinctState(context.client, partition_count); - } - const auto epoch_start = - collect_metrics ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point(); - auto inline_execution = allow_reuse && parallelism.IsInline(); - - if (inline_execution) { if (collect_metrics) { - ExecuteRecursiveInlinePlan(gstate, executor, *schedule_plan); + const auto &frontier = static_cast(gstate).CurrentInputTable(); + progress.frontier_rows = frontier.Count(); + progress.frontier_chunks = frontier.ChunkCount(); + progress.frontier_storage_bytes = frontier.SizeInBytes(); + progress.frontier_allocation_bytes = frontier.AllocationSize(); + progress.epoch_task_start = gstate.GetMetrics().TaskCount(); + } + if (!UsingKey() && UnionAll()) { + auto &union_state = gstate.Cast(); + const auto source_tasks_write_recursive_output = parallelism.frontier_worker_count == 1 && + parallelism.source_task_worker_count > 1 && + schedule_plan->source_tasks_write_recursive_output; + // Materialized fan-out already provides pipeline concurrency; private output multiplies collections per + // scan. + const auto has_materialized_fanout = schedule_plan->cte_scan_pipeline_count > 1; + union_state.SetUseLocalUnionAllOutput(source_tasks_write_recursive_output || + (parallelism.frontier_worker_count > 1 && !has_materialized_fanout && + work_units / parallelism.frontier_worker_count >= 2)); + if (!union_state.UsesLocalUnionAllOutput()) { + union_state.InitializeSharedOutputAppend(); + } + } + progress.max_worker_count = parallelism.MaxWorkerCount(); + if (progress.max_worker_count > 1 && !UsingKey() && !UnionAll()) { + const auto partition_count = MinValue(NextPowerOfTwo(progress.max_worker_count), 4); + gstate.Cast().PromoteDistinctState(context.client, partition_count); + } + progress.scheduler_input_rows = scheduler_input_rows; + progress.epoch_start = + collect_metrics ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point(); + progress.inline_execution = allow_reuse && parallelism.IsInline(); + progress.active = true; + + if (progress.inline_execution) { + for (auto &pipeline : schedule_plan->initialize_on_schedule_pipelines) { + pipeline.get().ResetSource(true); + } + gstate.GetScheduler().InitializeInlinePlan(*schedule_plan); } else { - ExecuteRecursiveInlinePlan(gstate, executor, *schedule_plan); + // The wake event is a parent of every scheduled event and fires the source's interrupt + // callback once the whole schedule has finished. + auto wake = make_shared_ptr(executor, interrupt_state); + ScheduleRecursivePlan(*schedule_plan, gstate, progress.events, parallelism, *wake); + progress.wake_event = std::move(wake); } + } else if (executor.HasError()) { + // resumed while the executor is failing: surface the error instead of driving the epoch + executor.ThrowException(); + } + + bool complete; + if (progress.inline_execution) { + complete = collect_metrics ? DriveRecursiveInlinePlan(gstate, executor, *schedule_plan, interrupt_state) + : DriveRecursiveInlinePlan(gstate, executor, *schedule_plan, interrupt_state); } else { - vector> events; - ScheduleRecursivePlan(*schedule_plan, gstate, events, parallelism); - WaitForRecursiveEvents(executor, events); + complete = !progress.wake_event->Cast().Arm(); + } + if (!complete) { + return RecursiveEpochResult::BLOCKED; } + // Epoch epilogue if (collect_metrics) { const auto epoch_end = std::chrono::steady_clock::now(); - const auto elapsed_us = - NumericCast(std::chrono::duration_cast(epoch_end - epoch_start).count()); - gstate.GetMetrics().RecordEpoch(max_worker_count, elapsed_us, frontier_rows, frontier_chunks, - scheduler_input_rows); - const auto epoch_tasks = gstate.GetMetrics().TaskCount() - epoch_task_start; - gstate.GetEpochMetrics().Record(frontier_rows, max_worker_count, epoch_tasks, elapsed_us, - frontier_storage_bytes, frontier_allocation_bytes); - } + const auto elapsed_us = NumericCast( + std::chrono::duration_cast(epoch_end - progress.epoch_start).count()); + gstate.GetMetrics().RecordEpoch(progress.max_worker_count, elapsed_us, progress.frontier_rows, + progress.frontier_chunks, progress.scheduler_input_rows); + const auto epoch_tasks = gstate.GetMetrics().TaskCount() - progress.epoch_task_start; + gstate.GetEpochMetrics().Record(progress.frontier_rows, progress.max_worker_count, epoch_tasks, elapsed_us, + progress.frontier_storage_bytes, progress.frontier_allocation_bytes); + } + const auto can_cache_invariant_meta_pipelines = gstate.AllowsExecutorReuse() && !invariant_meta_pipelines.empty(); if (can_cache_invariant_meta_pipelines && InvariantRecursiveBuildsRemainReusable(*this)) { if (collect_metrics && !gstate.HasMaterializedInvariantPipelines()) { for (auto &meta_pipeline : invariant_meta_pipelines) { @@ -1118,6 +1125,8 @@ void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) } gstate.MarkInvariantPipelinesMaterialized(); } + progress.Reset(); + return RecursiveEpochResult::COMPLETE; } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp index 3fe0427d9..822a82f81 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/bit_utils.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/parallel/event.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/parallel/pipeline_executor.hpp" @@ -217,7 +218,7 @@ void RecursiveCTEEpochMetrics::RecordPipelineExecution(RecursiveCTEPipelineMetri } RecursiveCTEMetrics::RecursiveCTEMetrics(ClientContext &context, const PhysicalRecursiveCTE &op_p) - : logger(context.logger), + : logger(context.GetContext().GetLoggerPtr()), enabled(logger && logger->ShouldLog(PhysicalOperatorLogType::NAME, PhysicalOperatorLogType::LEVEL)) { if (enabled) { identity = make_uniq(op_p.type, op_p.NextMetricsInvocation()); @@ -409,6 +410,16 @@ void RecursiveCTEMetrics::LogEpochSummary(const RecursiveCTEEpochMetrics &epoch_ to_string(epoch_metrics.invariant_cte_materialization_execute_work_ns.load())}}); } +RecursiveCTEEpochProgress::RecursiveCTEEpochProgress() { +} + +RecursiveCTEEpochProgress::~RecursiveCTEEpochProgress() { +} + +void RecursiveCTEEpochProgress::Reset() { + *this = RecursiveCTEEpochProgress(); +} + RecursiveCTESchedulerState::RecursiveCTESchedulerState(shared_ptr executor_pool_p, bool allow_executor_reuse_p) : executor_pool(std::move(executor_pool_p)), allow_executor_reuse(allow_executor_reuse_p) { diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp index 7b99d8628..676506c81 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp @@ -350,7 +350,8 @@ void RecursiveCTEUnionState::RebindRecursiveScans() { } SourceResultType RecursiveCTEUnionState::GetData(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source) { + RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state) { if (source_phase == RecursiveCTESourcePhase::INITIAL) { CurrentOutputTable().InitializeScan(scan_state); source.StartIteration(CurrentOutputTable().Count()); @@ -366,11 +367,11 @@ SourceResultType RecursiveCTEUnionState::GetData(ExecutionContext &context, Data } } else if (source_phase == RecursiveCTESourcePhase::FINISHED) { break; - } else { + } else if (source_phase != RecursiveCTESourcePhase::EXECUTING_RECURSION) { throw InternalException("Unsupported recursive CTE union source phase"); } - if (chunk.size() == 0) { + if (source_phase != RecursiveCTESourcePhase::EXECUTING_RECURSION) { // we have run out of chunks // now we need to recurse // we set up the working table as the data we gathered in this iteration of the recursion @@ -413,20 +414,26 @@ SourceResultType RecursiveCTEUnionState::GetData(ExecutionContext &context, Data } } - // now we need to re-execute all of the pipelines that depend on the recursion - op.ExecuteRecursivePipelines(context); + source_phase = RecursiveCTESourcePhase::EXECUTING_RECURSION; + } - // check if we obtained any results - // if not, we are done - if (CurrentOutputTable().Count() == 0) { - source_phase = RecursiveCTESourcePhase::FINISHED; - source.Finish(); - break; - } - // set up the scan again - CurrentOutputTable().InitializeScan(scan_state); - source.StartIteration(CurrentOutputTable().Count()); + // now we need to re-execute all of the pipelines that depend on the recursion + if (op.ExecuteRecursivePipelines(context, interrupt_state) == RecursiveEpochResult::BLOCKED) { + // the epoch waits for blocked inner work; the interrupt state re-enters this source + return SourceResultType::BLOCKED; } + + // check if we obtained any results + // if not, we are done + if (CurrentOutputTable().Count() == 0) { + source_phase = RecursiveCTESourcePhase::FINISHED; + source.Finish(); + break; + } + // set up the scan again + source_phase = RecursiveCTESourcePhase::SCANNING_UNION; + CurrentOutputTable().InitializeScan(scan_state); + source.StartIteration(CurrentOutputTable().Count()); } return chunk.size() == 0 ? SourceResultType::FINISHED : SourceResultType::HAVE_MORE_OUTPUT; diff --git a/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp b/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp index 1725409fe..e309220c5 100644 --- a/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp +++ b/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp @@ -146,6 +146,8 @@ void PerfectAggregateHashTable::AddChunk(DataChunk &groups, DataChunk &payload) ComputeGroupLocation(groups.data[i], group_minima[i], address_data, current_shift); } + // evaluate every aggregate filter once for this chunk + filter_set.ApplyFilters(payload); if (AddChunkClustered(address_data, payload)) { return; } @@ -165,7 +167,7 @@ void PerfectAggregateHashTable::AddChunk(DataChunk &groups, DataChunk &payload) auto &aggregate = aggregates[aggr_idx]; if (aggregate.filter) { RowOperations::UpdateFilteredStates(row_state, filter_set.GetFilterData(aggr_idx), aggregate, addresses, - payload, payload_idx); + payload_idx); } else { RowOperations::UpdateStates(row_state, aggregate, addresses, payload, payload_idx); } diff --git a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp index 2a127920d..ec2b3cf1a 100644 --- a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp @@ -10,7 +10,9 @@ #include "duckdb/execution/physical_plan_generator.hpp" #include "duckdb/function/function_binder.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" namespace duckdb { @@ -250,7 +252,9 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalAggregate &op) { D_ASSERT(op.children.size() == 1); reference plan = CreatePlan(*op.children[0]); - plan = ExtractAggregateExpressions(plan, op.expressions, op.groups, op.grouping_sets); + // the ungrouped aggregate evaluates its filters directly; grouped aggregates need them as payload columns + const bool ungrouped = op.groups.empty() && op.grouping_sets.size() <= 1; + plan = ExtractAggregateExpressions(plan, op.expressions, op.groups, op.grouping_sets, !ungrouped); bool can_use_simple_aggregation = true; for (auto &expression : op.expressions) { @@ -313,7 +317,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalAggregate &op) { PhysicalOperator &PhysicalPlanGenerator::ExtractAggregateExpressions(PhysicalOperator &child, vector> &aggregates, vector> &groups, - optional_ptr> grouping_sets) { + optional_ptr> grouping_sets, + bool extract_filters) { vector> expressions; vector types; @@ -331,20 +336,41 @@ PhysicalOperator &PhysicalPlanGenerator::ExtractAggregateExpressions(PhysicalOpe expressions.push_back(std::move(group)); group = std::move(ref); } + // children and filters that several aggregates share are projected (and later evaluated) once + // distinct aggregates keep their own columns: their distinct hash tables are keyed on them + expression_map_t shared_columns; + auto extract = [&](unique_ptr &expr, bool share) { + auto type = expr->GetReturnType(); + share = share && !expr->IsVolatile(); + auto entry = share ? shared_columns.find(*expr) : shared_columns.end(); + idx_t index; + if (entry != shared_columns.end()) { + index = entry->second; + } else { + index = expressions.size(); + types.push_back(type); + expressions.push_back(std::move(expr)); + if (share) { + shared_columns.emplace(*expressions[index], index); + } + } + expr = make_uniq(type, index); + }; for (auto &aggr : aggregates) { auto &bound_aggr = aggr->Cast(); for (auto &child_expr : bound_aggr.GetChildrenMutable()) { - auto ref = make_uniq(child_expr->GetReturnType(), expressions.size()); - types.push_back(child_expr->GetReturnType()); - expressions.push_back(std::move(child_expr)); - child_expr = std::move(ref); + extract(child_expr, !bound_aggr.IsDistinct()); } if (bound_aggr.GetFilter()) { auto &filter = bound_aggr.GetFilterMutable(); - auto ref = make_uniq(filter->GetReturnType(), expressions.size()); - types.push_back(filter->GetReturnType()); - expressions.push_back(std::move(filter)); - bound_aggr.GetFilterMutable() = std::move(ref); + // volatile filters stay in the projection: evaluated per aggregate, and in order for nextval + if (extract_filters || filter->IsVolatile()) { + extract(filter, true); + } else { + // the filter stays with the aggregate: only the columns it reads are projected + ExpressionIterator::VisitExpressionMutable( + filter, [&](BoundReferenceExpression &, unique_ptr &ref) { extract(ref, true); }); + } } } if (expressions.empty()) { 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 f4a017a2e..cf932a23e 100644 --- a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp @@ -333,6 +333,16 @@ static idx_t ValidateAsOfConditions(LogicalComparisonJoin &op, vector &eq } PhysicalOperator &PhysicalPlanGenerator::PlanAsOfJoin(LogicalComparisonJoin &op) { +#ifdef D_ASSERT_IS_ENABLED + // The sorted ASOF operator emits the full left payload in child order (see column_lifetime_analyzer.cpp), + // so the only supported left projection maps are empty or full-width identity. + if (op.join_type != JoinType::MARK && !op.left_projection_map.empty()) { + D_ASSERT(op.left_projection_map.size() == op.children[0]->GetColumnBindings().size()); + for (idx_t i = 0; i < op.left_projection_map.size(); i++) { + D_ASSERT(op.left_projection_map[i].GetIndex() == i); + } + } +#endif // If we have a predicate and its a "simple" join, then we can just plan a regular join switch (op.join_type) { case JoinType::SEMI: diff --git a/src/duckdb/src/execution/physical_plan/plan_create_table.cpp b/src/duckdb/src/execution/physical_plan/plan_create_table.cpp index 94350b014..28cb05cba 100644 --- a/src/duckdb/src/execution/physical_plan/plan_create_table.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_create_table.cpp @@ -38,8 +38,9 @@ PhysicalOperator &DuckCatalog::PlanCreateTableAs(ClientContext &context, Physica PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCreateTable &op) { const auto &create_info = op.info->base->Cast(); auto &catalog = op.info->schema.catalog; - auto existing_entry = catalog.GetEntry(context, CatalogType::TABLE_ENTRY, create_info.GetQualifiedName().Schema(), - create_info.GetTableName(), OnEntryNotFound::RETURN_NULL); + // probe the bound schema entry directly: re-resolving by name can hit a sibling schema with the same leaf name + auto existing_entry = op.info->schema.GetEntry(catalog.GetCatalogTransaction(context), CatalogType::TABLE_ENTRY, + create_info.GetTableName()); bool replace = op.info->Base().on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT; if ((!existing_entry || replace) && !op.children.empty()) { auto &plan = CreatePlan(*op.children[0]); diff --git a/src/duckdb/src/execution/physical_plan/plan_get.cpp b/src/duckdb/src/execution/physical_plan/plan_get.cpp index f92d095dd..7798cef8f 100644 --- a/src/duckdb/src/execution/physical_plan/plan_get.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_get.cpp @@ -82,16 +82,28 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalGet &op) { auto column_idx = projection_indices.empty() ? output_idx : projection_indices[output_idx]; if (column_ids[column_idx].GetPrimaryIndex() == op.ordinality_idx.GetIndex()) { ordinality_idx = output_idx; + // the operator produces the ordinality column, not the function: + // present the position as an empty column so strict functions do not reject it + column_ids[column_idx] = ColumnIndex(COLUMN_IDENTIFIER_EMPTY); break; } } } + bool table_input = false; + const auto &signature = op.function.GetSignature(); + for (idx_t i = 0; i < signature.GetPositionalParameterCount(); i++) { + if (signature.GetParameter(i).GetType().id() == LogicalTypeId::TABLE) { + table_input = true; + break; + } + } auto &table_in_out = Make( op.types, op.function, std::move(op.bind_data), column_ids, std::move(projection_indices), std::move(table_filters), op.estimated_cardinality, std::move(op.projected_input)); table_in_out.children.push_back(child); auto &cast_table_in_out = table_in_out.Cast(); cast_table_in_out.ordinality_idx = ordinality_idx; + cast_table_in_out.table_input = table_input; return table_in_out; } diff --git a/src/duckdb/src/execution/physical_plan/plan_sample.cpp b/src/duckdb/src/execution/physical_plan/plan_sample.cpp index 76dc21951..4b48c7214 100644 --- a/src/duckdb/src/execution/physical_plan/plan_sample.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_sample.cpp @@ -27,7 +27,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSample &op) { auto &plan = CreatePlan(*op.children[0]); if (!op.sample_options->seed.IsValid()) { auto &random_engine = RandomEngine::Get(context); - op.sample_options->SetSeed(random_engine.NextRandomInteger()); + op.sample_options->SetSeed(random_engine.NextSeed32()); } switch (op.sample_options->method) { diff --git a/src/duckdb/src/execution/radix_ht_adaptivity.cpp b/src/duckdb/src/execution/radix_ht_adaptivity.cpp index 4200c0285..af99abfeb 100644 --- a/src/duckdb/src/execution/radix_ht_adaptivity.cpp +++ b/src/duckdb/src/execution/radix_ht_adaptivity.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/execution/radix_ht_sink_state.hpp" +#include "duckdb/main/client_context.hpp" namespace duckdb { @@ -49,7 +50,7 @@ bool RadixHTAdaptivity::TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSink auto &memory_state = *gstate.temporary_memory_state; const auto request = desired_size * gstate.number_of_threads; const auto doubled_request = request <= NumericLimits::Maximum() / 2 ? request * 2 : request; - memory_state.SetRemainingSizeAndUpdateReservation(gstate.context, + memory_state.SetRemainingSizeAndUpdateReservation(gstate.context.GetContext(), MaxValue(memory_state.GetRemainingSize(), doubled_request)); } const auto thread_limit = gstate.GetThreadLimit(); diff --git a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp index 25e340b59..671dd0c1c 100644 --- a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp +++ b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp @@ -16,6 +16,7 @@ #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" +#include "duckdb/main/client_context.hpp" namespace duckdb { @@ -124,7 +125,8 @@ struct AggregatePartition : StateWithBlockableTasks { }; RadixHTGlobalSinkState::RadixHTGlobalSinkState(ClientContext &context_p, const RadixPartitionedHashTable &radix_ht_p) - : context(context_p), temporary_memory_state(TemporaryMemoryManager::Get(context).Register(context)), + : context(context_p), + temporary_memory_state(TemporaryMemoryManager::Get(context.GetContext()).Register(context.GetContext())), finalized(false), external(false), iteration_reused(false), active_threads(0), number_of_threads(TaskScheduler::GetScheduler(context).NumberOfThreads()), memory_limit(BufferManager::GetBufferManager(context).GetOperatorMemoryLimit()), @@ -132,7 +134,7 @@ RadixHTGlobalSinkState::RadixHTGlobalSinkState(ClientContext &context_p, const R any_abandoned(false), radix_ht(radix_ht_p), spill_plan(AggregateStateSpilling::TryCreateSpillPlan(radix_ht.GetLayout())), config(*this), stored_allocators_size(0), finalize_done(0), scan_pin_properties(TupleDataPinProperties::DESTROY_AFTER_DONE), - count_before_combining(0), max_partition_size(0) { + count_before_combining(0), size_before_combining(0), max_partition_size(0) { spill_phase = SpillPhase::NATIVE_ALLOWED; SetReservationFloor(context, MaxValue(config.GetRadixBits(), config.GetMaximumSinkRadixBits())); @@ -141,7 +143,7 @@ RadixHTGlobalSinkState::RadixHTGlobalSinkState(ClientContext &context_p, const R void RadixHTGlobalSinkState::SetReservationFloor(ClientContext &context_p, const idx_t radix_bits) { minimum_reservation = CalculateMinimumReservation(radix_bits); temporary_memory_state->SetMinimumReservation(minimum_reservation); - temporary_memory_state->SetRemainingSizeAndUpdateReservation(context_p, minimum_reservation); + temporary_memory_state->SetRemainingSizeAndUpdateReservation(context_p.GetContext(), minimum_reservation); } void RadixHTGlobalSinkState::ResetConfigForNewIteration(ClientContext &context_p, const idx_t scheduled_workers) { @@ -399,6 +401,7 @@ void RadixPartitionedHashTable::ResetGlobalSinkState(ClientContext &context, Glo gstate.finalize_done = 0; gstate.scan_pin_properties = TupleDataPinProperties::DESTROY_AFTER_DONE; gstate.count_before_combining = 0; + gstate.size_before_combining = 0; gstate.max_partition_size = 0; } @@ -610,7 +613,7 @@ void UpdateSinkReservation(ClientContext &context, RadixHTGlobalSinkState &gstat // Grow from current demand, not the previous request, which might not have been granted. const auto remaining_size = MaxValue(2 * gstate.number_of_threads * required_size, temporary_memory_state.GetRemainingSize()); - temporary_memory_state.SetRemainingSizeAndUpdateReservation(context, remaining_size); + temporary_memory_state.SetRemainingSizeAndUpdateReservation(context.GetContext(), remaining_size); } void MaybeRepartition(ClientContext &context, RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate, @@ -847,6 +850,7 @@ void RadixPartitionedHashTable::Finalize(ClientContext &context, GlobalSinkState const annotated_lock_guard guard {gstate.lock}; D_ASSERT(!gstate.finalized); + gstate.size_before_combining = 0; if (!gstate.uncombined_exported_data.empty() && (!gstate.uncombined_data || gstate.uncombined_exported_data.size() != gstate.uncombined_data->PartitionCount())) { @@ -866,6 +870,7 @@ void RadixPartitionedHashTable::Finalize(ClientContext &context, GlobalSinkState partition.exported_data = std::move(gstate.uncombined_exported_data[i]); if (partition.exported_data) { gstate.count_before_combining += partition.exported_data->Count(); + gstate.size_before_combining += partition.exported_data->SizeInBytes(); gstate.max_partition_size = MaxValue(gstate.max_partition_size, RadixHTConfig::EXPORTED_STATE_MEMORY_MULTIPLIER * partition.exported_data->SizeInBytes()); @@ -886,6 +891,7 @@ void RadixPartitionedHashTable::Finalize(ClientContext &context, GlobalSinkState gstate.partitions.reserve(n_partitions); for (idx_t i = 0; i < n_partitions; i++) { auto &partition = uncombined_partition_data[i]; + gstate.size_before_combining += partition->SizeInBytes(); auto partition_size = partition->SizeInBytes() + GroupedAggregateHashTable::GetCapacityForCount(partition->Count()) * sizeof(ht_entry_t); @@ -896,6 +902,7 @@ void RadixPartitionedHashTable::Finalize(ClientContext &context, GlobalSinkState gstate.partitions.back()->exported_data = std::move(gstate.uncombined_exported_data[i]); if (gstate.partitions.back()->exported_data) { gstate.count_before_combining += gstate.partitions.back()->exported_data->Count(); + gstate.size_before_combining += gstate.partitions.back()->exported_data->SizeInBytes(); partition_size += RadixHTConfig::EXPORTED_STATE_MEMORY_MULTIPLIER * gstate.partitions.back()->exported_data->SizeInBytes(); } @@ -927,10 +934,14 @@ idx_t RadixPartitionedHashTable::MaxThreads(GlobalSinkState &sink_p) const { return 0; } + // Small aggregates are not worth parallelizing: limit the threads by the amount of data to combine and scan + const auto data_size = sink.size_before_combining + sink.stored_allocators_size; + const auto threads_for_size = MaxValue(data_size / RadixHTConfig::MINIMUM_SOURCE_BYTES_PER_THREAD, 1); const auto max_threads = - MinValue(TaskScheduler::GetScheduler(sink.context).NumberOfThreads(), sink.partitions.size()); + MinValue(MinValue(TaskScheduler::GetScheduler(sink.context).NumberOfThreads(), threads_for_size), + sink.partitions.size()); sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation( - sink.context, sink.stored_allocators_size + max_threads * sink.max_partition_size); + sink.context.GetContext(), sink.stored_allocators_size + max_threads * sink.max_partition_size); // we cannot spill aggregate state memory const auto usable_memory = sink.temporary_memory_state->GetReservation() > sink.stored_allocators_size diff --git a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp index 2d53e44be..eda2ea5ae 100644 --- a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp +++ b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp @@ -136,8 +136,8 @@ static unique_ptr BindDecimalAverage(BindAggregateFunctionInput &i input_type.ToString()); } - uint8_t width = DecimalType::GetWidth(input_type); - uint8_t scale = DecimalType::GetScale(input_type); + uint32_t width = DecimalType::GetWidth(input_type); + uint32_t scale = DecimalType::GetScale(input_type); auto return_type = LogicalType::DECIMAL(width, scale); auto name = function.GetName(); 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 c6e16c6bc..48f9a0c67 100644 --- a/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp +++ b/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp @@ -298,24 +298,18 @@ struct FirstVectorFunction : FirstFunctionStringBase { static void Update(Vector inputs[], AggregateInputData &input_data, idx_t, Vector &state_vector, idx_t count) { auto &input = inputs[0]; - UnifiedVectorFormat idata; - input.ToUnifiedFormat(idata); UnifiedVectorFormat sdata; state_vector.ToUnifiedFormat(sdata); + auto states = UnifiedVectorFormat::GetData(sdata); + // Gather the rows that can still be assigned before touching the input: reading the values can be expensive + // (a shredded VARIANT has to be materialized), while in a grouped aggregate the states are typically set + // after the first few chunks, leaving nothing to do. sel_t assign_sel[STANDARD_VECTOR_SIZE]; idx_t assign_count = 0; - - auto states = UnifiedVectorFormat::GetData(sdata); for (idx_t i = 0; i < count; i++) { - const auto idx = idata.sel->get_index(i); - bool is_null = !idata.validity.RowIsValid(idx); - if (SKIP_NULLS && is_null) { - continue; - } - auto &state = *states[sdata.sel->get_index(i)]; - if (!LAST && state.is_set) { + if (!LAST && states[sdata.sel->get_index(i)]->is_set) { continue; } assign_sel[assign_count++] = NumericCast(i); @@ -325,6 +319,9 @@ struct FirstVectorFunction : FirstFunctionStringBase { return; } + UnifiedVectorFormat idata; + input.ToUnifiedFormat(idata); + Vector sort_key(LogicalType::BLOB); OrderModifiers modifiers(OrderType::ASCENDING, OrderByNullType::NULLS_LAST); // slice with a selection vector and generate sort keys @@ -339,14 +336,18 @@ struct FirstVectorFunction : FirstFunctionStringBase { // now assign sort keys for (idx_t i = 0; i < assign_count; i++) { + const auto idx = idata.sel->get_index(assign_sel[i]); + bool is_null = !idata.validity.RowIsValid(idx); + if (SKIP_NULLS && is_null) { + continue; + } + const auto state_idx = sdata.sel->get_index(assign_sel[i]); auto &state = *states[state_idx]; if (!LAST && state.is_set) { continue; } - const auto idx = idata.sel->get_index(assign_sel[i]); - bool is_null = !idata.validity.RowIsValid(idx); FirstFunctionStringBase::template SetValue(state, input_data, sort_key_data[i], is_null); } diff --git a/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp b/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp index fae02eaf8..1cbeec6ed 100644 --- a/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp @@ -547,9 +547,14 @@ struct SortedAggregateFunction { const idx_t offset) { // Internally we can only handle 2^16 rows, so chunk them up const idx_t group_limit = NumericLimits::Maximum(); - for (auto group_offset = offset; group_offset < count; group_offset += group_limit) { + if (count <= group_limit) { + FinalizeGroups(states, finalize_input_data, result, count, offset); + return; + } + for (idx_t group_offset = 0; group_offset < count; group_offset += group_limit) { const auto group_count = MinValue(group_limit, count - group_offset); - FinalizeGroups(states, finalize_input_data, result, group_count, group_offset); + Vector group_states(states, group_offset, group_offset + group_count); + FinalizeGroups(group_states, finalize_input_data, result, group_count, offset + group_offset); } } }; diff --git a/src/duckdb/src/function/cast/bignum_casts.cpp b/src/duckdb/src/function/cast/bignum_casts.cpp index a222595e3..db75f6eee 100644 --- a/src/duckdb/src/function/cast/bignum_casts.cpp +++ b/src/duckdb/src/function/cast/bignum_casts.cpp @@ -195,6 +195,8 @@ static bool DoubleToBignum(T double_value, bignum_t &result_value, Vector &resul // We can't cast inf -inf nan return false; } + // Round half to even like the casts to BIGINT and HUGEINT; the byte loop below is only exact for whole numbers. + double_value = std::nearbyint(double_value); // Determine if the number is negative bool is_negative = double_value < 0; // Determine the number of data bytes diff --git a/src/duckdb/src/function/cast/cast_statistics.cpp b/src/duckdb/src/function/cast/cast_statistics.cpp index 2a3988a90..ec7efedcb 100644 --- a/src/duckdb/src/function/cast/cast_statistics.cpp +++ b/src/duckdb/src/function/cast/cast_statistics.cpp @@ -224,6 +224,8 @@ static unique_ptr StatisticsPropagateArrayToList(const BaseStati auto result = ListStats::CreateEmpty(target); result.CopyBase(input); + auto array_size = ArrayType::GetSize(source); + ListStats::SetLengthBounds(result, array_size, array_size); ListStats::GetChildStats(result).Copy(ArrayStats::GetChildStats(input)); return result.ToUnique(); } diff --git a/src/duckdb/src/function/cast/decimal_cast.cpp b/src/duckdb/src/function/cast/decimal_cast.cpp index 01c98db67..3ca21796c 100644 --- a/src/duckdb/src/function/cast/decimal_cast.cpp +++ b/src/duckdb/src/function/cast/decimal_cast.cpp @@ -37,7 +37,7 @@ struct DecimalScaleInput { : result(result_p), vector_cast_data(result, parameters), factor(factor_p) { } DecimalScaleInput(Vector &result_p, LIMIT_TYPE limit_p, FACTOR_TYPE factor_p, CastParameters ¶meters, - uint8_t source_width_p, uint8_t source_scale_p) + uint32_t source_width_p, uint32_t source_scale_p) : result(result_p), vector_cast_data(result, parameters), limit(limit_p), factor(factor_p), source_width(source_width_p), source_scale(source_scale_p) { } @@ -46,8 +46,8 @@ struct DecimalScaleInput { VectorTryCastData vector_cast_data; LIMIT_TYPE limit; FACTOR_TYPE factor; - uint8_t source_width; - uint8_t source_scale; + uint32_t source_width; + uint32_t source_scale; }; struct DecimalScaleUpOperator { @@ -226,13 +226,13 @@ static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count } struct DecimalStringCastInput { - DecimalStringCastInput(Vector &result_p, uint8_t width_p, uint8_t scale_p) + DecimalStringCastInput(Vector &result_p, uint32_t width_p, uint32_t scale_p) : heap(StringVector::GetStringHeap(result_p)), width(width_p), scale(scale_p) { } StringHeap &heap; - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; }; struct StringCastFromDecimalOperator { diff --git a/src/duckdb/src/function/cast/time_casts.cpp b/src/duckdb/src/function/cast/time_casts.cpp index ffbf31cab..935cb30aa 100644 --- a/src/duckdb/src/function/cast/time_casts.cpp +++ b/src/duckdb/src/function/cast/time_casts.cpp @@ -185,6 +185,9 @@ BoundCastInfo DefaultCasts::TimestampTzNsCastSwitch(BindCastInput &input, const case LogicalTypeId::TIMESTAMP_TZ: // timestamp with time zone (ns) to timestamp with time zone (us) return BoundCastInfo(&VectorCastHelpers::TryCastLoop); + case LogicalTypeId::TIMESTAMP: + // timestamp with time zone (ns) to timestamp (us) + return BoundCastInfo(&VectorCastHelpers::TryCastLoop); case LogicalTypeId::TIMESTAMP_MS: // timestamp with time zone (ns) to timestamp (ms) return BoundCastInfo(&VectorCastHelpers::TryCastLoop); diff --git a/src/duckdb/src/function/cast/union/from_struct.cpp b/src/duckdb/src/function/cast/union/from_struct.cpp index fa748e326..717a2e1be 100644 --- a/src/duckdb/src/function/cast/union/from_struct.cpp +++ b/src/duckdb/src/function/cast/union/from_struct.cpp @@ -6,6 +6,7 @@ #include "duckdb/function/cast/bound_cast_data.hpp" #include "duckdb/common/exception/conversion_exception.hpp" #include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" namespace duckdb { @@ -80,8 +81,11 @@ bool StructToUnionCast::Cast(Vector &source, Vector &result, idx_t count, CastPa // the failing values have been set to NULL by the (TRY_CAST) member cast all_converted = false; } - // we flatten the child because we use FlatVector::SetNull below and we may get non-flat from source/cast - result_child_vector.Flatten(); + // copy the member into a flat vector we own - the member cast may reference the source, and we set NULLs below + Vector member(result_child_vector.GetType(), count); + VectorOperations::Copy(result_child_vector, member, count, 0, 0); + FlatVector::SetSize(member, count_t(count)); + result_child_vector.Reference(member); } if (source.GetVectorType() == VectorType::CONSTANT_VECTOR) { diff --git a/src/duckdb/src/function/cast/variant/from_variant.cpp b/src/duckdb/src/function/cast/variant/from_variant.cpp index ff6bc2c93..7e2ba37f8 100644 --- a/src/duckdb/src/function/cast/variant/from_variant.cpp +++ b/src/duckdb/src/function/cast/variant/from_variant.cpp @@ -788,8 +788,8 @@ static bool CastVariant(FromVariantConversionData &conversion_data, Vector &resu conversion_data, result, sel, offset, count, row, empty_payload); case LogicalTypeId::DECIMAL: { auto physical_type = target_type.InternalType(); - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; target_type.GetDecimalProperties(width, scale); DecimalConversionPayloadFromVariant decimal_payload(width, scale); diff --git a/src/duckdb/src/function/cast/variant/to_json.cpp b/src/duckdb/src/function/cast/variant/to_json.cpp index 3e47a0240..03be3de13 100644 --- a/src/duckdb/src/function/cast/variant/to_json.cpp +++ b/src/duckdb/src/function/cast/variant/to_json.cpp @@ -136,13 +136,13 @@ struct JSONConverterBase { static yyjson_mut_val *VisitDecimal(T val, uint32_t width, uint32_t scale, yyjson_mut_doc *doc) { string val_str; if constexpr (std::is_same_v) { - val_str = Decimal::ToString(val, static_cast(width), static_cast(scale)); + val_str = Decimal::ToString(val, width, scale); } else if constexpr (std::is_same_v) { - val_str = Decimal::ToString(val, static_cast(width), static_cast(scale)); + val_str = Decimal::ToString(val, width, scale); } else if constexpr (std::is_same_v) { - val_str = Decimal::ToString(val, static_cast(width), static_cast(scale)); + val_str = Decimal::ToString(val, width, scale); } else if constexpr (std::is_same_v) { - val_str = Decimal::ToString(val, static_cast(width), static_cast(scale)); + val_str = Decimal::ToString(val, width, scale); } else { throw InternalException("Unhandled decimal type"); } diff --git a/src/duckdb/src/function/combine_types_rules.cpp b/src/duckdb/src/function/combine_types_rules.cpp index 50f2d987f..2a6dfeeb7 100644 --- a/src/duckdb/src/function/combine_types_rules.cpp +++ b/src/duckdb/src/function/combine_types_rules.cpp @@ -141,14 +141,13 @@ static bool CombineEqualDecimal(LogicalTypeResolver &logical_type_resolver, cons // using the max of these of the two types gives us the new decimal size auto extra_width_left = DecimalType::GetWidth(left) - DecimalType::GetScale(left); auto extra_width_right = DecimalType::GetWidth(right) - DecimalType::GetScale(right); - auto extra_width = - MaxValue(NumericCast(extra_width_left), NumericCast(extra_width_right)); - auto scale = MaxValue(DecimalType::GetScale(left), DecimalType::GetScale(right)); - auto width = NumericCast(extra_width + scale); + auto extra_width = MaxValue(extra_width_left, extra_width_right); + auto scale = MaxValue(DecimalType::GetScale(left), DecimalType::GetScale(right)); + uint32_t width = extra_width + scale; if (width > DecimalType::MaxWidth()) { // if the resulting decimal does not fit, we truncate the scale width = DecimalType::MaxWidth(); - scale = NumericCast(width - extra_width); + scale = width - extra_width; } result = LogicalType::DECIMAL(width, scale); return true; diff --git a/src/duckdb/src/function/function_binder.cpp b/src/duckdb/src/function/function_binder.cpp index baa71a2fa..5dae97d37 100644 --- a/src/duckdb/src/function/function_binder.cpp +++ b/src/duckdb/src/function/function_binder.cpp @@ -6,6 +6,7 @@ #include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/window_function_catalog_entry.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/aggregate_function.hpp" @@ -15,6 +16,7 @@ #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/expression_binder.hpp" @@ -880,6 +882,44 @@ FunctionBinder::BindTableFunction(const TableFunctionSet &functions, std::move(named_parameters)); } +unique_ptr +FunctionBinder::BindTableInOutFunction(const TableFunctionSet &functions, const vector &input_types, + vector>> &named_arguments, + ErrorData &error) { + VerifyNamedArgumentsAccepted(functions, named_arguments); + vector> input_arguments; + for (idx_t i = 0; i < input_types.size(); i++) { + input_arguments.push_back(make_uniq(input_types[i], storage_t(i))); + } + auto selection = SelectFunction(context, functions, {input_arguments, named_arguments}); + if (!selection) { + error = selection.GetError(); + return nullptr; + } + auto &binding = selection.GetBinding(); + auto definition = binding.GetFunction(); + for (const auto &argument : named_arguments) { + auto parameter = definition->GetSignature().GetParameterIndexByName(argument.first); + if (parameter.IsValid() && definition->GetSignature().GetParameter(parameter.GetIndex()).AcceptsPosition()) { + throw BinderException("Table in-out function input columns must be passed positionally: %s", + argument.first); + } + } + auto resolved = ResolveArguments(*definition, binding, input_arguments, named_arguments); + // Input columns remain in the subquery; only named options are cast and folded here. + const auto positional_count = + NumericCast>::difference_type>(resolved.positional_count); + resolved.arguments.erase(resolved.arguments.begin(), resolved.arguments.begin() + positional_count); + resolved.types.erase(resolved.types.begin(), resolved.types.begin() + positional_count); + resolved.positional_count = 0; + CastToFunctionArguments(definition->GetName(), resolved.types, resolved.arguments); + vector parameters; + named_argument_map_t named_parameters; + FoldArguments(context, *definition, resolved, parameters, named_parameters); + return make_uniq(BoundTableFunction(definition), std::move(parameters), + std::move(named_parameters)); +} + unique_ptr FunctionBinder::BindPragmaFunction( const PragmaFunctionSet &functions, vector> &positional_arguments, vector>> &named_arguments, ErrorData &error) { @@ -957,6 +997,10 @@ void FunctionBinder::CastToFunctionArguments(const Identifier &function_name, ve "Function %s returned a STRING_LITERAL or INTEGER_LITERAL type - return an explicit type instead", 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 + throw ParameterNotResolvedException(); + } target_type.Verify(); // don't cast lambda children, their slot only ever holds a placeholder if (children[i]->GetReturnType().id() == LogicalTypeId::LAMBDA) { @@ -974,9 +1018,9 @@ void FunctionBinder::CastToFunctionArguments(const Identifier &function_name, ve // except for one special case: if the function accepts ANY argument // in that case we don't add a cast if (cast_result == LogicalTypeComparisonResult::DIFFERENT_TYPES) { - if (target_has_any && children[i]->GetReturnType().id() != LogicalTypeId::UNKNOWN) { + if (target_has_any) { // a type that is not concrete cannot be cast to (e.g. a NULL or a VARIANT passed to LIST(ANY)) - the - // function has to handle the argument as-is. Unresolved parameters are still assigned the type. + // function has to handle the argument as-is continue; } if (IsIncompleteCastTarget(target_type)) { @@ -1275,7 +1319,7 @@ static string ExtractCollation(const vector> &children) { //! Pushes the collations of the arguments into the children, returns the collation to propagate to the return type static string PushCollations(ClientContext &context, BoundSimpleFunction &bound_function, - vector> &children, CollationType type) { + vector> &children, CollationType type, bool is_index_key) { FunctionCollations collations; auto &argument_types = bound_function.GetArguments(); for (idx_t i = 0; i < children.size(); i++) { @@ -1283,8 +1327,8 @@ static string PushCollations(ClientContext &context, BoundSimpleFunction &bound_ auto &target_type = argument_types[i].IsComplete() ? argument_types[i] : source_type; ExtractCollationFromType(source_type, target_type, collations); } - if (collations.collation.empty() && collations.fields.empty()) { - // no collation to push + if (is_index_key && collations.collation.empty() && collations.fields.empty()) { + // index keys only use explicit collations, comparison keys and the default collation would change them return string(); } // push collations to the children @@ -1310,13 +1354,14 @@ static string PushCollations(ClientContext &context, BoundSimpleFunction &bound_ //! Pushes collations into the children (if required), returns the collation to propagate to the return type static string PushArgumentCollations(ClientContext &context, BoundSimpleFunction &bound_function, - const FunctionProperties &props, vector> &children) { + const FunctionProperties &props, vector> &children, + bool is_index_key) { switch (props.GetCollationHandling()) { case FunctionCollationHandling::IGNORE_COLLATIONS: case FunctionCollationHandling::PROPAGATE_COLLATIONS: return string(); case FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS: - return PushCollations(context, bound_function, children, CollationType::COMBINABLE_COLLATIONS); + return PushCollations(context, bound_function, children, CollationType::COMBINABLE_COLLATIONS, is_index_key); case FunctionCollationHandling::PUSH_DISTINCT_COLLATIONS: throw InternalException("PUSH_DISTINCT_COLLATIONS is only supported for aggregate functions"); default: @@ -1427,8 +1472,9 @@ FunctionBinder::ResolveScalarFunctionTypes(const FunctionBinding &binding, vecto bound_function.GetResolveTypesCallback()(input); VerifyArgumentCount(bound_function, arguments.size()); } + const bool is_index_key = arguments_collated || (binder && binder->IsBindingIndexKey()); result.pushed_collation = - PushArgumentCollations(context, bound_function, bound_function.GetProperties(), arguments); + PushArgumentCollations(context, bound_function, bound_function.GetProperties(), arguments, is_index_key); CastToFunctionArguments(bound_function.GetName(), bound_function.GetArguments(), arguments); return result; } diff --git a/src/duckdb/src/function/scalar/comparison/between.cpp b/src/duckdb/src/function/scalar/comparison/between.cpp index f1fc5b657..07af88c26 100644 --- a/src/duckdb/src/function/scalar/comparison/between.cpp +++ b/src/duckdb/src/function/scalar/comparison/between.cpp @@ -1,9 +1,11 @@ #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/smaller_binary.hpp" +#include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/function/scalar/comparison_functions.hpp" #include "duckdb/function/scalar_function.hpp" #include "duckdb/parser/expression/between_expression.hpp" +#include "duckdb/parser/expression/comparison_expression.hpp" #include "duckdb/planner/expression/bound_between_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/legacy_bound_between_expression.hpp" @@ -59,6 +61,9 @@ void BetweenFunction(DataChunk &args, ExpressionState &state, Vector &result) { #if !DUCKDB_SMALLER_BINARY(between_select) struct BothInclusiveBetweenOperator { + static constexpr bool LOWER_INCLUSIVE = true; + static constexpr bool UPPER_INCLUSIVE = true; + template static inline bool Operation(T input, T lower, T upper) { return GreaterThanEquals::Operation(input, lower) && LessThanEquals::Operation(input, upper); @@ -66,6 +71,9 @@ struct BothInclusiveBetweenOperator { }; struct LowerInclusiveBetweenOperator { + static constexpr bool LOWER_INCLUSIVE = true; + static constexpr bool UPPER_INCLUSIVE = false; + template static inline bool Operation(T input, T lower, T upper) { return GreaterThanEquals::Operation(input, lower) && LessThan::Operation(input, upper); @@ -73,6 +81,9 @@ struct LowerInclusiveBetweenOperator { }; struct UpperInclusiveBetweenOperator { + static constexpr bool LOWER_INCLUSIVE = false; + static constexpr bool UPPER_INCLUSIVE = true; + template static inline bool Operation(T input, T lower, T upper) { return GreaterThan::Operation(input, lower) && LessThanEquals::Operation(input, upper); @@ -80,12 +91,39 @@ struct UpperInclusiveBetweenOperator { }; struct ExclusiveBetweenOperator { + static constexpr bool LOWER_INCLUSIVE = false; + static constexpr bool UPPER_INCLUSIVE = false; + template static inline bool Operation(T input, T lower, T upper) { return GreaterThan::Operation(input, lower) && LessThan::Operation(input, upper); } }; +template +static idx_t BetweenSelectGeneric(const Vector &input, const Vector &lower, const Vector &upper, + optional_ptr sel, idx_t count, + optional_ptr true_sel, optional_ptr false_sel) { + // fallback for types without a templated select path (e.g. nested types): + // evaluate the boolean result like the execute path and turn it into a selection + Vector intermediate1(LogicalType::BOOLEAN); + Vector intermediate2(LogicalType::BOOLEAN); + Vector result(LogicalType::BOOLEAN); + if (OP::LOWER_INCLUSIVE) { + VectorOperations::GreaterThanEquals(input, lower, intermediate1); + } else { + VectorOperations::GreaterThan(input, lower, intermediate1); + } + if (OP::UPPER_INCLUSIVE) { + VectorOperations::LessThanEquals(input, upper, intermediate2); + } else { + VectorOperations::LessThan(input, upper, intermediate2); + } + VectorOperations::And(intermediate1, intermediate2, result); + return UnaryExecutor::Select( + result, sel.get(), count, [](bool value) { return value; }, true_sel.get(), false_sel.get()); +} + template static idx_t BetweenLoopTypeSwitch(const Vector &input, const Vector &lower, const Vector &upper, optional_ptr sel, idx_t count, @@ -134,7 +172,7 @@ static idx_t BetweenLoopTypeSwitch(const Vector &input, const Vector &lower, con return TernaryExecutor::Select(input, lower, upper, sel, count, true_sel, false_sel); default: - throw InvalidTypeException(input.GetType(), "Invalid type for BETWEEN"); + return BetweenSelectGeneric(input, lower, upper, sel, count, true_sel, false_sel); } } @@ -184,7 +222,17 @@ unique_ptr BindBetweenFun(BindScalarFunctionInput &input) { } string BetweenToString(FunctionToStringInput &input) { - return BetweenExpression::ToString(*input.children[0], *input.children[1], *input.children[2]); + auto &between_info = input.bind_data->Cast(); + auto &between_input = input.GetChild(0); + auto &lower = input.GetChild(1); + auto &upper = input.GetChild(2); + if (between_info.lower_inclusive && between_info.upper_inclusive) { + return BetweenExpression::ToString(between_input, lower, upper); + } + auto lower_type = BoundBetweenExpression::LowerComparisonType(between_info.lower_inclusive); + auto upper_type = BoundBetweenExpression::UpperComparisonType(between_info.upper_inclusive); + return "(" + ComparisonExpression::ToString(lower_type, between_input, lower) + " AND " + + ComparisonExpression::ToString(upper_type, between_input, upper) + ")"; } ExpressionType BetweenGetExpressionType(FunctionToStringInput &input) { diff --git a/src/duckdb/src/function/scalar/list/contains_or_position.cpp b/src/duckdb/src/function/scalar/list/contains_or_position.cpp index c70da99f7..1bf28749e 100644 --- a/src/duckdb/src/function/scalar/list/contains_or_position.cpp +++ b/src/duckdb/src/function/scalar/list/contains_or_position.cpp @@ -70,7 +70,7 @@ static FilterPropagateResult ListContainsFilterPrune(const FunctionStatisticsPru if (!ListSearchNeverMatches(list_stats, needle_stats, false)) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } - // list_contains is NULL if either side is NULL, and false otherwise. + // list_contains is NULL if either side is NULL (except an empty list, which gives false), and false otherwise. const bool can_have_null = list_stats->CanHaveNull() || !needle_stats || needle_stats->CanHaveNull(); return can_have_null ? FilterPropagateResult::FILTER_FALSE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_FALSE; } @@ -96,6 +96,7 @@ ScalarFunction ListContainsFun::GetFunction() { fun.GetSignature() .AddParameter("list", LogicalType::LIST(LogicalType::TEMPLATE("T"))) .AddParameter("element", LogicalType::TEMPLATE("T")); + fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); fun.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS); fun.SetFilterPruneCallback(ListContainsFilterPrune); return fun; diff --git a/src/duckdb/src/function/scalar/list/list_select.cpp b/src/duckdb/src/function/scalar/list/list_select.cpp index a3f67377b..f12bb84a8 100644 --- a/src/duckdb/src/function/scalar/list/list_select.cpp +++ b/src/duckdb/src/function/scalar/list/list_select.cpp @@ -155,7 +155,12 @@ void ListSelectFunction(const DataChunk &args, ExpressionState &state, Vector &r } ListVector::SetListSize(result, offset); - if (result_length > 0) { + if (ListVector::GetListSize(list) == 0) { + // an empty input child has nothing to slice: every selected entry is NULL + for (idx_t i = 0; i < offset; i++) { + FlatVector::SetNull(result_entry, i, true); + } + } else if (result_length > 0) { result_entry.Slice(input_entry, result_selection_vec, offset); result_entry.Flatten(); diff --git a/src/duckdb/src/function/scalar/map/map_contains.cpp b/src/duckdb/src/function/scalar/map/map_contains.cpp index 5565d0ebd..93e6aad1e 100644 --- a/src/duckdb/src/function/scalar/map/map_contains.cpp +++ b/src/duckdb/src/function/scalar/map/map_contains.cpp @@ -61,6 +61,7 @@ ScalarFunction MapContainsFun::GetFunction() { ScalarFunction fun("map_contains", {}, LogicalType::BOOLEAN, MapContainsFunction); fun.GetSignature().AddParameter("map", LogicalType::MAP(key_type, val_type)).AddParameter("key", key_type); + fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); fun.SetBindExpressionCallback(BindMapContainsExpression); return fun; } diff --git a/src/duckdb/src/function/scalar/operator/add.cpp b/src/duckdb/src/function/scalar/operator/add.cpp index 22bce3f0e..f951f2068 100644 --- a/src/duckdb/src/function/scalar/operator/add.cpp +++ b/src/duckdb/src/function/scalar/operator/add.cpp @@ -8,6 +8,7 @@ #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/operator/cast_operators.hpp" namespace duckdb { @@ -107,11 +108,41 @@ timestamp_t AddOperator::Operation(timestamp_t left, interval_t right) { return Interval::Add(left, right); } +template <> +timestamp_t AddOperator::Operation(timestamp_sec_t left, interval_t right) { + return Interval::Add(Cast::Operation(left), right); +} + +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, interval_t right) { + return Interval::Add(Cast::Operation(left), right); +} + +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, interval_t right) { + return Interval::Add(left, right); +} + +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_sec_t right) { + return AddOperator::Operation(right, left); +} + +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_ms_t right) { + return AddOperator::Operation(right, left); +} + template <> timestamp_t AddOperator::Operation(interval_t left, timestamp_t right) { return AddOperator::Operation(right, left); } +template <> +timestamp_ns_t AddOperator::Operation(interval_t left, timestamp_ns_t right) { + return AddOperator::Operation(right, left); +} + template <> timestamp_t AddOperator::Operation(timestamp_t left, double right) { timestamp_t result; @@ -121,6 +152,33 @@ timestamp_t AddOperator::Operation(timestamp_t left, double right) { return result; } +template <> +timestamp_t AddOperator::Operation(timestamp_sec_t left, double right) { + timestamp_t result; + if (!TryAddOperator::Operation(left.value, int64_t(right), result.value)) { + throw OutOfRangeException("Overflow in timestamp (s) addition"); + } + return result; +} + +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, double right) { + timestamp_t result; + if (!TryAddOperator::Operation(left.value, int64_t(right), result.value)) { + throw OutOfRangeException("Overflow in timestamp (ms) addition"); + } + return result; +} + +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, double right) { + timestamp_ns_t result; + if (!TryAddOperator::Operation(left.value, int64_t(right), result.value)) { + throw OutOfRangeException("Overflow in timestamp_ns addition"); + } + return result; +} + //===--------------------------------------------------------------------===// // + [add] with overflow check //===--------------------------------------------------------------------===// @@ -167,6 +225,11 @@ bool TryAddOperator::Operation(timestamp_t left, interval_t right, timestamp_t & return Interval::TryAdd(left, right, result); } +template <> +bool TryAddOperator::Operation(timestamp_ns_t left, interval_t right, timestamp_ns_t &result) { + return Interval::TryAdd(left, right, result); +} + template <> bool TryAddOperator::Operation(date_t left, int32_t right, date_t &result) { if (left == date_t::infinity() || left == date_t::ninfinity()) { diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index 87761732a..2e9953f06 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -7,6 +7,7 @@ #include "duckdb/common/enum_util.hpp" #include "duckdb/common/bignum.hpp" +#include "duckdb/common/exception/conversion_exception.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/interpolate.hpp" #include "duckdb/common/operator/multiply.hpp" @@ -328,12 +329,12 @@ template LogicalType DecimalArithmeticResultType(const vector &input_types, bool &check_overflow) { check_overflow = false; // get the max width and scale of the input arguments - uint8_t max_width = 0, max_scale = 0, max_width_over_scale = 0; + uint32_t max_width = 0, max_scale = 0, max_width_over_scale = 0; for (auto &input_type : input_types) { if (input_type.id() == LogicalTypeId::UNKNOWN) { continue; } - uint8_t width, scale; + uint32_t width, scale; auto can_convert = input_type.GetDecimalProperties(width, scale); if (!can_convert) { throw BinderException("Could not convert type %s to a decimal for the arithmetic operator - add an " @@ -343,14 +344,14 @@ LogicalType DecimalArithmeticResultType(const vector &input_types, if (width > max_width) { max_width = width; } - max_scale = MaxValue(scale, max_scale); - max_width_over_scale = MaxValue(width - scale, max_width_over_scale); + max_scale = MaxValue(scale, max_scale); + max_width_over_scale = MaxValue(width - scale, max_width_over_scale); } D_ASSERT(max_width > 0); - uint8_t required_width = MaxValue(max_scale + max_width_over_scale, max_width); + uint32_t required_width = MaxValue(max_scale + max_width_over_scale, max_width); if (!IS_MODULO) { // for addition/subtraction, we add 1 to the width to ensure we don't overflow - required_width = NumericCast(required_width + 1); + required_width++; } if (required_width > Decimal::MAX_WIDTH_DECIMAL) { // target width does not fit in decimal at all: truncate the scale and perform overflow detection @@ -372,7 +373,7 @@ bool ResolveDecimalArithmeticTypes(ResolveScalarFunctionTypesInput &input) { // first check if the cast is necessary // if the argument has a matching scale and internal type as the output type, no casting is necessary auto &argument_type = argument_types[i]; - uint8_t width, scale; + uint32_t width, scale; argument_type.GetDecimalProperties(width, scale); if (scale == DecimalType::GetScale(result_type) && argument_type.InternalType() == result_type.InternalType()) { bound_function.GetArguments()[i] = argument_type; @@ -627,6 +628,30 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi // not monotonic: adding months clamps the day but keeps the time, e.g. // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' return function; + } else if (right_type.id() == LogicalTypeId::TIMESTAMP_SEC) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: adding months clamps the day but keeps the time, e.g. + // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + return function; + } else if (right_type.id() == LogicalTypeId::TIMESTAMP_MS) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: adding months clamps the day but keeps the time, e.g. + // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + return function; + } else if (right_type.id() == LogicalTypeId::TIMESTAMP_NS) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP_NS, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: adding months clamps the day but keeps the time, e.g. + // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + return function; } break; case LogicalTypeId::TIME: @@ -656,6 +681,26 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi return function; } break; + case LogicalTypeId::TIMESTAMP_SEC: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: see INTERVAL + TIMESTAMP_SEC + return function; + } + break; + case LogicalTypeId::TIMESTAMP_MS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: see INTERVAL + TIMESTAMP_MS + return function; + } + break; case LogicalTypeId::TIMESTAMP: if (right_type.id() == LogicalTypeId::INTERVAL) { ScalarFunction function("+", {left_type, right_type}, LogicalType::TIMESTAMP, @@ -665,6 +710,16 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi return function; } break; + case LogicalTypeId::TIMESTAMP_NS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP_NS, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: see INTERVAL + TIMESTAMP + return function; + } + break; default: break; } @@ -713,9 +768,18 @@ ScalarFunctionSet OperatorAddFun::GetFunctions() { add.AddFunction(AddFunction::GetFunction(LogicalType::TIME, LogicalType::INTERVAL)); add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIME)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP_S, LogicalType::INTERVAL)); + add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP_S)); + + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP_MS, LogicalType::INTERVAL)); + add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP_MS)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP, LogicalType::INTERVAL)); add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP_NS, LogicalType::INTERVAL)); + add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP_NS)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIME_TZ, LogicalType::INTERVAL)); add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIME_TZ)); @@ -919,6 +983,42 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const return function; } break; + case LogicalTypeId::TIMESTAMP_SEC: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "-", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' + + return function; + } + break; + case LogicalTypeId::TIMESTAMP_MS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "-", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' + + return function; + } + break; + case LogicalTypeId::TIMESTAMP_NS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "-", {left_type, right_type}, LogicalType::TIMESTAMP_NS, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' + + return function; + } + break; case LogicalTypeId::INTERVAL: if (right_type.id() == LogicalTypeId::INTERVAL) { ScalarFunction function( @@ -980,6 +1080,9 @@ ScalarFunctionSet OperatorSubtractFun::GetFunctions() { subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::DATE, LogicalType::INTERVAL)); subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIME, LogicalType::INTERVAL)); subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP, LogicalType::INTERVAL)); + subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP_S, LogicalType::INTERVAL)); + subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP_MS, LogicalType::INTERVAL)); + subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP_NS, LogicalType::INTERVAL)); subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIME_TZ, LogicalType::INTERVAL)); // we can negate intervals subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::INTERVAL)); @@ -1033,20 +1136,19 @@ struct MultiplyPropagateStatistics { //! Computes the result type of a decimal multiplication over the given input types LogicalType DecimalMultiplyResultType(const vector &input_types, bool &check_overflow) { check_overflow = false; - uint8_t result_width = 0, result_scale = 0; - uint8_t max_width = 0; + uint32_t result_width = 0, result_scale = 0, max_width = 0; for (auto &input_type : input_types) { if (input_type.id() == LogicalTypeId::UNKNOWN) { continue; } - uint8_t width, scale; + uint32_t width, scale; auto can_convert = input_type.GetDecimalProperties(width, scale); if (!can_convert) { throw BinderException("Could not convert type %s to a decimal for the arithmetic operator - add an " "explicit cast", input_type.ToString()); } - max_width = MaxValue(width, max_width); + max_width = MaxValue(width, max_width); result_width += width; result_scale += scale; } @@ -1083,7 +1185,7 @@ void DecimalMultiplyResolveTypes(ResolveScalarFunctionTypesInput &input) { if (argument_type.InternalType() == result_type.InternalType()) { bound_function.GetArguments()[i] = argument_type; } else { - uint8_t width, scale; + uint32_t width, scale; if (!argument_type.GetDecimalProperties(width, scale)) { scale = 0; } @@ -1812,13 +1914,33 @@ double InterpolateOperator::Operation(const double &lo, const double d, const do return lo * (1.0 - d) + hi * d; } -//! Interpolates between two integers without going through a double for the values themselves +//! Interpolates between two integers without going through a double for the values themselves. +//! The result lies between the two values, but the double arithmetic can round past them (and past the int64 range, +//! where llround is undefined), so bound it against the endpoints before converting back. static int64_t InterpolateInt64(const int64_t lo, const double d, const int64_t hi) { int64_t delta; if (!TrySubtractOperator::Operation(hi, lo, delta)) { - return std::llround(static_cast(lo) * (1.0 - d) + static_cast(hi) * d); + const auto range_min = MinValue(lo, hi); + const auto range_max = MaxValue(lo, hi); + const auto mixed = static_cast(lo) * (1.0 - d) + static_cast(hi) * d; + if (mixed <= static_cast(range_min)) { + return range_min; + } + if (mixed >= static_cast(range_max)) { + return range_max; + } + return std::llround(mixed); + } + const auto offset_min = MinValue(delta, 0); + const auto offset_max = MaxValue(delta, 0); + const auto offset = static_cast(delta) * d; + if (offset <= static_cast(offset_min)) { + return lo + offset_min; } - return lo + std::llround(static_cast(delta) * d); + if (offset >= static_cast(offset_max)) { + return lo + offset_max; + } + return lo + std::llround(offset); } template <> @@ -1846,6 +1968,13 @@ dtime_tz_t InterpolateOperator::Operation(const dtime_tz_t &lo, const double d, template <> timestamp_t InterpolateOperator::Operation(const timestamp_t &lo, const double d, const timestamp_t &hi) { + if (lo == hi) { + return lo; + } + // the infinities are sentinel values, and interpolating with their raw encodings produces nonsense + if (!Value::IsFinite(lo) || !Value::IsFinite(hi)) { + throw ConversionException("Cannot interpolate infinite TIMESTAMP values"); + } return timestamp_t(InterpolateInt64(lo.value, d, hi.value)); } @@ -1854,7 +1983,8 @@ hugeint_t InterpolateOperator::Operation(const hugeint_t &lo, const double d, co hugeint_t delta_hugeint = hi; if (Hugeint::TrySubtractInPlace(delta_hugeint, lo)) { const auto delta = Hugeint::Cast(delta_hugeint); - return lo + Hugeint::Convert(delta * d); + // Rounding delta to double can carry the offset past hi, and past the HUGEINT range when hi is the minimum. + return Hugeint::Add(lo, Hugeint::Convert(delta * d)); } // if delta overflows, we fall back to original subtraction to avoid UB diff --git a/src/duckdb/src/function/scalar/operator/decimal_division.cpp b/src/duckdb/src/function/scalar/operator/decimal_division.cpp index d90950655..2e8c94c08 100644 --- a/src/duckdb/src/function/scalar/operator/decimal_division.cpp +++ b/src/duckdb/src/function/scalar/operator/decimal_division.cpp @@ -40,12 +40,66 @@ struct DecimalDivBindData : public FunctionData { // hugeint_t -- otherwise //===--------------------------------------------------------------------===// +template +static constexpr uint8_t DecimalTierWidth() { + if constexpr (std::is_same_v) { + return Decimal::MAX_WIDTH_INT16; + } else if constexpr (std::is_same_v) { + return Decimal::MAX_WIDTH_INT32; + } else if constexpr (std::is_same_v) { + return Decimal::MAX_WIDTH_INT64; + } else { + return Decimal::MAX_WIDTH_DECIMAL; + } +} + +template +static void WidenDecimal(Vector &input, Vector &widened, idx_t count) { + if constexpr (sizeof(SOURCE_TYPE) < sizeof(INPUT_TYPE)) { + auto widen = [](SOURCE_TYPE value) { + return INPUT_TYPE(value); + }; + UnaryExecutor::Execute(input, widened, count, widen); + } else { + throw InternalException("decimal_division: argument is wider than the compute tier"); + } +} + +//! Bring an argument to the physical type of the wider argument; a decimal keeps its integer value at the same scale +template +static Vector &GetDecimalInput(Vector &input, idx_t count, unique_ptr &widened) { + auto source_physical = input.GetType().InternalType(); + if (source_physical == GetTypeId()) { + return input; + } + auto scale = DecimalType::GetScale(input.GetType()); + widened = make_uniq(LogicalType::DECIMAL(DecimalTierWidth(), scale), count); + switch (source_physical) { + case PhysicalType::INT16: + WidenDecimal(input, *widened, count); + break; + case PhysicalType::INT32: + WidenDecimal(input, *widened, count); + break; + case PhysicalType::INT64: + WidenDecimal(input, *widened, count); + break; + default: + throw InternalException("decimal_division: unexpected argument physical type"); + } + return *widened; +} + template static void DecimalDivExecute(DataChunk &args, ExpressionState &state, Vector &result) { auto &bind_data = state.expr.Cast().BindInfo()->Cast(); + unique_ptr lhs_widened; + unique_ptr rhs_widened; + auto &lhs = GetDecimalInput(args.data[0], args.size(), lhs_widened); + auto &rhs = GetDecimalInput(args.data[1], args.size(), rhs_widened); bool scale_divisor = bind_data.scale_exp < 0; - uint8_t abs_exp = UnsafeNumericCast(AbsValue(bind_data.scale_exp)); + uint32_t abs_exp = UnsafeNumericCast(AbsValue(bind_data.scale_exp)); COMPUTE_TYPE scale_factor; if constexpr (std::is_same_v) { @@ -56,7 +110,7 @@ static void DecimalDivExecute(DataChunk &args, ExpressionState &state, Vector &r auto result_width = DecimalType::GetWidth(result.GetType()); BinaryExecutor::Execute( - args.data[0], args.data[1], result, args.size(), [&](INPUT_TYPE a, INPUT_TYPE b) -> RESULT_TYPE { + lhs, rhs, result, args.size(), [&](INPUT_TYPE a, INPUT_TYPE b) -> RESULT_TYPE { if (b == INPUT_TYPE(0)) { throw InvalidInputException("decimal_division: division by zero"); } @@ -160,6 +214,8 @@ static scalar_function_t GetDecimalDivExecuteFunction(PhysicalType result_physic // Bind function //===--------------------------------------------------------------------===// +static void SelectDecimalDivFunction(BoundScalarFunction &bound_function); + // Result width and scale for e1 / e2 (SQL Server semantics): // result_scale = max(6, s1 + p2 + 1) // result_width = p1 - s1 + s2 + result_scale @@ -169,12 +225,15 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) auto &lhs_type = input.GetArgumentType(0); auto &rhs_type = input.GetArgumentType(1); - uint8_t p1, s1, p2, s2; + uint32_t p1, s1, p2, s2; if (!lhs_type.GetDecimalProperties(p1, s1) || !rhs_type.GetDecimalProperties(p2, s2)) { throw InvalidInputException("decimal_division: both arguments must be DECIMAL"); } + // an integer argument is an implicit DECIMAL(p, 0): bind on its canonical DECIMAL type + auto lhs_decimal_type = lhs_type.id() == LogicalTypeId::DECIMAL ? lhs_type : LogicalType::DECIMAL(p1, s1); + auto rhs_decimal_type = rhs_type.id() == LogicalTypeId::DECIMAL ? rhs_type : LogicalType::DECIMAL(p2, s2); - uint8_t result_scale; + uint32_t result_scale; if (input.GetArgumentCount() == 3) { auto scale_val = input.GetNonNullConstant(2); auto scale_i = scale_val.GetValue(); @@ -182,17 +241,17 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) throw InvalidInputException("decimal_division: scale must be between 0 and %d, got %d", Decimal::MAX_WIDTH_DECIMAL, scale_i); } - result_scale = UnsafeNumericCast(scale_i); + result_scale = UnsafeNumericCast(scale_i); } else { - result_scale = MaxValue(6, s1 + p2 + 1); + result_scale = MaxValue(6, s1 + p2 + 1); } // result_width uses signed arithmetic to catch underflow before casting. - auto result_width_i = p1 - s1 + s2 + result_scale; + auto result_width_i = int64_t(p1) - int64_t(s1) + int64_t(s2) + int64_t(result_scale); if (result_width_i < 1) { throw InvalidInputException("decimal_division: scale %d produces a zero-width result for these input types", result_scale); } - uint8_t result_width = UnsafeNumericCast(result_width_i); + uint32_t result_width = UnsafeNumericCast(result_width_i); if (result_scale > Decimal::MAX_WIDTH_DECIMAL) { throw OutOfRangeException( @@ -209,50 +268,22 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) result_width, Decimal::MAX_WIDTH_DECIMAL); } - PhysicalType result_physical; - if (result_width <= Decimal::MAX_WIDTH_INT16) { - result_physical = PhysicalType::INT16; - } else if (result_width <= Decimal::MAX_WIDTH_INT32) { - result_physical = PhysicalType::INT32; - } else if (result_width <= Decimal::MAX_WIDTH_INT64) { - result_physical = PhysicalType::INT64; - } else { - result_physical = PhysicalType::INT128; - } - bound_function.SetReturnType(LogicalType::DECIMAL(result_width, result_scale)); + // keep the argument types: a narrower argument is widened at execution, so binding again yields the same types + bound_function.GetArguments()[0] = lhs_decimal_type; + bound_function.GetArguments()[1] = rhs_decimal_type; + SelectDecimalDivFunction(bound_function); +} - auto lhs_physical = lhs_type.InternalType(); - auto rhs_physical = rhs_type.InternalType(); - auto wider = MaxValue(lhs_physical, rhs_physical); - - int32_t scale_exp = s2 + result_scale - s1; - int32_t abs_scale_exp = scale_exp < 0 ? -scale_exp : scale_exp; - - uint8_t input_max_width; - switch (wider) { - case PhysicalType::INT16: - input_max_width = Decimal::MAX_WIDTH_INT16; - break; - case PhysicalType::INT32: - input_max_width = Decimal::MAX_WIDTH_INT32; - break; - case PhysicalType::INT64: - input_max_width = Decimal::MAX_WIDTH_INT64; - break; - case PhysicalType::INT128: - input_max_width = Decimal::MAX_WIDTH_DECIMAL; - break; - default: - throw InternalException("decimal_division: unexpected physical type"); - } - - // For same-tier inputs, preserve the original argument type so bind is idempotent - // during plan deserialization (bind is re-called with the stored argument types, and - // changing p changes the result-width formula). - // For cross-tier inputs, promote the narrower argument to the wider physical tier. - bound_function.GetArguments()[0] = (lhs_physical != wider) ? LogicalType::DECIMAL(input_max_width, s1) : lhs_type; - bound_function.GetArguments()[1] = (rhs_physical != wider) ? LogicalType::DECIMAL(input_max_width, s2) : rhs_type; +//! Pick the execute function from the resolved argument and return types +static void SelectDecimalDivFunction(BoundScalarFunction &bound_function) { + auto &arguments = bound_function.GetArguments(); + const auto result_physical = bound_function.GetReturnType().InternalType(); + const auto wider = MaxValue(arguments[0].InternalType(), arguments[1].InternalType()); + const int32_t scale_exp = int32_t(DecimalType::GetScale(arguments[1])) + + int32_t(DecimalType::GetScale(bound_function.GetReturnType())) - + int32_t(DecimalType::GetScale(arguments[0])); + const int32_t abs_scale_exp = scale_exp < 0 ? -scale_exp : scale_exp; switch (wider) { case PhysicalType::INT16: @@ -287,7 +318,7 @@ static unique_ptr DecimalDivisionBind(BindScalarFunctionInput &inp auto lhs_scale = DecimalType::GetScale(bound_function.GetArguments()[0]); auto rhs_scale = DecimalType::GetScale(bound_function.GetArguments()[1]); auto result_scale = DecimalType::GetScale(bound_function.GetReturnType()); - return make_uniq(rhs_scale + result_scale - lhs_scale); + return make_uniq(int32_t(rhs_scale) + int32_t(result_scale) - int32_t(lhs_scale)); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/function/scalar/operator/multiply.cpp b/src/duckdb/src/function/scalar/operator/multiply.cpp index c728cdd58..f0394ef90 100644 --- a/src/duckdb/src/function/scalar/operator/multiply.cpp +++ b/src/duckdb/src/function/scalar/operator/multiply.cpp @@ -223,49 +223,41 @@ bool TryMultiplyOperator::Operation(int64_t left, int64_t right, int64_t &result } return false; } - uint64_t left_non_negative = uint64_t(std::abs(left)); - uint64_t right_non_negative = uint64_t(std::abs(right)); + uint64_t left_magnitude = uint64_t(std::abs(left)); + uint64_t right_magnitude = uint64_t(std::abs(right)); + bool negative = (left < 0) != (right < 0); // split values into 2 32-bit parts - uint64_t left_high_bits = left_non_negative >> 32; - uint64_t left_low_bits = left_non_negative & 0xffffffff; - uint64_t right_high_bits = right_non_negative >> 32; - uint64_t right_low_bits = right_non_negative & 0xffffffff; - - // check the high bits of both - // the high bits define the overflow - if (left_high_bits == 0) { - if (right_high_bits != 0) { - // only the right has high bits set - // multiply the high bits of right with the low bits of left - // multiply the low bits, and carry any overflow to the high bits - // then check for any overflow - auto low_low = left_low_bits * right_low_bits; - auto low_high = left_low_bits * right_high_bits; - auto high_bits = low_high + (low_low >> 32); - if (high_bits & 0xffffff80000000) { - // there is! abort - return false; - } - } - } else if (right_high_bits == 0) { - // only the left has high bits set - // multiply the high bits of left with the low bits of right - // multiply the low bits, and carry any overflow to the high bits - // then check for any overflow - auto low_low = left_low_bits * right_low_bits; - auto high_low = left_high_bits * right_low_bits; - auto high_bits = high_low + (low_low >> 32); - if (high_bits & 0xffffff80000000) { - // there is! abort - return false; - } - } else { - // both left and right have high bits set: guaranteed overflow - // abort! + uint64_t left_high_bits = left_magnitude >> 32; + uint64_t left_low_bits = left_magnitude & 0xffffffff; + uint64_t right_high_bits = right_magnitude >> 32; + uint64_t right_low_bits = right_magnitude & 0xffffffff; + + if (left_high_bits != 0 && right_high_bits != 0) { + // both left and right have high bits set: the product is at least 2^64 + return false; + } + // at most one cross term is non-zero here, and it is below 2^63 + uint64_t cross_bits = left_high_bits * right_low_bits + left_low_bits * right_high_bits; + if (cross_bits >> 32) { + // the shifted cross term alone is at least 2^64 return false; } - // now we know that there is no overflow, we can just perform the multiplication - result = left * right; + uint64_t low_bits = left_low_bits * right_low_bits; + uint64_t magnitude = (cross_bits << 32) + low_bits; + if (magnitude < low_bits) { + // adding the cross term wrapped: the product is at least 2^64 + return false; + } + if (magnitude > (uint64_t(1) << 63) - (negative ? 0 : 1)) { + // the magnitude exceeds the signed range (the minimum is representable when negative) + return false; + } + // the magnitude fits: produce the signed result (the minimum cannot be negated) + if (negative) { + result = magnitude == (uint64_t(1) << 63) ? std::numeric_limits::min() : -int64_t(magnitude); + } else { + result = int64_t(magnitude); + } #endif return true; } diff --git a/src/duckdb/src/function/scalar/operator/subtract.cpp b/src/duckdb/src/function/scalar/operator/subtract.cpp index f33936b9e..87cd193d6 100644 --- a/src/duckdb/src/function/scalar/operator/subtract.cpp +++ b/src/duckdb/src/function/scalar/operator/subtract.cpp @@ -72,6 +72,21 @@ timestamp_t SubtractOperator::Operation(timestamp_t left, interval_t right) { return AddOperator::Operation(left, Interval::Invert(right)); } +template <> +timestamp_t SubtractOperator::Operation(timestamp_ms_t left, interval_t right) { + return AddOperator::Operation(left, Interval::Invert(right)); +} + +template <> +timestamp_t SubtractOperator::Operation(timestamp_sec_t left, interval_t right) { + return AddOperator::Operation(left, Interval::Invert(right)); +} + +template <> +timestamp_ns_t SubtractOperator::Operation(timestamp_ns_t left, interval_t right) { + return AddOperator::Operation(left, Interval::Invert(right)); +} + template <> interval_t SubtractOperator::Operation(timestamp_t left, timestamp_t right) { return Interval::GetDifference(left, right); diff --git a/src/duckdb/src/function/scalar/strftime_format.cpp b/src/duckdb/src/function/scalar/strftime_format.cpp index 2c25fa174..889d82d13 100644 --- a/src/duckdb/src/function/scalar/strftime_format.cpp +++ b/src/duckdb/src/function/scalar/strftime_format.cpp @@ -1483,6 +1483,10 @@ date_t StrpTimeFormat::ParseResult::ToDate() { } bool StrpTimeFormat::ParseResult::TryToDate(date_t &result) { + if (is_special) { + result = special; + return true; + } return Date::TryFromDate(data[0], data[1], data[2], result); } @@ -1526,6 +1530,10 @@ timestamp_t StrpTimeFormat::ParseResult::ToTimestamp() { } bool StrpTimeFormat::ParseResult::TryToTimestamp(timestamp_t &result) { + if (is_special) { + result = ToTimestamp(); + return true; + } date_t date; if (!TryToDate(date)) { return false; @@ -1560,6 +1568,10 @@ timestamp_ns_t StrpTimeFormat::ParseResult::ToTimestampNS() { } bool StrpTimeFormat::ParseResult::TryToTimestampNS(timestamp_ns_t &result) { + if (is_special) { + result = ToTimestampNS(); + return true; + } date_t date; if (!TryToDate(date)) { return false; diff --git a/src/duckdb/src/function/scalar/string/concat.cpp b/src/duckdb/src/function/scalar/string/concat.cpp index 0176cc707..f32de3e62 100644 --- a/src/duckdb/src/function/scalar/string/concat.cpp +++ b/src/duckdb/src/function/scalar/string/concat.cpp @@ -332,6 +332,23 @@ unique_ptr ListConcatStats(ClientContext &context, FunctionStati for (idx_t i = 1; i < child_stats.size(); i++) { stats->Merge(child_stats[i]); } + // NULL lists are skipped, so the result length is the sum of the input lengths + idx_t min_length = 0; + optional_idx max_length = 0; + for (auto &child : child_stats) { + auto child_min = ListStats::MinListLength(child); + auto child_max = ListStats::MaxListLength(child); + if (!child.CanHaveNull() && child_min.IsValid()) { + min_length += child_min.GetIndex(); + } + if (!max_length.IsValid() || !child_max.IsValid() || + child_max.GetIndex() > NumericLimits::Maximum() - max_length.GetIndex()) { + max_length = optional_idx(); + } else { + max_length = max_length.GetIndex() + child_max.GetIndex(); + } + } + ListStats::SetLengthBounds(*stats, min_length, max_length); return stats; } diff --git a/src/duckdb/src/function/scalar/string/length.cpp b/src/duckdb/src/function/scalar/string/length.cpp index e1e3e440e..3aba567b6 100644 --- a/src/duckdb/src/function/scalar/string/length.cpp +++ b/src/duckdb/src/function/scalar/string/length.cpp @@ -5,10 +5,14 @@ #include "duckdb/common/vector/vector_writer.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" #include "duckdb/storage/statistics/string_stats.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" +#include "duckdb/function/scalar/generic_functions.hpp" #include "duckdb/function/scalar/string_common.hpp" #include "duckdb/function/scalar/string_functions.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_parameter_expression.hpp" #include "utf8proc.hpp" @@ -163,6 +167,31 @@ void ArrayLengthFunction(DataChunk &args, ExpressionState &state, Vector &result } } +unique_ptr ListLengthPropagateStats(ClientContext &context, FunctionStatisticsInput &input) { + auto &list_stats = input.child_stats[0]; + if (list_stats.GetStatsType() != StatisticsType::LIST_STATS) { + return nullptr; + } + auto min_length = ListStats::MinListLength(list_stats); + auto max_length = ListStats::MaxListLength(list_stats); + if (!min_length.IsValid() || !max_length.IsValid()) { + return nullptr; + } + auto result = NumericStats::CreateEmpty(input.expr.GetReturnType()); + NumericStats::SetMin(result, Value::BIGINT(NumericCast(min_length.GetIndex()))); + NumericStats::SetMax(result, Value::BIGINT(NumericCast(max_length.GetIndex()))); + result.CopyValidity(list_stats); + if (min_length.GetIndex() == max_length.GetIndex() && input.expr_ptr) { + // all lists have the same length, so the result is that length unless the list is NULL + vector> children; + children.push_back( + make_uniq(Value::BIGINT(NumericCast(min_length.GetIndex())))); + children.push_back(std::move(input.expr.GetChildrenMutable()[0])); + *input.expr_ptr = BindBuiltinScalarExpression(context, ConstantOrNullFun::Name, std::move(children)); + } + return result.ToUnique(); +} + void ArrayOrListLengthResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); auto &argument = input.GetArgument(0); @@ -298,6 +327,7 @@ ScalarFunctionSet LengthFun::GetFunctions() { ScalarFunction list_fun({}, LogicalType::BIGINT, nullptr); list_fun.SetResolveTypesCallback(ArrayOrListLengthResolveTypes); + list_fun.SetStatisticsCallback(ListLengthPropagateStats); list_fun.GetSignature().AddParameter("list", LogicalType::LIST(LogicalType::ANY)); length.AddFunction(list_fun); @@ -318,6 +348,7 @@ ScalarFunctionSet ArrayLengthFun::GetFunctions() { ScalarFunction unary({}, LogicalType::BIGINT, nullptr); unary.SetResolveTypesCallback(ArrayOrListLengthResolveTypes); + unary.SetStatisticsCallback(ListLengthPropagateStats); unary.GetSignature().AddParameter("list", LogicalType::LIST(LogicalType::ANY)); array_length.AddFunction(unary); diff --git a/src/duckdb/src/function/scalar/string/substring.cpp b/src/duckdb/src/function/scalar/string/substring.cpp index 4588171e5..048c6c8ba 100644 --- a/src/duckdb/src/function/scalar/string/substring.cpp +++ b/src/duckdb/src/function/scalar/string/substring.cpp @@ -210,18 +210,17 @@ string_t SubstringGrapheme(Vector &result, string_t input, int64_t offset, int64 return SubstringEmptyString(result); } - // now check if all the characters between 0 and end are ascii characters - // note that we scan one further to check for a potential combining diacritics (e.g. i + diacritic is ï) - bool is_ascii = true; - idx_t ascii_end = MinValue(UnsafeNumericCast(end + 1), input_size); - for (idx_t i = 0; i < ascii_end; i++) { - if (input_data[i] & 0x80) { - // found a non-ascii character: eek - is_ascii = false; - break; - } + // now check if the characters that determine the window are ascii characters + idx_t ascii_start = 0; + idx_t ascii_end = input_size; + if (offset < 0) { + // counted from the end, check from one before the window (a prepended character, e.g. U+0600) to the end + ascii_start = UnsafeNumericCast(MaxValue(start - 1, 0)); + } else { + // counted from the start, check up to one after the window (a combining diacritic, e.g. i + diacritic is ï) + ascii_end = MinValue(UnsafeNumericCast(end + 1), input_size); } - if (is_ascii) { + if (IsAscii(input_data + ascii_start, ascii_end - ascii_start)) { // all characters are ascii, we can just slice the substring return SubstringSlice(result, input_data, start, end - start); } diff --git a/src/duckdb/src/function/scalar/struct/remap_struct.cpp b/src/duckdb/src/function/scalar/struct/remap_struct.cpp index 87013c2f1..79b16a0cb 100644 --- a/src/duckdb/src/function/scalar/struct/remap_struct.cpp +++ b/src/duckdb/src/function/scalar/struct/remap_struct.cpp @@ -577,6 +577,13 @@ void VerifyRemapArgumentTypes(const vector &types) { auto &from_type = types[0]; auto &to_type = types[1]; + auto &mapping_type = types[2]; + if (mapping_type.id() != LogicalTypeId::SQLNULL && !StructType::IsStruct(mapping_type)) { + throw BinderException( + "The mapping provided to 'remap_struct' should be of type STRUCT if it's not NULL, not '%s'", + mapping_type.ToString()); + } + auto &defaults_type = types[3]; if (defaults_type.id() != LogicalTypeId::SQLNULL && !StructType::IsStruct(defaults_type)) { throw BinderException("The defaults provided to 'remap_struct' should be of type STRUCT if they're not NULL"); diff --git a/src/duckdb/src/function/scalar/system/write_log.cpp b/src/duckdb/src/function/scalar/system/write_log.cpp index 7174900b5..4ffe4a268 100644 --- a/src/duckdb/src/function/scalar/system/write_log.cpp +++ b/src/duckdb/src/function/scalar/system/write_log.cpp @@ -134,8 +134,8 @@ void WriteLogFunction(DataChunk &args, ExpressionState &state, Vector &result) { WriteLogValues(*info.context->db, info.level, input_data, idata.sel, args.size(), info.type); } else if (info.scope == "file_opener") { - WriteLogValues(*info.context->client_data->file_opener, info.level, input_data, idata.sel, - args.size(), info.type); + WriteLogValues(*info.context->GetContext().TryGetFileOpener(), info.level, input_data, + idata.sel, args.size(), info.type); } else { throw InvalidInputException( "write_log: 'scope' argument unknown: '%s'. Valid values are [connection, database, file_opener]", diff --git a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp index a8deaa571..bd67c027c 100644 --- a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp @@ -63,14 +63,21 @@ void VariantEncodeNumber(SINK &sink, const VariantNumberKey &key) { }; // adjusted exponent (order-preserving signed encoding) orders magnitude - data_t exp_buffer[sizeof(int64_t)]; - Radix::EncodeData(exp_buffer, key.adjusted_exponent); - for (idx_t i = 0; i < sizeof(int64_t); i++) { - emit(exp_buffer[i]); + // common exponents use a single byte in 1..254; 0x00 / 0xFF escape to the full 8 bytes (keeps keys short) + if (key.adjusted_exponent >= -127 && key.adjusted_exponent <= 126) { + emit(static_cast(key.adjusted_exponent + 128)); + } else { + data_t exp_buffer[sizeof(int64_t)]; + Radix::EncodeData(exp_buffer, key.adjusted_exponent); + emit(key.adjusted_exponent < 0 ? 0x00 : 0xFF); + for (idx_t i = 0; i < sizeof(int64_t); i++) { + emit(exp_buffer[i]); + } } // significant digits (1..10 so the 0x00 terminator is smaller than any digit -> prefix sorts first) - for (auto c : key.digits) { - emit(static_cast((c - '0') + 1)); + auto digits = key.GetDigits(); + for (idx_t i = 0; i < key.digit_count; i++) { + emit(static_cast((digits[i] - '0') + 1)); } emit(0); // terminator } @@ -217,7 +224,7 @@ void CreateVariantComparator(const Vector &input, idx_t count, Vector &result) { result.SetVectorType(VectorType::FLAT_VECTOR); auto writer = FlatVector::Writer(result, count); - //! reused growable buffer - the key is encoded once and then copied into the result vector + //! reused growable buffer, so encoding a chunk does not allocate once per value string buffer; for (idx_t r = 0; r < count; r++) { auto root = variant[r]; diff --git a/src/duckdb/src/function/scalar/variant/variant_extract.cpp b/src/duckdb/src/function/scalar/variant/variant_extract.cpp index bd3807cfd..1126aeded 100644 --- a/src/duckdb/src/function/scalar/variant/variant_extract.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_extract.cpp @@ -82,13 +82,16 @@ static unique_ptr VariantExtractBind(BindScalarFunctionInput &inpu } } -static bool TryShreddedExtractRecursive(const Vector &input, const vector &components, - Vector &result, idx_t count, idx_t path_index = 0) { +enum class ShreddedExtractResult : uint8_t { SUCCESS, NOT_SUPPORTED, KEY_NOT_FOUND }; + +static ShreddedExtractResult TryShreddedExtractRecursive(const Vector &input, + const vector &components, Vector &result, + idx_t count, idx_t path_index = 0) { if (path_index >= components.size()) { // reached the end of the path - shred if (input.GetType().IsNested()) { // we only support this for non-nested types for now - return false; + return ShreddedExtractResult::NOT_SUPPORTED; } // create the shredded vector with an empty unshredded part auto shredded_type = VariantUtils::ShreddedType(input.GetType()); @@ -105,27 +108,27 @@ static bool TryShreddedExtractRecursive(const Vector &input, const vector &components, @@ -153,7 +156,15 @@ static bool TryFromShreddedExtract(const Vector &variant_vec, const vector &components, diff --git a/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp b/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp index 972fa48a0..b499de186 100644 --- a/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp @@ -54,7 +54,7 @@ class VariantStringWriter { static void VariantExtractStringFunction(DataChunk &input, ExpressionState &state, Vector &result) { string error; - ConvertedJSONHolder holder(BufferAllocator::Get(state.GetContext())); + ConvertedJSONHolder holder(state.GetAllocator()); VariantPathFunction::Execute(input, state, result, VariantStringWriter(holder, error)); } diff --git a/src/duckdb/src/function/table/arrow.cpp b/src/duckdb/src/function/table/arrow.cpp index 878b4501c..a828b5e09 100644 --- a/src/duckdb/src/function/table/arrow.cpp +++ b/src/duckdb/src/function/table/arrow.cpp @@ -332,6 +332,8 @@ bool ArrowTableFunction::ArrowPushdownType(const FunctionData &bind_data, idx_t void ArrowTableFunction::RegisterFunction(BuiltinFunctions &set) { TableFunction arrow("arrow_scan", {}, ArrowScanFunction, ArrowScanBind, ArrowScanInitGlobal, ArrowScanInitLocal); + // pulls from an external producer whose streams may be one-shot + arrow.stability = FunctionStability::VOLATILE; arrow.cardinality = ArrowScanCardinality; arrow.get_partition_data = ArrowGetPartitionData; arrow.projection_pushdown = true; @@ -343,6 +345,7 @@ void ArrowTableFunction::RegisterFunction(BuiltinFunctions &set) { TableFunction arrow_dumb("arrow_scan_dumb", {}, ArrowScanFunction, ArrowScanBindDumb, ArrowScanInitGlobal, ArrowScanInitLocal); + arrow_dumb.stability = FunctionStability::VOLATILE; arrow_dumb.cardinality = ArrowScanCardinality; arrow_dumb.get_partition_data = ArrowGetPartitionData; arrow_dumb.projection_pushdown = false; diff --git a/src/duckdb/src/function/table/arrow/arrow_duck_schema.cpp b/src/duckdb/src/function/table/arrow/arrow_duck_schema.cpp index fb4e986d2..9465106c4 100644 --- a/src/duckdb/src/function/table/arrow/arrow_duck_schema.cpp +++ b/src/duckdb/src/function/table/arrow/arrow_duck_schema.cpp @@ -119,17 +119,21 @@ unique_ptr ArrowType::GetTypeFromFormat(string &format) { } switch (bitwidth) { case 32: - return make_uniq(LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), - make_uniq(DecimalBitWidth::DECIMAL_32)); + return make_uniq( + LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), + make_uniq(DecimalBitWidth::DECIMAL_32)); case 64: - return make_uniq(LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), - make_uniq(DecimalBitWidth::DECIMAL_64)); + return make_uniq( + LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), + make_uniq(DecimalBitWidth::DECIMAL_64)); case 128: - return make_uniq(LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), - make_uniq(DecimalBitWidth::DECIMAL_128)); + return make_uniq( + LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), + make_uniq(DecimalBitWidth::DECIMAL_128)); case 256: - return make_uniq(LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), - make_uniq(DecimalBitWidth::DECIMAL_256)); + return make_uniq( + LogicalType::DECIMAL(NumericCast(width), NumericCast(scale)), + make_uniq(DecimalBitWidth::DECIMAL_256)); default: throw NotImplementedException("Unsupported bit-width value of %d for Arrow Decimal type", bitwidth); } diff --git a/src/duckdb/src/function/table/checkpoint.cpp b/src/duckdb/src/function/table/checkpoint.cpp index 9031b6f2b..91ebf1f5e 100644 --- a/src/duckdb/src/function/table/checkpoint.cpp +++ b/src/duckdb/src/function/table/checkpoint.cpp @@ -62,16 +62,20 @@ static void TemplatedCheckpointFunction(ClientContext &context, TableFunctionInp } void CheckpointFunction::RegisterFunction(BuiltinFunctions &set) { + // a checkpoint is a side effect per execution TableFunctionSet checkpoint("checkpoint"); checkpoint.AddFunction(TableFunction({}, TemplatedCheckpointFunction, CheckpointBind)); checkpoint.AddFunction(TableFunction(FunctionSignature().AddPositionalOnly("database", LogicalType::VARCHAR), TemplatedCheckpointFunction, CheckpointBind)); + checkpoint.ApplyToFunctions([](TableFunction &function) { function.stability = FunctionStability::VOLATILE; }); set.AddFunction(checkpoint); TableFunctionSet force_checkpoint("force_checkpoint"); force_checkpoint.AddFunction(TableFunction({}, TemplatedCheckpointFunction, CheckpointBind)); force_checkpoint.AddFunction(TableFunction(FunctionSignature().AddPositionalOnly("database", LogicalType::VARCHAR), TemplatedCheckpointFunction, CheckpointBind)); + force_checkpoint.ApplyToFunctions( + [](TableFunction &function) { function.stability = FunctionStability::VOLATILE; }); set.AddFunction(force_checkpoint); } diff --git a/src/duckdb/src/function/table/copy_csv.cpp b/src/duckdb/src/function/table/copy_csv.cpp index 3b24087e4..c5f3869a1 100644 --- a/src/duckdb/src/function/table/copy_csv.cpp +++ b/src/duckdb/src/function/table/copy_csv.cpp @@ -250,7 +250,7 @@ static unique_ptr OpenCSVFileWriter(ClientContext &context, con if (!fs.IsRemoteFile(file_path) && !fs.FileExists(file_path) && !fs.IsPipe(file_path)) { flags |= FileFlags::FILE_FLAGS_EXCLUSIVE_CREATE; } - return make_uniq(QueryContext(context), fs, file_path, flags); + return make_uniq(context.GetContext(), fs, file_path, flags); } struct GlobalWriteCSVData : public GlobalFunctionData { diff --git a/src/duckdb/src/function/table/glob.cpp b/src/duckdb/src/function/table/glob.cpp index f600943e4..b7715f1c5 100644 --- a/src/duckdb/src/function/table/glob.cpp +++ b/src/duckdb/src/function/table/glob.cpp @@ -90,6 +90,8 @@ void GlobTableFunction::RegisterFunction(BuiltinFunctions &set) { TableFunction glob_function("glob", FunctionSignature().AddPositionalOnly("pattern", LogicalType::VARCHAR), GlobFunction, GlobFunctionBind, GlobFunctionInit); glob_function.table_scan_progress = GlobFunctionProgress; + // lists the filesystem at execution time + glob_function.stability = FunctionStability::VOLATILE; set.AddFunction(MultiFileReader::CreateFunctionSet(glob_function)); } diff --git a/src/duckdb/src/function/table/query_function.cpp b/src/duckdb/src/function/table/query_function.cpp index d7abd9e47..fdcdebb04 100644 --- a/src/duckdb/src/function/table/query_function.cpp +++ b/src/duckdb/src/function/table/query_function.cpp @@ -5,10 +5,12 @@ #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/parser/statement/multi_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/planner/binder.hpp" namespace duckdb { -static unique_ptr ParseSubquery(const string &query, ClientContext &context, const string &err_msg) { +static unique_ptr ParseSubquery(const string &query, TableFunctionBindInput &input, ClientContext &context, + const string &err_msg) { Parser parser(context); parser.ParseQuery(query); if (parser.statements.size() != 1) { @@ -16,6 +18,16 @@ static unique_ptr ParseSubquery(const string &query, ClientContext } auto &stmt = parser.statements[0]; + // a parameter that only appears inside the string is invisible to the prepared statement and never gets a value + if (input.binder && input.binder->GetBindingMode() == BindingMode::PREPARE) { + for (auto &entry : stmt->named_param_map) { + if (!input.binder->StatementHasParameter(entry.first)) { + throw BinderException("Prepared statement parameter \"$%s\" only appears inside query(): declare it in " + "the outer statement as well, or use getvariable() to read a variable", + entry.first.GetIdentifierName()); + } + } + } if (stmt->type == StatementType::SELECT_STATEMENT) { // Regular SELECT statement @@ -97,13 +109,13 @@ static unique_ptr QueryBindReplace(ClientContext &context, TableFuncti throw BinderException("Cannot use NULL as function argument"); } auto query = input.inputs[0].ToString(); - auto subquery_ref = ParseSubquery(query, context, "Expected a single SELECT statement"); + auto subquery_ref = ParseSubquery(query, input, context, "Expected a single SELECT statement"); return std::move(subquery_ref); } static unique_ptr TableBindReplace(ClientContext &context, TableFunctionBindInput &input) { auto query = UnionTablesQuery(input); - auto subquery_ref = ParseSubquery(query, context, "Expected a table or a list with tables as input"); + auto subquery_ref = ParseSubquery(query, input, context, "Expected a table or a list with tables as input"); return std::move(subquery_ref); } diff --git a/src/duckdb/src/function/table/range.cpp b/src/duckdb/src/function/table/range.cpp index 5477282db..330d6d90b 100644 --- a/src/duckdb/src/function/table/range.cpp +++ b/src/duckdb/src/function/table/range.cpp @@ -294,7 +294,7 @@ unique_ptr RangeDateTimeCardinality(ClientContext &context, cons return nullptr; } auto &bind_data = bind_data_p->Cast(); - return make_uniq(bind_data.cardinality, bind_data.cardinality); + return make_uniq(bind_data.cardinality); } //! Progress of a timestamp range used as a source (i.e. with a single input row) @@ -351,6 +351,9 @@ struct RangeDateTimeLocalState : public LocalTableFunctionState { bool greater_than_check; bool empty_range = false; + //! Whether the next step went past the timestamp range, which ends the series also when the end lies below + //! -infinity, as INT64_MIN does + bool past_range = false; bool Finished(timestamp_t current_value) const { if (greater_than_check) { @@ -444,6 +447,7 @@ static OperatorResultType RangeDateTimeFunction(ExecutionContext &context, Table GenerateRangeDateTimeParameters(input, state.current_input_row, state); state.initialized_row = true; state.current_state = state.start; + state.past_range = false; if (state.global_state) { state.global_state->Initialize(state.start, state.end); } @@ -457,7 +461,7 @@ static OperatorResultType RangeDateTimeFunction(ExecutionContext &context, Table idx_t size = 0; auto result_data = FlatVector::ScatterWriter(output.data[0]); while (true) { - if (state.Finished(state.current_state)) { + if (state.past_range || state.Finished(state.current_state)) { break; } if (size >= STANDARD_VECTOR_SIZE) { @@ -469,6 +473,7 @@ static OperatorResultType RangeDateTimeFunction(ExecutionContext &context, Table state.current_state)) { // the next value is outside of the timestamp range: the series ends here state.current_state = state.greater_than_check ? timestamp_t::infinity() : timestamp_t::ninfinity(); + state.past_range = true; } } if (size == 0) { @@ -485,10 +490,6 @@ static OperatorResultType RangeDateTimeFunction(ExecutionContext &context, Table } } -static bool RangeIsRepeatable(optional_ptr) { - return true; -} - void RangeTableFunction::RegisterFunction(BuiltinFunctions &set) { TableFunctionSet range("range"); @@ -508,7 +509,6 @@ void RangeTableFunction::RegisterFunction(BuiltinFunctions &set) { range_function.table_scan_progress = RangeFunctionProgress; range_function.in_out_function = RangeFunction; range_function.cardinality = RangeCardinality; - range_function.is_repeatable = RangeIsRepeatable; range_function.parallelism = TableFunctionParallelism::FORCE_SINGLE_THREADED; range_function.return_type = TableFunctionReturnType::SET_RETURNING_FUNCTION; @@ -525,7 +525,6 @@ void RangeTableFunction::RegisterFunction(BuiltinFunctions &set) { range_in_out.table_scan_progress = RangeDateTimeProgress; range_in_out.in_out_function = RangeDateTimeFunction; range_in_out.cardinality = RangeDateTimeCardinality; - range_in_out.is_repeatable = RangeIsRepeatable; range_in_out.parallelism = TableFunctionParallelism::FORCE_SINGLE_THREADED; range_in_out.return_type = TableFunctionReturnType::SET_RETURNING_FUNCTION; range.AddFunction(range_in_out); @@ -545,7 +544,6 @@ void RangeTableFunction::RegisterFunction(BuiltinFunctions &set) { RangeDateTimeLocalInit); generate_series_in_out.table_scan_progress = RangeDateTimeProgress; generate_series_in_out.in_out_function = RangeDateTimeFunction; - generate_series_in_out.is_repeatable = RangeIsRepeatable; generate_series_in_out.parallelism = TableFunctionParallelism::FORCE_SINGLE_THREADED; generate_series_in_out.return_type = TableFunctionReturnType::SET_RETURNING_FUNCTION; generate_series.AddFunction(generate_series_in_out); diff --git a/src/duckdb/src/function/table/read_csv.cpp b/src/duckdb/src/function/table/read_csv.cpp index c0d7ca173..f09127d84 100644 --- a/src/duckdb/src/function/table/read_csv.cpp +++ b/src/duckdb/src/function/table/read_csv.cpp @@ -256,7 +256,7 @@ void BuiltinFunctions::RegisterReadFunctions() { CSVCopyFunction::RegisterFunction(*this); ReadCSVTableFunction::RegisterFunction(*this); AddFunction(MultiFileReader::CreateFunctionSet(ReadDuckDBTableFunction::GetFunction())); - auto &config = DBConfig::GetConfig(*transaction.db); + auto &config = DBConfig::GetConfig(transaction.db); config.replacement_scans.emplace_back(ReadCSVReplacement); config.replacement_scans.emplace_back(ReadDuckDBTableFunction::ReplacementScan); } 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 bcb998737..c5c7b030a 100644 --- a/src/duckdb/src/function/table/system/create_external_resource.cpp +++ b/src/duckdb/src/function/table/system/create_external_resource.cpp @@ -169,8 +169,16 @@ static void CreateExternalResourceFunction(ClientContext &context, TableFunction } auto &bind_data = data_p.bind_data->Cast(); - auto type = ExternalResourceTypeRegistry::Get(context).Lookup(bind_data.type_name); + // An unknown type autoloads the extension known to provide it, like an unknown function or file format does + auto type = + ExternalResourceTypeRegistry::LookupOrAutoload(DatabaseInstance::GetDatabase(context), bind_data.type_name); if (!type) { + auto extension = ExternalResourceTypeRegistry::ProvidingExtension(bind_data.type_name); + if (!extension.empty()) { + throw InvalidInputException("create_external_resource: unknown resource type \"%s\": it is provided by the " + "%s extension, which could not be autoloaded. Try: INSTALL AND LOAD %s;", + bind_data.type_name, extension, extension); + } throw InvalidInputException("create_external_resource: unknown resource type \"%s\"", bind_data.type_name); } // Separate internal connection: the current connection's context lock is held here. @@ -384,6 +392,8 @@ void CreateExternalResourceFun::RegisterFunction(BuiltinFunctions &set) { .Add("timeout_seconds", LogicalType::BIGINT) .Add("poll_interval_seconds", LogicalType::BIGINT); }); + // provisions an external resource per execution + fn.stability = FunctionStability::VOLATILE; set.AddFunction(fn); } @@ -452,12 +462,15 @@ static void DestroyExternalResourceFunction(ClientContext &context, TableFunctio } void DestroyExternalResourceFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("destroy_external_resource", - FunctionSignature() - .AddPositionalOnly("deleter_function", LogicalType::VARCHAR) - .AddPositionalOnly("payload", LogicalType::ANY), - DestroyExternalResourceFunction, DestroyExternalResourceBind, - DestroyExternalResourceInit)); + TableFunction destroy_fun("destroy_external_resource", + FunctionSignature() + .AddPositionalOnly("deleter_function", LogicalType::VARCHAR) + .AddPositionalOnly("payload", LogicalType::ANY), + DestroyExternalResourceFunction, DestroyExternalResourceBind, + DestroyExternalResourceInit); + // tears down an external resource per execution + destroy_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(destroy_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp b/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp index ff7da6c40..e3cac5d54 100644 --- a/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp +++ b/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp @@ -35,8 +35,11 @@ void DuckDBApproxDatabaseCountFunction(ClientContext &context, TableFunctionInpu } void DuckDBApproxDatabaseCountFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_approx_database_count", {}, DuckDBApproxDatabaseCountFunction, - DuckDBApproxDatabaseCountBind, DuckDBApproxDatabaseCountInit)); + TableFunction approx_count_fun("duckdb_approx_database_count", {}, DuckDBApproxDatabaseCountFunction, + DuckDBApproxDatabaseCountBind, DuckDBApproxDatabaseCountInit); + // reads an approximate live count of the attached databases + approx_count_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(approx_count_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_columns.cpp b/src/duckdb/src/function/table/system/duckdb_columns.cpp index 5f6bf7e9d..2428f4fb0 100644 --- a/src/duckdb/src/function/table/system/duckdb_columns.cpp +++ b/src/duckdb/src/function/table/system/duckdb_columns.cpp @@ -5,6 +5,8 @@ #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/view_catalog_entry.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/common/numeric_utils.hpp" +#include "duckdb/function/table/system_catalog_scanner.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/parser/constraints/not_null_constraint.hpp" @@ -22,6 +24,7 @@ struct DuckDBColumnsData : public GlobalTableFunctionState { vector> entries; atomic offset; idx_t column_offset; + SystemCatalogScannerStats stats; }; static unique_ptr DuckDBColumnsBind(ClientContext &context, TableFunctionBindInput &input, @@ -89,18 +92,14 @@ static unique_ptr DuckDBColumnsBind(ClientContext &context, TableF names.emplace_back("generation_expression"); return_types.emplace_back(LogicalType::VARCHAR); - return nullptr; + return SystemCatalogScanner::CreateBindData(names, return_types, "table_name", "table_oid"); } static unique_ptr DuckDBColumnsInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan all the schemas for tables and views and collect them - auto schemas = Catalog::GetAllSchemas(context); - for (auto &schema : schemas) { - schema.get().Scan(context, CatalogType::TABLE_ENTRY, - [&](CatalogEntry &entry) { result->entries.push_back(entry); }); - } + // collect the tables and views that survive the pushed-down filters + result->entries = SystemCatalogScanner::GetEntries(context, input, CatalogType::TABLE_ENTRY, result->stats); return std::move(result); } @@ -324,8 +323,8 @@ void ColumnHelper::WriteColumns(idx_t start_col, idx_t end_col, DataChunk &outpu Value numeric_precision, numeric_scale, numeric_precision_radix; switch (type.id()) { case LogicalTypeId::DECIMAL: - numeric_precision = Value::INTEGER(DecimalType::GetWidth(type)); - numeric_scale = Value::INTEGER(DecimalType::GetScale(type)); + numeric_precision = Value::INTEGER(NumericCast(DecimalType::GetWidth(type))); + numeric_scale = Value::INTEGER(NumericCast(DecimalType::GetScale(type))); numeric_precision_radix = Value::INTEGER(10); break; case LogicalTypeId::HUGEINT: @@ -428,8 +427,14 @@ static double DuckDBColumnsProgress(ClientContext &context, const FunctionData * return 100.0 * static_cast(data.offset) / static_cast(data.entries.size()); } +static void DuckDBColumnsGetMetrics(TableFunctionGetMetricsInput &input) { + SystemCatalogScanner::ReportMetrics(input, input.global_state->Cast().stats); +} + void DuckDBColumnsFun::RegisterFunction(BuiltinFunctions &set) { TableFunction columns("duckdb_columns", {}, DuckDBColumnsFunction, DuckDBColumnsBind, DuckDBColumnsInit); + SystemCatalogScanner::RegisterPushdown(columns); + columns.get_metrics = DuckDBColumnsGetMetrics; columns.table_scan_progress = DuckDBColumnsProgress; set.AddFunction(columns); } diff --git a/src/duckdb/src/function/table/system/duckdb_connection_count.cpp b/src/duckdb/src/function/table/system/duckdb_connection_count.cpp index df30262f7..7b539f59a 100644 --- a/src/duckdb/src/function/table/system/duckdb_connection_count.cpp +++ b/src/duckdb/src/function/table/system/duckdb_connection_count.cpp @@ -38,8 +38,11 @@ void DuckDBConnectionCountFunction(ClientContext &context, TableFunctionInput &d } void DuckDBConnectionCountFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_connection_count", {}, DuckDBConnectionCountFunction, - DuckDBConnectionCountBind, DuckDBConnectionCountInit)); + TableFunction connection_count_fun("duckdb_connection_count", {}, DuckDBConnectionCountFunction, + DuckDBConnectionCountBind, DuckDBConnectionCountInit); + // reads the live connection registry + connection_count_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(connection_count_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_eviction_queues.cpp b/src/duckdb/src/function/table/system/duckdb_eviction_queues.cpp index 085a2a711..1b9c8422b 100644 --- a/src/duckdb/src/function/table/system/duckdb_eviction_queues.cpp +++ b/src/duckdb/src/function/table/system/duckdb_eviction_queues.cpp @@ -68,8 +68,11 @@ void DuckDBEvictionQueuesFunction(ClientContext &context, TableFunctionInput &da } void DuckDBEvictionQueuesFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_eviction_queues", {}, DuckDBEvictionQueuesFunction, DuckDBEvictionQueuesBind, - DuckDBEvictionQueuesInit)); + TableFunction eviction_queues_fun("duckdb_eviction_queues", {}, DuckDBEvictionQueuesFunction, + DuckDBEvictionQueuesBind, DuckDBEvictionQueuesInit); + // reads live buffer manager state + eviction_queues_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(eviction_queues_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_extensions.cpp b/src/duckdb/src/function/table/system/duckdb_extensions.cpp index f03581312..8d0b8aeb9 100644 --- a/src/duckdb/src/function/table/system/duckdb_extensions.cpp +++ b/src/duckdb/src/function/table/system/duckdb_extensions.cpp @@ -256,7 +256,10 @@ void DuckDBExtensionsFunction(ClientContext &context, TableFunctionInput &data_p void DuckDBExtensionsFun::RegisterFunction(BuiltinFunctions &set) { TableFunctionSet functions("duckdb_extensions"); - functions.AddFunction(TableFunction({}, DuckDBExtensionsFunction, DuckDBExtensionsBind, DuckDBExtensionsInit)); + TableFunction extensions_fun({}, DuckDBExtensionsFunction, DuckDBExtensionsBind, DuckDBExtensionsInit); + // reads installed and loaded extension state, which autoloading can change while a query executes + extensions_fun.stability = FunctionStability::VOLATILE; + functions.AddFunction(std::move(extensions_fun)); set.AddFunction(functions); } diff --git a/src/duckdb/src/function/table/system/duckdb_external_file_cache.cpp b/src/duckdb/src/function/table/system/duckdb_external_file_cache.cpp index 8e13a4078..b3df07804 100644 --- a/src/duckdb/src/function/table/system/duckdb_external_file_cache.cpp +++ b/src/duckdb/src/function/table/system/duckdb_external_file_cache.cpp @@ -89,6 +89,8 @@ void DuckDBExternalFileCacheFun::RegisterFunction(BuiltinFunctions &set) { TableFunction function("duckdb_external_file_cache", {}, DuckDBExternalFileCacheFunction, DuckDBExternalFileCacheBind, DuckDBExternalFileCacheInit); function.table_scan_progress = DuckDBExternalFileCacheProgress; + // reads the live cache contents + function.stability = FunctionStability::VOLATILE; set.AddFunction(function); } diff --git a/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp b/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp index b628729ce..a8efa87f1 100644 --- a/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp +++ b/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp @@ -10,8 +10,18 @@ namespace duckdb { -static bool IsActiveGrammarExtension(const ClientContext &context, const string &name) { - for (auto &active : ClientConfig::GetConfig(context).active_grammar_extensions) { +//! The selection these functions read and modify is the effective one, matching the parse path: +//! the session selection when set, otherwise the database-wide default +static shared_ptr> EffectiveGrammarExtensions(const ClientContext &context) { + auto selection = ClientConfig::GetConfig(context).active_grammar_extensions.atomic_load(); + if (!selection) { + selection = DBConfig::GetConfig(context).default_grammar_extensions.atomic_load(); + } + return selection; +} + +static bool ListContainsGrammarExtension(const vector &list, const string &name) { + for (auto &active : list) { if (StringUtil::CIEquals(active, name)) { return true; } @@ -19,6 +29,11 @@ static bool IsActiveGrammarExtension(const ClientContext &context, const string return false; } +static bool IsActiveGrammarExtension(const ClientContext &context, const string &name) { + auto active_list = EffectiveGrammarExtensions(context); + return active_list && ListContainsGrammarExtension(*active_list, name); +} + struct GrammarExtensionData { string name; string description; @@ -121,10 +136,16 @@ static void SetActiveGrammarExtensions(ClientContext &context, const vectorCast().name; - if (IsActiveGrammarExtension(context, name)) { + // one retained snapshot serves both the membership check and the modification, so a + // concurrent change to the database default cannot split the two + auto current = EffectiveGrammarExtensions(context); + if (current && ListContainsGrammarExtension(*current, name)) { return; } - auto extensions = ClientConfig::GetConfig(context).active_grammar_extensions; + vector extensions; + if (current) { + extensions = *current; + } extensions.push_back(name); SetActiveGrammarExtensions(context, extensions); } @@ -132,11 +153,13 @@ static void AddGrammarExtension(ClientContext &context, TableFunctionInput &data //! Removes the grammar extension from the active grammar extensions, keeping the other ones static void RemoveGrammarExtension(ClientContext &context, TableFunctionInput &data, DataChunk &output) { auto &name = data.bind_data->Cast().name; - if (!IsActiveGrammarExtension(context, name)) { + // same single-snapshot discipline as the add path + auto current = EffectiveGrammarExtensions(context); + if (!current || !ListContainsGrammarExtension(*current, name)) { return; } vector extensions; - for (auto &active : ClientConfig::GetConfig(context).active_grammar_extensions) { + for (auto &active : *current) { if (!StringUtil::CIEquals(active, name)) { extensions.push_back(active); } diff --git a/src/duckdb/src/function/table/system/duckdb_live_query_metrics.cpp b/src/duckdb/src/function/table/system/duckdb_live_query_metrics.cpp index 6a39e8667..e0cc4a2ed 100644 --- a/src/duckdb/src/function/table/system/duckdb_live_query_metrics.cpp +++ b/src/duckdb/src/function/table/system/duckdb_live_query_metrics.cpp @@ -61,8 +61,11 @@ static void DuckDBLiveQueryMetricsFunction(ClientContext &context, TableFunction } void DuckDBLiveQueryMetricsFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_live_query_metrics", {}, DuckDBLiveQueryMetricsFunction, - DuckDBLiveQueryMetricsBind, DuckDBLiveQueryMetricsInit)); + TableFunction live_metrics_fun("duckdb_live_query_metrics", {}, DuckDBLiveQueryMetricsFunction, + DuckDBLiveQueryMetricsBind, DuckDBLiveQueryMetricsInit); + // reads live metrics of the executing queries + live_metrics_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(live_metrics_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_log.cpp b/src/duckdb/src/function/table/system/duckdb_log.cpp index 40c9ffdc3..d9415df80 100644 --- a/src/duckdb/src/function/table/system/duckdb_log.cpp +++ b/src/duckdb/src/function/table/system/duckdb_log.cpp @@ -118,6 +118,8 @@ unique_ptr DuckDBLogBindReplace(ClientContext &context, TableFunctionB void DuckDBLogFun::RegisterFunction(BuiltinFunctions &set) { TableFunction logs_fun("duckdb_logs", {}, DuckDBLogFunction, DuckDBLogBind, DuckDBLogInit); logs_fun.bind_replace = DuckDBLogBindReplace; + // the log storage grows while a query executes + logs_fun.stability = FunctionStability::VOLATILE; logs_fun.table_scan_progress = DuckDBLogProgress; logs_fun.GetSignature().WithTypedKwargs( "options", [](TypedKwargs &options) { options.Add("denormalized_table", LogicalType::BOOLEAN); }); 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 1a8f18a8d..d3b0005fe 100644 --- a/src/duckdb/src/function/table/system/duckdb_log_contexts.cpp +++ b/src/duckdb/src/function/table/system/duckdb_log_contexts.cpp @@ -72,6 +72,8 @@ void DuckDBLogContextFun::RegisterFunction(BuiltinFunctions &set) { auto fun = TableFunction("duckdb_log_contexts", {}, DuckDBLogContextFunction, DuckDBLogContextBind, DuckDBLogContextInit); fun.bind_replace = DuckDBLogContextsBindReplace; + // the log storage grows while a query executes + fun.stability = FunctionStability::VOLATILE; set.AddFunction(fun); } diff --git a/src/duckdb/src/function/table/system/duckdb_memory.cpp b/src/duckdb/src/function/table/system/duckdb_memory.cpp index 96b536127..e45584560 100644 --- a/src/duckdb/src/function/table/system/duckdb_memory.cpp +++ b/src/duckdb/src/function/table/system/duckdb_memory.cpp @@ -65,7 +65,10 @@ void DuckDBMemoryFunction(ClientContext &context, TableFunctionInput &data_p, Da } void DuckDBMemoryFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_memory", {}, DuckDBMemoryFunction, DuckDBMemoryBind, DuckDBMemoryInit)); + TableFunction memory_fun("duckdb_memory", {}, DuckDBMemoryFunction, DuckDBMemoryBind, DuckDBMemoryInit); + // reads live buffer manager usage + memory_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(memory_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_prepared_statements.cpp b/src/duckdb/src/function/table/system/duckdb_prepared_statements.cpp index 0ee0f69f0..044f24f62 100644 --- a/src/duckdb/src/function/table/system/duckdb_prepared_statements.cpp +++ b/src/duckdb/src/function/table/system/duckdb_prepared_statements.cpp @@ -109,8 +109,11 @@ void DuckDBPreparedStatementsFunction(ClientContext &context, TableFunctionInput } void DuckDBPreparedStatementsFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_prepared_statements", {}, DuckDBPreparedStatementsFunction, - DuckDBPreparedStatementsBind, DuckDBPreparedStatementsInit)); + TableFunction prepared_fun("duckdb_prepared_statements", {}, DuckDBPreparedStatementsFunction, + DuckDBPreparedStatementsBind, DuckDBPreparedStatementsInit); + // reads the live prepared statement registry + prepared_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(prepared_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_secrets.cpp b/src/duckdb/src/function/table/system/duckdb_secrets.cpp index 81c59b5a3..26b40064b 100644 --- a/src/duckdb/src/function/table/system/duckdb_secrets.cpp +++ b/src/duckdb/src/function/table/system/duckdb_secrets.cpp @@ -139,6 +139,8 @@ void DuckDBSecretsFun::RegisterFunction(BuiltinFunctions &set) { auto fun = TableFunction({}, DuckDBSecretsFunction, DuckDBSecretsBind, DuckDBSecretsInit); fun.GetSignature().WithTypedKwargs("options", [](TypedKwargs &options) { options.Add("redact", LogicalType::BOOLEAN); }); + // the secret manager registry is not transactional + fun.stability = FunctionStability::VOLATILE; functions.AddFunction(fun); set.AddFunction(functions); } diff --git a/src/duckdb/src/function/table/system/duckdb_tables.cpp b/src/duckdb/src/function/table/system/duckdb_tables.cpp index 00b4a00de..fcb4c42e6 100644 --- a/src/duckdb/src/function/table/system/duckdb_tables.cpp +++ b/src/duckdb/src/function/table/system/duckdb_tables.cpp @@ -73,18 +73,14 @@ static unique_ptr DuckDBTablesBind(ClientContext &context, TableFu names.emplace_back("sql"); return_types.emplace_back(LogicalType::VARCHAR); - return SystemCatalogScanner::CreateBindData(names); + return SystemCatalogScanner::CreateBindData(names, return_types, "table_name", "table_oid"); } unique_ptr DuckDBTablesInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan the surviving schemas for tables and collect them - auto schemas = SystemCatalogScanner::GetSchemas(context, input, result->stats); - for (auto &schema : schemas) { - schema.get().Scan(context, CatalogType::TABLE_ENTRY, - [&](CatalogEntry &entry) { result->entries.push_back(entry); }); - }; + // collect the tables that survive the pushed-down filters + result->entries = SystemCatalogScanner::GetEntries(context, input, CatalogType::TABLE_ENTRY, result->stats); return std::move(result); } diff --git a/src/duckdb/src/function/table/system/duckdb_temporary_files.cpp b/src/duckdb/src/function/table/system/duckdb_temporary_files.cpp index 6f7f1742c..db3f53761 100644 --- a/src/duckdb/src/function/table/system/duckdb_temporary_files.cpp +++ b/src/duckdb/src/function/table/system/duckdb_temporary_files.cpp @@ -53,8 +53,11 @@ void DuckDBTemporaryFilesFunction(ClientContext &context, TableFunctionInput &da } void DuckDBTemporaryFilesFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_temporary_files", {}, DuckDBTemporaryFilesFunction, DuckDBTemporaryFilesBind, - DuckDBTemporaryFilesInit)); + TableFunction temp_files_fun("duckdb_temporary_files", {}, DuckDBTemporaryFilesFunction, DuckDBTemporaryFilesBind, + DuckDBTemporaryFilesInit); + // reads the live temporary file list of the buffer manager + temp_files_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(temp_files_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_views.cpp b/src/duckdb/src/function/table/system/duckdb_views.cpp index 8bfbe2d28..54ef6b49c 100644 --- a/src/duckdb/src/function/table/system/duckdb_views.cpp +++ b/src/duckdb/src/function/table/system/duckdb_views.cpp @@ -61,18 +61,14 @@ static unique_ptr DuckDBViewsBind(ClientContext &context, TableFun names.emplace_back("is_bound"); return_types.emplace_back(LogicalType::BOOLEAN); - return SystemCatalogScanner::CreateBindData(names); + return SystemCatalogScanner::CreateBindData(names, return_types, "view_name", "view_oid"); } unique_ptr DuckDBViewsInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan the surviving schemas for views and collect them - auto schemas = SystemCatalogScanner::GetSchemas(context, input, result->stats); - for (auto &schema : schemas) { - schema.get().Scan(context, CatalogType::VIEW_ENTRY, - [&](CatalogEntry &entry) { result->entries.push_back(entry); }); - }; + // collect the views that survive the pushed-down filters + result->entries = SystemCatalogScanner::GetEntries(context, input, CatalogType::VIEW_ENTRY, result->stats); result->column_ids = input.column_indexes; return std::move(result); } diff --git a/src/duckdb/src/function/table/system/duckdb_which_secret.cpp b/src/duckdb/src/function/table/system/duckdb_which_secret.cpp index e4462e1e4..ad25a4031 100644 --- a/src/duckdb/src/function/table/system/duckdb_which_secret.cpp +++ b/src/duckdb/src/function/table/system/duckdb_which_secret.cpp @@ -67,11 +67,14 @@ void DuckDBWhichSecretFunction(ClientContext &context, TableFunctionInput &data_ } void DuckDBWhichSecretFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("which_secret", - FunctionSignature() - .AddPositionalOnly("path", LogicalType::VARCHAR) - .AddPositionalOnly("type", LogicalType::VARCHAR), - DuckDBWhichSecretFunction, DuckDBWhichSecretBind, DuckDBWhichSecretInit)); + TableFunction which_secret_fun("which_secret", + FunctionSignature() + .AddPositionalOnly("path", LogicalType::VARCHAR) + .AddPositionalOnly("type", LogicalType::VARCHAR), + DuckDBWhichSecretFunction, DuckDBWhichSecretBind, DuckDBWhichSecretInit); + // resolves against the live secret registry + which_secret_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(which_secret_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/enable_profiling.cpp b/src/duckdb/src/function/table/system/enable_profiling.cpp index f5979b71e..afe903ab8 100644 --- a/src/duckdb/src/function/table/system/enable_profiling.cpp +++ b/src/duckdb/src/function/table/system/enable_profiling.cpp @@ -147,9 +147,12 @@ void EnableProfilingFun::RegisterFunction(BuiltinFunctions &set) { .Add("mode", LogicalType::VARCHAR)), EnableProfiling, BindEnableProfiling)); + // reconfigures profiling per execution + enable_set.ApplyToFunctions([](TableFunction &function) { function.stability = FunctionStability::VOLATILE; }); set.AddFunction(std::move(enable_set)); auto disable_fun = TableFunction("disable_profiling", {}, DisableProfiling, BindDisableProfiling, nullptr, nullptr); + disable_fun.stability = FunctionStability::VOLATILE; set.AddFunction(std::move(disable_fun)); } diff --git a/src/duckdb/src/function/table/system/external_resources.cpp b/src/duckdb/src/function/table/system/external_resources.cpp index 1d4318a79..a7afe7f93 100644 --- a/src/duckdb/src/function/table/system/external_resources.cpp +++ b/src/duckdb/src/function/table/system/external_resources.cpp @@ -1,57 +1,147 @@ #include "duckdb/function/table/system_functions.hpp" -#include "duckdb/common/error_data.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/map.hpp" -#include "duckdb/common/set.hpp" +#include "duckdb/common/string_util.hpp" #include "duckdb/common/types/value.hpp" -#include "duckdb/main/connection.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/external_resource_type_registry.hpp" #include "duckdb/main/external_resources_manager.hpp" +#include "duckdb/parser/keyword_helper.hpp" +#include "duckdb/parser/parser.hpp" #include "duckdb/parser/qualified_name.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" namespace duckdb { //===--------------------------------------------------------------------===// -// duckdb_external_resources(discover := false) +// duckdb_external_resources(discover := false, type := NULL) // -// Lists the external resources this instance knows about. `discover := false` (the default) returns just -// the locally registered resources (managed = true) and stays local. `discover := true` also calls each -// resource type's `list` callback to discover resources that exist externally, unioning in the ones not -// locally registered (managed = false) — the reconciliation view that feeds REGISTER. +// Lists the external resources this instance knows about. By default that is the local registry: the +// resources registered in this instance (managed = true). `type` restricts the listing to one type. +// +// `discover := true` also lists what exists externally. The call is then rewritten (bind_replace) into +// plain SQL: the registry UNION ALL one `SELECT ... FROM ()` per type with a list callback, +// each tagged with its type name and anti-joined against the registry, so a resource registered here is +// shown once, as managed. A `type` restriction leaves out the other types' branches up front, and a +// `WHERE type = ...` on the result is pushed into the branches by the optimizer, where it folds to a +// constant and drops the branch - so only the callbacks of the types asked for run. //===--------------------------------------------------------------------===// -struct ExternalResourceRow { - string name; // local registration name; empty for a discovered (unmanaged) resource +struct ExternalResourcesParameters { + bool discover = false; + //! The type to list; empty lists every type. string type; - Value handle; - string uri; - string attached_db_type; - bool managed; - string reference; // from the type's `list` callback - string state; // from the type's `list` callback }; +static ExternalResourcesParameters ReadParameters(TableFunctionBindInput &input) { + ExternalResourcesParameters result; + for (auto &np : input.named_parameters) { + if (np.second.IsNull()) { + continue; + } + if (np.first == "discover") { + result.discover = BooleanValue::Get(np.second); + } else if (np.first == "type") { + result.type = StringValue::Get(np.second); + } + } + return result; +} + +static bool MatchesType(const string &type, const string &type_name) { + return type.empty() || type == type_name; +} + +//! The registry scan restricted to `type`, as SQL. +static string RegistryScan(const string &type) { + if (type.empty()) { + return "duckdb_external_resources()"; + } + return "duckdb_external_resources(type := " + Value(type).ToSQLString() + ")"; +} + +static bool RegistryHasType(ClientContext &context, const string &type) { + for (auto &instance : ExternalResourcesManager::Get(context).List()) { + if (instance.type == type) { + return true; + } + } + return false; +} + +static unique_ptr ExternalResourcesBindReplace(ClientContext &context, TableFunctionBindInput &input) { + auto params = ReadParameters(input); + if (!params.discover) { + return nullptr; // the registry scan below + } + vector branches; + branches.push_back("SELECT name, type, managed, NULL::VARCHAR AS state, NULL::VARCHAR AS reference, uri, " + "attached_db_type, handle FROM " + + RegistryScan(params.type)); + if (!params.type.empty()) { + // An unknown type autoloads the extension known to provide it, like an unknown function does + ExternalResourceTypeRegistry::LookupOrAutoload(DatabaseInstance::GetDatabase(context), params.type); + } + bool matched = false; + for (auto &type : ExternalResourceTypeRegistry::Get(context).List()) { + if (!MatchesType(params.type, type.name)) { + continue; + } + matched = true; + if (type.list_function.empty()) { + continue; // a type without a list callback has nothing to discover + } + // Resolved here, in the caller's search path, so the generated SQL does not depend on it. + auto callback = QualifyTableCallback(context, type.list_function); + if (callback.empty()) { + throw InvalidInputException( + "external resource discovery for type \"%s\": the list callback \"%s\" does not exist", type.name, + type.list_function); + } + // The callback returns handle (MAP), reference and state; the rows registered here are left out by handle. + // The callback's rows are aliased with its name, so a binder error about a missing column names it. + auto type_literal = Value(type.name).ToSQLString(); + auto alias = KeywordHelper::WriteQuotedAndEscaped(type.list_function, '"'); + branches.push_back(StringUtil::Format( + "SELECT NULL::VARCHAR AS name, %s AS type, false AS managed, %s.state::VARCHAR AS state, " + "%s.reference::VARCHAR AS reference, NULL::VARCHAR AS uri, NULL::VARCHAR AS attached_db_type, " + "%s.handle::MAP(VARCHAR, VARCHAR) AS handle FROM %s(MAP {}::MAP(VARCHAR, VARCHAR)) AS %s " + "ANTI JOIN %s AS registry ON %s.handle = registry.handle", + type_literal, alias, alias, alias, callback, alias, RegistryScan(type.name), alias)); + } + // A type nothing provides but the registry knows (its extension is not loaded, or it was registered as an + // opaque type) has nothing to discover, like a type without a list callback. A type neither knows is most + // likely a typo, or a missing extension. + if (!matched && !params.type.empty() && !RegistryHasType(context, params.type)) { + auto extension = ExternalResourceTypeRegistry::ProvidingExtension(params.type); + if (!extension.empty()) { + throw InvalidInputException( + "duckdb_external_resources: unknown resource type \"%s\": it is provided by the " + "%s extension, which could not be autoloaded. Try: INSTALL AND LOAD %s;", + params.type, extension, extension); + } + throw InvalidInputException("duckdb_external_resources: unknown resource type \"%s\"", params.type); + } + Parser parser(context); + parser.ParseQuery(StringUtil::Join(branches, " UNION ALL ")); + auto select = unique_ptr_cast(std::move(parser.statements[0])); + return make_uniq(std::move(select)); +} + struct ExternalResourcesBindData : public TableFunctionData { - bool discover = false; + string type; }; struct ExternalResourcesGlobalState : public GlobalTableFunctionState { - ExternalResourcesGlobalState() : offset(0) { - } - vector rows; - idx_t offset; + vector rows; + idx_t offset = 0; }; static unique_ptr ExternalResourcesBind(ClientContext &context, TableFunctionBindInput &input, vector &return_types, vector &names) { auto result = make_uniq(); - for (auto &np : input.named_parameters) { - if (np.first == "discover" && !np.second.IsNull()) { - result->discover = BooleanValue::Get(np.second); - } - } + result->type = ReadParameters(input).type; names.emplace_back("name"); return_types.emplace_back(LogicalType::VARCHAR); @@ -72,117 +162,13 @@ static unique_ptr ExternalResourcesBind(ClientContext &context, Ta return std::move(result); } -//! A stable key for a handle, so a discovered resource can be matched against a locally registered one. -//! Handles are only ever compared within a single type: the durable identity is (type, handle), so a -//! matching handle under a different type is a different resource. -static string HandleKey(const Value &handle) { - return handle.IsNull() ? string() : handle.ToString(); -} - -//! Call a type's `list` callback and append the resources it discovers that are not already locally -//! managed (keyed by handle). A misconfigured type is a hard error: a callback that fails or returns the -//! wrong schema must surface, not be silently dropped as "nothing exists externally". -static void DiscoverExternalResources(ClientContext &context, const ExternalResourceType &type, - const set &managed_handles, vector &rows) { - // Separate internal connection (the current connection's context lock is held here), resolving the - // callback in the type's registration-time search path. - auto callback_con = CreateExternalResourceCallbackConnection(DatabaseInstance::GetDatabase(context), &context); - auto &con = *callback_con; - if (!type.search_path.empty()) { - auto set_res = con.Query("SET search_path = " + Value(type.search_path).ToSQLString()); - if (set_res->HasError()) { - throw InvalidInputException("external resource discovery for type \"%s\": failed to set the type's " - "registration search path: %s", - type.name, set_res->GetError()); - } - } - auto sql = - "SELECT * FROM " + QualifiedName::Parse(type.list_function).ToString() + "(MAP {}::MAP(VARCHAR, VARCHAR))"; - // con.Query reports query errors in-band, but with statement verification active (a global debug setting - // the internal connection inherits) a bind-time failure of the callback is thrown instead. Handle both so - // the wrapped message is identical in every mode. - unique_ptr res; - try { - res = con.Query(sql); - } catch (const std::exception &ex) { - throw InvalidInputException("external resource discovery for type \"%s\": the list callback \"%s\" failed: %s", - type.name, type.list_function, ErrorData(ex).RawMessage()); - } - if (res->HasError()) { - throw InvalidInputException("external resource discovery for type \"%s\": the list callback \"%s\" failed: %s", - type.name, type.list_function, res->GetError()); - } - // Resolve the columns we consume by name; only `handle` is required. - idx_t handle_idx = DConstants::INVALID_INDEX, reference_idx = DConstants::INVALID_INDEX, - state_idx = DConstants::INVALID_INDEX; - for (idx_t c = 0; c < res->GetNames().size(); c++) { - auto col = StringUtil::Lower(res->ColumnName(c).GetIdentifierName()); - if (col == "handle") { - handle_idx = c; - } else if (col == "reference") { - reference_idx = c; - } else if (col == "state") { - state_idx = c; - } - } - if (handle_idx == DConstants::INVALID_INDEX) { - throw InvalidInputException( - "external resource discovery for type \"%s\": the list callback \"%s\" did not return a \"handle\" column", - type.name, type.list_function); - } - auto res_rows = res->Collection().GetRows(); - for (idx_t r = 0; r < res->RowCount(); r++) { - // The handle is a MAP (opaque to us), the same contract create/status enforce - reject anything else - // with a clear message rather than a cast failure deep in the output append. - auto handle = RequireResourceMap(res_rows.GetValue(handle_idx, r), type.list_function, "handle"); - if (managed_handles.count(HandleKey(handle)) > 0) { - continue; // already shown as a locally managed resource of this type - } - ExternalResourceRow row; - row.type = type.name; - row.handle = std::move(handle); - row.managed = false; - if (reference_idx != DConstants::INVALID_INDEX) { - auto ref = res_rows.GetValue(reference_idx, r); - row.reference = ref.IsNull() ? string() : ref.ToString(); - } - if (state_idx != DConstants::INVALID_INDEX) { - auto st = res_rows.GetValue(state_idx, r); - row.state = st.IsNull() ? string() : st.ToString(); - } - rows.push_back(std::move(row)); - } -} - static unique_ptr ExternalResourcesInit(ClientContext &context, TableFunctionInitInput &input) { auto &bind_data = input.bind_data->Cast(); auto result = make_uniq(); - - // Locally registered resources — always shown (managed = true). - // Handles of the locally registered resources, bucketed per type - handles are only comparable within a type. - map> managed_handles; for (auto &instance : ExternalResourcesManager::Get(context).List()) { - ExternalResourceRow row; - row.name = instance.name; - row.type = instance.type; - row.handle = instance.handle; - row.uri = instance.uri; - row.attached_db_type = instance.attached_db_type; - row.managed = true; - managed_handles[instance.type].insert(HandleKey(instance.handle)); - result->rows.push_back(std::move(row)); - } - - // Discovery union: for each type with a `list` callback, add the externally-existing resources that - // are not locally managed. - if (bind_data.discover) { - for (auto &type : ExternalResourceTypeRegistry::Get(context).List()) { - if (type.list_function.empty()) { - continue; - } - // operator[] gives an empty bucket for a type with nothing registered locally - DiscoverExternalResources(context, type, managed_handles[type.name], result->rows); + if (MatchesType(bind_data.type, instance.type)) { + result->rows.push_back(std::move(instance)); } } return std::move(result); @@ -195,14 +181,15 @@ static Value NullableString(const string &s) { static void ExternalResourcesFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { auto &state = data_p.global_state->Cast(); auto empty_handle = Value(LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); + auto null_string = Value(LogicalType::VARCHAR); idx_t count = 0; while (state.offset < state.rows.size() && count < STANDARD_VECTOR_SIZE) { auto &r = state.rows[state.offset++]; - output.data[0].Append(NullableString(r.name)); + output.data[0].Append(Value(r.name)); output.data[1].Append(Value(r.type)); - output.data[2].Append(Value::BOOLEAN(r.managed)); - output.data[3].Append(NullableString(r.state)); - output.data[4].Append(NullableString(r.reference)); + output.data[2].Append(Value::BOOLEAN(true)); + output.data[3].Append(null_string); + output.data[4].Append(null_string); output.data[5].Append(NullableString(r.uri)); output.data[6].Append(NullableString(r.attached_db_type)); output.data[7].Append(r.handle.IsNull() ? empty_handle : r.handle); @@ -213,8 +200,12 @@ static void ExternalResourcesFunction(ClientContext &context, TableFunctionInput void DuckDBExternalResourcesFun::RegisterFunction(BuiltinFunctions &set) { TableFunction fn("duckdb_external_resources", {}, ExternalResourcesFunction, ExternalResourcesBind, ExternalResourcesInit); - fn.GetSignature().WithTypedKwargs("options", - [](TypedKwargs &options) { options.Add("discover", LogicalType::BOOLEAN); }); + fn.bind_replace = ExternalResourcesBindReplace; + fn.GetSignature().WithTypedKwargs("options", [](TypedKwargs &options) { + options.Add("discover", LogicalType::BOOLEAN).Add("type", LogicalType::VARCHAR); + }); + // reads the live external resource registry, and discovery reaches out to external systems + fn.stability = FunctionStability::VOLATILE; set.AddFunction(fn); } @@ -302,6 +293,8 @@ void RegisterExternalResourceFun::RegisterFunction(BuiltinFunctions &set) { .Add("attached_db_type", LogicalType::VARCHAR) .Add("deleter_function", LogicalType::VARCHAR); }); + // writes the external resource registry per execution + fn.stability = FunctionStability::VOLATILE; set.AddFunction(fn); } @@ -353,9 +346,12 @@ static void DeregisterExternalResourceFunction(ClientContext &context, TableFunc } void DeregisterExternalResourceFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction( + TableFunction deregister_fun( "deregister_external_resource", FunctionSignature().AddPositionalOnly("name", LogicalType::VARCHAR), - DeregisterExternalResourceFunction, DeregisterExternalResourceBind, DeregisterExternalResourceInit)); + DeregisterExternalResourceFunction, DeregisterExternalResourceBind, DeregisterExternalResourceInit); + // writes the external resource registry per execution + deregister_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(deregister_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/logging_utils.cpp b/src/duckdb/src/function/table/system/logging_utils.cpp index 4e201c959..08f6c002c 100644 --- a/src/duckdb/src/function/table/system/logging_utils.cpp +++ b/src/duckdb/src/function/table/system/logging_utils.cpp @@ -220,12 +220,16 @@ void EnableLoggingFun::RegisterFunction(BuiltinFunctions &set) { .Add("storage_buffer_size", LogicalType::UBIGINT); }); + // reconfigures the log storage per execution + enable_fun.stability = FunctionStability::VOLATILE; set.AddFunction(enable_fun); auto disable_fun = TableFunction("disable_logging", {}, DisableLogging, BindDisableLogging, nullptr, nullptr); + disable_fun.stability = FunctionStability::VOLATILE; set.AddFunction(disable_fun); auto truncate_fun = TableFunction("truncate_duckdb_logs", {}, TruncateLogs, BindTruncateLogs, nullptr, nullptr); + truncate_fun.stability = FunctionStability::VOLATILE; set.AddFunction(truncate_fun); } diff --git a/src/duckdb/src/function/table/system/pragma_database_size.cpp b/src/duckdb/src/function/table/system/pragma_database_size.cpp index 50873f329..f2efdb8dc 100644 --- a/src/duckdb/src/function/table/system/pragma_database_size.cpp +++ b/src/duckdb/src/function/table/system/pragma_database_size.cpp @@ -101,8 +101,11 @@ void PragmaDatabaseSizeFunction(ClientContext &context, TableFunctionInput &data } void PragmaDatabaseSize::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("pragma_database_size", {}, PragmaDatabaseSizeFunction, PragmaDatabaseSizeBind, - PragmaDatabaseSizeInit)); + TableFunction database_size_fun("pragma_database_size", {}, PragmaDatabaseSizeFunction, PragmaDatabaseSizeBind, + PragmaDatabaseSizeInit); + // reads live storage, WAL, and memory statistics + database_size_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(database_size_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/pragma_metadata_info.cpp b/src/duckdb/src/function/table/system/pragma_metadata_info.cpp index ab958bd66..870d359f7 100644 --- a/src/duckdb/src/function/table/system/pragma_metadata_info.cpp +++ b/src/duckdb/src/function/table/system/pragma_metadata_info.cpp @@ -93,6 +93,8 @@ void PragmaMetadataInfo::RegisterFunction(BuiltinFunctions &set) { metadata_info.AddFunction(TableFunction(FunctionSignature().AddPositionalOnly("database", LogicalType::VARCHAR), PragmaMetadataInfoFunction, PragmaMetadataInfoBind, PragmaMetadataInfoInit)); + // reads live block usage of the database file, which concurrent checkpoints change + metadata_info.ApplyToFunctions([](TableFunction &function) { function.stability = FunctionStability::VOLATILE; }); set.AddFunction(metadata_info); } diff --git a/src/duckdb/src/function/table/system/pragma_table_info.cpp b/src/duckdb/src/function/table/system/pragma_table_info.cpp index 392892e46..73eae26dd 100644 --- a/src/duckdb/src/function/table/system/pragma_table_info.cpp +++ b/src/duckdb/src/function/table/system/pragma_table_info.cpp @@ -178,6 +178,10 @@ static unique_ptr PragmaTableInfoBind(ClientContext &context, Tabl qname = Binder::BindTableName(retriever, qname); auto &entry = Catalog::GetEntry(context, CatalogType::TABLE_ENTRY, qname); Binder::RegisterEntryRead(input.binder, context, entry); + if (entry.type != CatalogType::TABLE_ENTRY || !entry.Cast().IsDuckTable()) { + // views are rebound during execution, and non-native tables are not fixed by the catalog snapshot + input.table_function.stability = FunctionStability::VOLATILE; + } return make_uniq(entry, IS_PRAGMA_TABLE_INFO); } @@ -292,12 +296,13 @@ static void PragmaTableInfoFunction(ClientContext &context, TableFunctionInput & } void PragmaTableInfo::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("pragma_table_info", - FunctionSignature().AddPositionalOnly("table_name", LogicalType::VARCHAR), - PragmaTableInfoFunction, PragmaTableInfoBind, PragmaTableInfoInit)); - set.AddFunction(TableFunction("pragma_show", - FunctionSignature().AddPositionalOnly("table_name", LogicalType::VARCHAR), - PragmaTableInfoFunction, PragmaTableInfoBind, PragmaTableInfoInit)); + TableFunction table_info("pragma_table_info", + FunctionSignature().AddPositionalOnly("table_name", LogicalType::VARCHAR), + PragmaTableInfoFunction, PragmaTableInfoBind, PragmaTableInfoInit); + set.AddFunction(table_info); + TableFunction show("pragma_show", FunctionSignature().AddPositionalOnly("table_name", LogicalType::VARCHAR), + PragmaTableInfoFunction, PragmaTableInfoBind, PragmaTableInfoInit); + set.AddFunction(show); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/pragma_table_sample.cpp b/src/duckdb/src/function/table/system/pragma_table_sample.cpp index 4cc7461e9..3ebf09a80 100644 --- a/src/duckdb/src/function/table/system/pragma_table_sample.cpp +++ b/src/duckdb/src/function/table/system/pragma_table_sample.cpp @@ -93,9 +93,12 @@ static void DuckDBTableSampleFunction(ClientContext &context, TableFunctionInput } void DuckDBTableSample::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_table_sample", - FunctionSignature().AddPositionalOnly("table_name", LogicalType::VARCHAR), - DuckDBTableSampleFunction, DuckDBTableSampleBind, DuckDBTableSampleInit)); + TableFunction table_sample_fun("duckdb_table_sample", + FunctionSignature().AddPositionalOnly("table_name", LogicalType::VARCHAR), + DuckDBTableSampleFunction, DuckDBTableSampleBind, DuckDBTableSampleInit); + // returns a random sample per execution + table_sample_fun.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(table_sample_fun)); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/system_catalog_scanner.cpp b/src/duckdb/src/function/table/system/system_catalog_scanner.cpp index 7635a2505..f3d7b8b03 100644 --- a/src/duckdb/src/function/table/system/system_catalog_scanner.cpp +++ b/src/duckdb/src/function/table/system/system_catalog_scanner.cpp @@ -1,6 +1,7 @@ #include "duckdb/function/table/system_catalog_scanner.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/entry_scan_filters.hpp" #include "duckdb/catalog/schema_scan_filters.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -9,6 +10,7 @@ #include "duckdb/main/client_context.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/main/profiler/profiling_node.hpp" +#include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/optimizer/column_lifetime_analyzer.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/table_filter_set.hpp" @@ -17,20 +19,14 @@ namespace duckdb { +static bool Matches(const optional_idx &idx, idx_t column_index) { + return idx.IsValid() && idx.GetIndex() == column_index; +} + bool SystemCatalogScannerData::IsIdentityColumn(idx_t column_index) const { - if (database_name_idx.IsValid() && database_name_idx.GetIndex() == column_index) { - return true; - } - if (database_oid_idx.IsValid() && database_oid_idx.GetIndex() == column_index) { - return true; - } - if (schema_name_idx.IsValid() && schema_name_idx.GetIndex() == column_index) { - return true; - } - if (schema_oid_idx.IsValid() && schema_oid_idx.GetIndex() == column_index) { - return true; - } - return false; + return Matches(database_name_idx, column_index) || Matches(database_oid_idx, column_index) || + Matches(schema_name_idx, column_index) || Matches(schema_oid_idx, column_index) || + Matches(entry_name_idx, column_index) || Matches(entry_oid_idx, column_index); } unique_ptr SystemCatalogScannerData::Copy() const { @@ -39,36 +35,60 @@ unique_ptr SystemCatalogScannerData::Copy() const { result->database_oid_idx = database_oid_idx; result->schema_name_idx = schema_name_idx; result->schema_oid_idx = schema_oid_idx; + result->entry_name_idx = entry_name_idx; + result->entry_oid_idx = entry_oid_idx; return std::move(result); } bool SystemCatalogScannerData::Equals(const FunctionData &other_p) const { auto &other = other_p.Cast(); return database_name_idx == other.database_name_idx && database_oid_idx == other.database_oid_idx && - schema_name_idx == other.schema_name_idx && schema_oid_idx == other.schema_oid_idx; + schema_name_idx == other.schema_name_idx && schema_oid_idx == other.schema_oid_idx && + entry_name_idx == other.entry_name_idx && entry_oid_idx == other.entry_oid_idx; +} + +// the filters are evaluated against a VARCHAR (names) or BIGINT (oids) value, so only a column of that type can be +// an identity column +static bool IsIdentityType(const LogicalType &type, bool is_oid) { + return type.id() == (is_oid ? LogicalTypeId::BIGINT : LogicalTypeId::VARCHAR); } -unique_ptr SystemCatalogScanner::CreateBindData(const vector &names) { +unique_ptr SystemCatalogScanner::CreateBindData(const vector &names, + const vector &return_types, + const char *entry_name_column, + const char *entry_oid_column) { + D_ASSERT(names.size() == return_types.size()); auto result = make_uniq(); for (idx_t i = 0; i < names.size(); i++) { - if (names[i] == "database_name") { + auto &name = names[i]; + auto &type = return_types[i]; + if (name == "database_name" && IsIdentityType(type, false)) { result->database_name_idx = i; - } else if (names[i] == "database_oid") { + } else if (name == "database_oid" && IsIdentityType(type, true)) { result->database_oid_idx = i; - } else if (names[i] == "schema_name") { + } else if (name == "schema_name" && IsIdentityType(type, false)) { result->schema_name_idx = i; - } else if (names[i] == "schema_oid") { + } else if (name == "schema_oid" && IsIdentityType(type, true)) { result->schema_oid_idx = i; + } else if (entry_name_column && name == entry_name_column && IsIdentityType(type, false)) { + result->entry_name_idx = i; + } else if (entry_oid_column && name == entry_oid_column && IsIdentityType(type, true)) { + result->entry_oid_idx = i; } } return std::move(result); } -// pushdown_expression: accept an expression only if the single column it references is an identity column. +// pushdown_expression: accept an expression only if the single column it references is an identity column and it +// cannot throw. The scan evaluates the expression on the names of all catalogs, schemas and entries, including ones +// the function never returns, so one that fails on such a name raises an error that a filter on the rows would not. static bool PushdownExpression(ClientContext &context, const LogicalGet &get, Expression &expr) { if (!get.bind_data) { return false; } + if (expr.CanThrow()) { + return false; + } auto &data = get.bind_data->Cast(); vector bindings; ColumnLifetimeAnalyzer::ExtractColumnBindings(expr, bindings); @@ -88,58 +108,74 @@ static bool SupportsPushdown(const FunctionData &bind_data, idx_t col_idx) { return bind_data.Cast().IsIdentityColumn(col_idx); } -static bool Matches(const optional_idx &idx, idx_t column_index) { - return idx.IsValid() && idx.GetIndex() == column_index; -} +namespace { -vector> SystemCatalogScanner::GetSchemas(ClientContext &context, - TableFunctionInitInput &input, - SystemCatalogScannerStats &stats) { - if (!input.bind_data || !input.filters || !input.filters->HasFilters()) { - return Catalog::GetAllSchemas(context); +//! The pushed-down filters of a scan, bucketed by identity column. +struct ScanFilters { + optional_ptr database_name; + optional_ptr database_oid; + SchemaScanFilters schema; + EntryScanFilters entry; + + bool HasSchemaLevelFilters() const { + return database_name || database_oid || schema.GetSchemaName() || schema.GetSchemaOid(); } - auto &data = input.bind_data->Cast(); +}; - // filters are keyed by position in input.column_indexes. A filter on any other column is either re-applied above - // the scan by the planner (supports_pushdown_type) or an optional join filter the join re-checks; skip it. - optional_ptr database_name_filter; - optional_ptr database_oid_filter; - SchemaScanFilters schema_filters; +// filters are keyed by position in input.column_indexes. A filter on any other column is either re-applied above +// the scan by the planner (supports_pushdown_type) or an optional join filter the join re-checks; skip it. +ScanFilters CollectFilters(TableFunctionInitInput &input, const SystemCatalogScannerData &data) { + ScanFilters result; + if (!input.filters) { + return result; + } for (auto &entry : *input.filters) { auto &column = input.column_indexes[entry.GetIndex().GetIndex()]; auto column_index = column.GetPrimaryIndex(); if (Matches(data.database_name_idx, column_index)) { - database_name_filter = &entry.Filter(); + result.database_name = &entry.Filter(); } else if (Matches(data.database_oid_idx, column_index)) { - database_oid_filter = &entry.Filter(); + result.database_oid = &entry.Filter(); } else if (Matches(data.schema_name_idx, column_index)) { - schema_filters.schema_name = &entry.Filter(); + result.schema.SetSchemaName(&entry.Filter()); } else if (Matches(data.schema_oid_idx, column_index)) { - schema_filters.schema_oid = &entry.Filter(); + result.schema.SetSchemaOid(&entry.Filter()); + } else if (Matches(data.entry_name_idx, column_index)) { + result.entry.SetName(&entry.Filter()); + } else if (Matches(data.entry_oid_idx, column_index)) { + result.entry.SetOid(&entry.Filter()); } } - if (!database_name_filter && !database_oid_filter && !schema_filters.schema_name && !schema_filters.schema_oid) { + return result; +} + +vector> GetSchemasWithFilters(ClientContext &context, const ScanFilters &filters, + SystemCatalogScannerStats &stats) { + if (!filters.HasSchemaLevelFilters()) { return Catalog::GetAllSchemas(context); } vector> result; auto &db_manager = DatabaseManager::Get(context); + auto &meta_transaction = MetaTransaction::Get(context); for (auto &database : db_manager.GetDatabases(context)) { if (database->GetVisibility() == AttachVisibility::HIDDEN) { continue; // same skip as Catalog::GetAllSchemas } auto &catalog = database->GetCatalog(); stats.catalogs_total++; - if (!SchemaScanFilters::Satisfies(context, database_name_filter, Value(catalog.GetName())) || - !SchemaScanFilters::Satisfies(context, database_oid_filter, + if (!SchemaScanFilters::Satisfies(context, filters.database_name, Value(catalog.GetName())) || + !SchemaScanFilters::Satisfies(context, filters.database_oid, Value::BIGINT(NumericCast(catalog.GetOid())))) { continue; } stats.catalogs_scanned++; - for (auto &schema : catalog.GetSchemasForScan(context, schema_filters)) { + // keep the database alive until the end of the transaction, the returned schemas reference it + meta_transaction.UseDatabase(database); + for (auto &schema : catalog.GetSchemasForScan(context, filters.schema)) { stats.schemas_total++; // the catalog may return schemas the filters reject - if (!schema_filters.Accepts(context, schema.get())) { + if (!filters.schema.Accepts(context, schema.get())) { continue; } stats.schemas_scanned++; @@ -162,11 +198,69 @@ vector> SystemCatalogScanner::GetSchemas(ClientCon return result; } +} // namespace + +vector> SystemCatalogScanner::GetSchemas(ClientContext &context, + TableFunctionInitInput &input, + SystemCatalogScannerStats &stats) { + if (!input.bind_data) { + return Catalog::GetAllSchemas(context); + } + auto &data = input.bind_data->Cast(); + return GetSchemasWithFilters(context, CollectFilters(input, data), stats); +} + +EntryScanFilters SystemCatalogScanner::GetEntryFilters(TableFunctionInitInput &input) { + if (!input.bind_data) { + return EntryScanFilters(); + } + return CollectFilters(input, input.bind_data->Cast()).entry; +} + +vector> SystemCatalogScanner::GetSchemaEntries(ClientContext &context, + SchemaCatalogEntry &schema, CatalogType type, + const EntryScanFilters &filters, + SystemCatalogScannerStats &stats) { + vector> result; + std::function collect = [&](CatalogEntry &entry) { + stats.entries_total++; + // the schema may return entries the filters reject + if (!filters.Accepts(context, entry)) { + return; + } + stats.entries_scanned++; + result.push_back(entry); + }; + SchemaScanInfo info {type, collect, &filters}; + schema.Scan(context, info); + return result; +} + +vector> SystemCatalogScanner::GetEntries(ClientContext &context, TableFunctionInitInput &input, + CatalogType type, SystemCatalogScannerStats &stats) { + vector> result; + if (!input.bind_data) { + for (auto &schema : Catalog::GetAllSchemas(context)) { + schema.get().Scan(context, type, [&](CatalogEntry &entry) { result.push_back(entry); }); + } + return result; + } + auto &data = input.bind_data->Cast(); + auto filters = CollectFilters(input, data); + for (auto &schema : GetSchemasWithFilters(context, filters, stats)) { + auto entries = GetSchemaEntries(context, schema.get(), type, filters.entry, stats); + result.insert(result.end(), entries.begin(), entries.end()); + } + return result; +} + void SystemCatalogScanner::ReportMetrics(TableFunctionGetMetricsInput &input, const SystemCatalogScannerStats &stats) { input.operator_metrics.AddExtraInfo("Catalogs Scanned", to_string(stats.catalogs_scanned) + "/" + to_string(stats.catalogs_total)); input.operator_metrics.AddExtraInfo("Schemas Scanned", to_string(stats.schemas_scanned) + "/" + to_string(stats.schemas_total)); + input.operator_metrics.AddExtraInfo("Entries Scanned", + to_string(stats.entries_scanned) + "/" + to_string(stats.entries_total)); } void SystemCatalogScanner::RegisterPushdown(TableFunction &function) { diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index aa5267a09..d6341077b 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -222,7 +222,7 @@ class DuckIndexScanState : public TableScanGlobalState { l_state->column_ids.push_back(bind_data.table.GetStorageIndex(col_idx)); } l_state->scan_state.Initialize(l_state->column_ids, context.client, input.filters.get()); - local_storage.InitializeScan(storage, l_state->scan_state.local_state, input.filters); + local_storage.InitializeScan(context.client, storage, l_state->scan_state.local_state, input.filters); return std::move(l_state); } diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index a8cce95bd..2ecf50d61 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-alpha52095" +#define DUCKDB_PATCH_VERSION "0-alpha54042" #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-alpha52095" +#define DUCKDB_VERSION "v2.1.0-alpha54042" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "71f47d410f" +#define DUCKDB_SOURCE_ID "45c50f87c4" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/table_function.cpp b/src/duckdb/src/function/table_function.cpp index 38988ab48..5c48c258c 100644 --- a/src/duckdb/src/function/table_function.cpp +++ b/src/duckdb/src/function/table_function.cpp @@ -26,9 +26,9 @@ BaseTableFunction::BaseTableFunction(table_function_t function_, table_function_ pushdown_complex_filter(nullptr), pushdown_expression(nullptr), to_string(nullptr), table_scan_progress(nullptr), get_partition_data(nullptr), get_bind_info(nullptr), get_table_entry(nullptr), projection_expression_pushdown(nullptr), get_multi_file_reader(nullptr), supports_pushdown_type(nullptr), - supports_pushdown_extract(nullptr), is_repeatable(nullptr), get_partition_info(nullptr), - get_partition_stats(nullptr), get_virtual_columns(nullptr), get_row_id_columns(nullptr), set_scan_order(nullptr), - serialize(nullptr), deserialize(nullptr), projection_pushdown(false), filter_pushdown(false), filter_prune(false), + supports_pushdown_extract(nullptr), get_partition_info(nullptr), get_partition_stats(nullptr), + get_virtual_columns(nullptr), get_row_id_columns(nullptr), set_scan_order(nullptr), serialize(nullptr), + deserialize(nullptr), projection_pushdown(false), filter_pushdown(false), filter_prune(false), sampling_pushdown(false), late_materialization(false), return_type(TableFunctionReturnType::TABLE_RETURNING_FUNCTION) { } @@ -105,7 +105,7 @@ BoundTableFunction::BoundTableFunction(shared_ptr function_ get_multi_file_reader = function.get_multi_file_reader; supports_pushdown_type = function.supports_pushdown_type; supports_pushdown_extract = function.supports_pushdown_extract; - is_repeatable = function.is_repeatable; + stability = function.stability; get_partition_info = function.get_partition_info; get_partition_stats = function.get_partition_stats; get_virtual_columns = function.get_virtual_columns; @@ -175,7 +175,7 @@ bool BaseTableFunction::operator==(const BaseTableFunction &rhs) const { get_table_entry == rhs.get_table_entry && projection_expression_pushdown == rhs.projection_expression_pushdown && get_multi_file_reader == rhs.get_multi_file_reader && supports_pushdown_type == rhs.supports_pushdown_type && - is_repeatable == rhs.is_repeatable && get_partition_info == rhs.get_partition_info && + stability == rhs.stability && get_partition_info == rhs.get_partition_info && get_partition_stats == rhs.get_partition_stats && get_virtual_columns == rhs.get_virtual_columns && get_row_id_columns == rhs.get_row_id_columns && serialize == rhs.serialize && deserialize == rhs.deserialize && verify_serialization == rhs.verify_serialization && diff --git a/src/duckdb/src/function/window/window_distinct_aggregator.cpp b/src/duckdb/src/function/window/window_distinct_aggregator.cpp index c3fca7fdb..816562ede 100644 --- a/src/duckdb/src/function/window/window_distinct_aggregator.cpp +++ b/src/duckdb/src/function/window/window_distinct_aggregator.cpp @@ -498,7 +498,11 @@ bool WindowDistinctSortTree::TryNextRun(idx_t &level_idx, idx_t &run_idx) { ++build_level; if (build_level >= tree.size()) { - zipped_tree.tree.clear(); + // Release the levels but keep the vector intact, as other threads may still be reading its size + for (auto &level : zipped_tree.tree) { + auto released_elements = std::move(level.first); + auto released_offsets = std::move(level.second); + } return false; } diff --git a/src/duckdb/src/function/window/window_value_function.cpp b/src/duckdb/src/function/window/window_value_function.cpp index c4a4ba2bc..09cfd8a6b 100644 --- a/src/duckdb/src/function/window/window_value_function.cpp +++ b/src/duckdb/src/function/window/window_value_function.cpp @@ -363,8 +363,8 @@ class WindowLeadLagStreamingState : public WindowExecutorStreamingState { if (offset_expr->HasParameter() || !offset_expr->IsFoldable()) { return false; } - auto offset_value = ExpressionExecutor::EvaluateScalar(client, *offset_expr); - if (offset_value.IsNull()) { + Value offset_value; + if (!ExpressionExecutor::TryEvaluateScalar(client, *offset_expr, offset_value) || offset_value.IsNull()) { return false; } auto bigint_value = offset_value.DefaultTryCastAs(LogicalType::BIGINT); @@ -394,7 +394,10 @@ class WindowLeadLagStreamingState : public WindowExecutorStreamingState { if (default_expr && (default_expr->HasParameter() || !default_expr->IsFoldable())) { return false; } - auto dflt_value = ExpressionExecutor::EvaluateScalar(client, *default_expr); + Value dflt_value; + if (!ExpressionExecutor::TryEvaluateScalar(client, *default_expr, dflt_value)) { + return false; + } auto cast_value = dflt_value.DefaultTryCastAs(wexpr.GetReturnType()); if (!cast_value) { return false; @@ -1087,8 +1090,8 @@ class WindowNthValueStreamingState : public WindowValueStreamingState { if (nth_expr && (nth_expr->HasParameter() || !nth_expr->IsFoldable())) { return false; } - auto nth_value = ExpressionExecutor::EvaluateScalar(client, *nth_expr); - if (nth_value.IsNull()) { + Value nth_value; + if (!ExpressionExecutor::TryEvaluateScalar(client, *nth_expr, nth_value) || nth_value.IsNull()) { return false; } auto bigint_value = nth_value.DefaultTryCastAs(LogicalType::BIGINT); diff --git a/src/duckdb/src/include/duckdb/catalog/catalog.hpp b/src/duckdb/src/include/duckdb/catalog/catalog.hpp index 350979e0f..afda13719 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog.hpp @@ -47,7 +47,7 @@ struct CreateTypeInfo; struct CreateTableInfo; struct DatabaseSize; struct MetadataBlockInfo; -struct SchemaScanFilters; +class SchemaScanFilters; class AttachedDatabase; class ClientContext; @@ -523,6 +523,7 @@ class Catalog { AttachedDatabase &db; //! (optionally) a default table to query for `SELECT * FROM ;` + mutable mutex default_table_lock; Identifier default_table; Identifier default_table_schema; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp index 32a9f30ef..a0a151a53 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp @@ -67,6 +67,7 @@ class DuckSchemaEntry : public SchemaCatalogEntry { //! Create a nested schema inside this schema optional_ptr CreateSchema(CatalogTransaction transaction, CreateSchemaInfo &info); void Alter(CatalogTransaction transaction, AlterInfo &info) override; + using SchemaCatalogEntry::Scan; void Scan(ClientContext &context, CatalogType type, const std::function &callback) override; void Scan(CatalogTransaction transaction, CatalogType type, const std::function &callback) override; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp index eeace24d5..70bd7c9a2 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp @@ -37,6 +37,14 @@ struct CreateCopyFunctionInfo; struct CreateTypeInfo; struct DropInfo; +class EntryScanFilters; + +//! Parameters of a schema scan: the entry type, the per-entry callback and any filters pushed down on the entries. +struct SchemaScanInfo { + CatalogType type; + const std::function &callback; + optional_ptr filter; +}; //! A schema in the catalog class SchemaCatalogEntry : public InCatalogEntry { @@ -71,6 +79,9 @@ class SchemaCatalogEntry : public InCatalogEntry { const std::function &callback); //! Scan the specified catalog set, invoking the callback method for every committed entry virtual void Scan(CatalogType type, const std::function &callback) = 0; + //! Scan the entries of `info.type`, filtered by `info.filter`. An override may return a superset of the matches, so + //! callers that need exact results re-check them. + DUCKDB_API virtual void Scan(ClientContext &context, SchemaScanInfo &info); //! Visit this schema and its descendants in depth-first, parent-before-child order. DUCKDB_API void ScanSchemaTree(CatalogTransaction transaction, const std::function &callback); diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp index 2ecf6e73e..80c3c546b 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp @@ -22,6 +22,8 @@ struct SequenceValue { SequenceCatalogEntry *entry; uint64_t usage_count; int64_t counter; + bool has_last_value; + int64_t last_value; }; struct SequenceData { diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_transaction.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_transaction.hpp index 1f01aa4a6..64dc5c6c9 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_transaction.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_transaction.hpp @@ -15,6 +15,7 @@ namespace duckdb { class Catalog; class ClientContext; +class Context; class DatabaseInstance; class Transaction; @@ -22,7 +23,7 @@ struct CatalogTransaction { CatalogTransaction(Catalog &catalog, ClientContext &context); CatalogTransaction(DatabaseInstance &db, transaction_t transaction_id_p, VisibilityBound visibility_bound_p); - optional_ptr db; + DatabaseInstance &db; optional_ptr context; optional_ptr transaction; SnapshotView view; @@ -36,6 +37,8 @@ struct CatalogTransaction { ClientContext &GetContext(); static CatalogTransaction GetSystemCatalogTransaction(ClientContext &context); + //! The system transaction of the client of the services, or of the database if they do not belong to a client + static CatalogTransaction GetSystemCatalogTransaction(Context &context); static CatalogTransaction GetSystemTransaction(DatabaseInstance &db); }; diff --git a/src/duckdb/src/include/duckdb/catalog/entry_scan_filters.hpp b/src/duckdb/src/include/duckdb/catalog/entry_scan_filters.hpp new file mode 100644 index 000000000..2fa48d291 --- /dev/null +++ b/src/duckdb/src/include/duckdb/catalog/entry_scan_filters.hpp @@ -0,0 +1,43 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/catalog/entry_scan_filters.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/common.hpp" +#include "duckdb/common/optional_ptr.hpp" + +namespace duckdb { +class CatalogEntry; +class ClientContext; +class TableFilter; + +//! Filters pushed into a system catalog scan on the entry identity columns (e.g. table_name / table_oid). +class EntryScanFilters { +public: + optional_ptr GetName() const { + return name; + } + optional_ptr GetOid() const { + return oid; + } + void SetName(optional_ptr filter) { + name = filter; + } + void SetOid(optional_ptr filter) { + oid = filter; + } + + //! Whether the entry satisfies every filter present; a missing filter accepts everything. + bool Accepts(ClientContext &context, const CatalogEntry &entry) const; + +private: + optional_ptr name; + optional_ptr oid; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/catalog/schema_scan_filters.hpp b/src/duckdb/src/include/duckdb/catalog/schema_scan_filters.hpp index f0c6f09c2..6c9e7961b 100644 --- a/src/duckdb/src/include/duckdb/catalog/schema_scan_filters.hpp +++ b/src/duckdb/src/include/duckdb/catalog/schema_scan_filters.hpp @@ -17,15 +17,30 @@ class SchemaCatalogEntry; class TableFilter; class Value; -//! Filters pushed into a system catalog scan (duckdb_tables, duckdb_views) on the schema identity columns. -struct SchemaScanFilters { - optional_ptr schema_name; - optional_ptr schema_oid; +//! Filters pushed into a system catalog scan on the schema identity columns (schema_name / schema_oid). +class SchemaScanFilters { +public: + optional_ptr GetSchemaName() const { + return schema_name; + } + optional_ptr GetSchemaOid() const { + return schema_oid; + } + void SetSchemaName(optional_ptr filter) { + schema_name = filter; + } + void SetSchemaOid(optional_ptr filter) { + schema_oid = filter; + } //! Whether the schema satisfies every filter present. bool Accepts(ClientContext &context, const SchemaCatalogEntry &schema) const; //! Whether a single filter accepts the value; a missing filter accepts everything. static bool Satisfies(ClientContext &context, optional_ptr filter, const Value &value); + +private: + optional_ptr schema_name; + optional_ptr schema_oid; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/allocator.hpp b/src/duckdb/src/include/duckdb/common/allocator.hpp index 4cca0e95b..c94fbe5ed 100644 --- a/src/duckdb/src/include/duckdb/common/allocator.hpp +++ b/src/duckdb/src/include/duckdb/common/allocator.hpp @@ -19,6 +19,7 @@ class Allocator; class AttachedDatabase; class ClientContext; class DatabaseInstance; +class Context; class ExecutionContext; class ThreadContext; @@ -222,6 +223,7 @@ class BufferAllocator : public Allocator { //! Allocate with a huge-page hint, retaining the matching release path. DUCKDB_API HugeAllocation AllocateHuge(idx_t size); DUCKDB_API static BufferAllocator &Get(ClientContext &context); + DUCKDB_API static BufferAllocator &Get(Context &context); DUCKDB_API static BufferAllocator &Get(DatabaseInstance &db); DUCKDB_API static BufferAllocator &Get(AttachedDatabase &db); diff --git a/src/duckdb/src/include/duckdb/common/bind_helpers.hpp b/src/duckdb/src/include/duckdb/common/bind_helpers.hpp index b0880a79b..ce9c063be 100644 --- a/src/duckdb/src/include/duckdb/common/bind_helpers.hpp +++ b/src/duckdb/src/include/duckdb/common/bind_helpers.hpp @@ -22,6 +22,7 @@ struct TableIndex; class Binder; Value ConvertVectorToValue(vector set); +idx_t ParseBytesArg(const Identifier &name, const Value &arg); vector ParseColumnList(const vector &set, const vector &names, const Identifier &option_name); vector ParseColumnList(const Value &value, const vector &names, const Identifier &option_name); vector ParseColumnsOrdered(const vector &set, const vector &names, diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 220496956..29bb9ce03 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -472,6 +472,8 @@ enum class PipelineBroadcastExchangeScanMode : uint8_t; enum class PipelineInputMode : uint8_t; +enum class PipelineScheduleGraph : uint8_t; + enum class PipelineScheduleMode : uint8_t; enum class PipelineScheduleStageType : uint8_t; @@ -510,6 +512,10 @@ enum class RecursiveCTEPipelineMetricType : uint8_t; enum class RecursiveCTESourcePhase : uint8_t; +enum class RecursiveCTEStageStep : uint8_t; + +enum class RecursiveEpochResult : uint8_t; + enum class RecursiveProbeSidePreference : uint8_t; enum class RegexMatchOperatorSemantics : uint8_t; @@ -646,6 +652,8 @@ enum class TransactionModifierType : uint8_t; enum class TransactionType : uint8_t; +enum class TransformChildKind : uint8_t; + enum class TriggerEventType : uint8_t; enum class TriggerForEach : uint8_t; @@ -1357,6 +1365,9 @@ const char* EnumUtil::ToChars(PipelineBroadca template<> const char* EnumUtil::ToChars(PipelineInputMode value); +template<> +const char* EnumUtil::ToChars(PipelineScheduleGraph value); + template<> const char* EnumUtil::ToChars(PipelineScheduleMode value); @@ -1414,6 +1425,12 @@ const char* EnumUtil::ToChars(RecursiveCTEPipeli template<> const char* EnumUtil::ToChars(RecursiveCTESourcePhase value); +template<> +const char* EnumUtil::ToChars(RecursiveCTEStageStep value); + +template<> +const char* EnumUtil::ToChars(RecursiveEpochResult value); + template<> const char* EnumUtil::ToChars(RecursiveProbeSidePreference value); @@ -1618,6 +1635,9 @@ const char* EnumUtil::ToChars(TransactionModifierType v template<> const char* EnumUtil::ToChars(TransactionType value); +template<> +const char* EnumUtil::ToChars(TransformChildKind value); + template<> const char* EnumUtil::ToChars(TriggerEventType value); @@ -2354,6 +2374,9 @@ PipelineBroadcastExchangeScanMode EnumUtil::FromString PipelineInputMode EnumUtil::FromString(const char *value); +template<> +PipelineScheduleGraph EnumUtil::FromString(const char *value); + template<> PipelineScheduleMode EnumUtil::FromString(const char *value); @@ -2411,6 +2434,12 @@ RecursiveCTEPipelineMetricType EnumUtil::FromString RecursiveCTESourcePhase EnumUtil::FromString(const char *value); +template<> +RecursiveCTEStageStep EnumUtil::FromString(const char *value); + +template<> +RecursiveEpochResult EnumUtil::FromString(const char *value); + template<> RecursiveProbeSidePreference EnumUtil::FromString(const char *value); @@ -2615,6 +2644,9 @@ TransactionModifierType EnumUtil::FromString(const char template<> TransactionType EnumUtil::FromString(const char *value); +template<> +TransformChildKind EnumUtil::FromString(const char *value); + template<> TriggerEventType EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp index 953da94c5..09320feeb 100644 --- a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp @@ -63,7 +63,9 @@ enum class OptimizerType : uint32_t { REDUNDANT_ORDER_KEYS = 46, DISJUNCTIVE_JOIN_REWRITER = 47, REDUNDANT_ORDER = 48, - WINDOW_JOIN_PUSHDOWN = 49 + WINDOW_JOIN_PUSHDOWN = 49, + SELF_JOIN_AGGREGATE = 50, + SCALAR_AGGREGATE_MERGE = 51 }; string OptimizerTypeToString(OptimizerType type); diff --git a/src/duckdb/src/include/duckdb/common/file_opener.hpp b/src/duckdb/src/include/duckdb/common/file_opener.hpp index 746f5b1d5..e3d01fb78 100644 --- a/src/duckdb/src/include/duckdb/common/file_opener.hpp +++ b/src/duckdb/src/include/duckdb/common/file_opener.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/open_file_info.hpp" #include "duckdb/common/string.hpp" #include "duckdb/common/winapi.hpp" #include "duckdb/main/setting_info.hpp" @@ -16,13 +17,23 @@ namespace duckdb { struct CatalogTransaction; class SecretManager; -class ClientContext; +class Context; class HTTPUtil; class Value; class Logger; +//! The file an open, listing or request is for struct FileOpenerInfo { - string file_path; + FileOpenerInfo() = default; + FileOpenerInfo(string path) // NOLINT: allow implicit conversion from a path + : file(std::move(path)) { + } + FileOpenerInfo(OpenFileInfo file_p) // NOLINT: allow implicit conversion from a file + : file(std::move(file_p)) { + } + + //! The file, with the options it is opened with, e.g. the secret to open it with + OpenFileInfo file; }; //! Abstract type that provide client-specific context to FileSystem. @@ -34,13 +45,13 @@ class FileOpener { virtual SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result, FileOpenerInfo &info); virtual SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) = 0; - virtual optional_ptr TryGetClientContext() = 0; + virtual Context &TryGetContext() = 0; virtual optional_ptr TryGetDatabase() = 0; virtual HTTPUtil &GetHTTPUtil() = 0; DUCKDB_API virtual Logger &GetLogger() const = 0; DUCKDB_API static unique_ptr TryGetCatalogTransaction(optional_ptr opener); - DUCKDB_API static optional_ptr TryGetClientContext(optional_ptr opener); + DUCKDB_API static optional_ptr TryGetContext(optional_ptr opener); DUCKDB_API static optional_ptr TryGetDatabase(optional_ptr opener); DUCKDB_API static optional_ptr TryGetSecretManager(optional_ptr opener); DUCKDB_API static SettingLookupResult TryGetCurrentSetting(optional_ptr opener, const Identifier &key, diff --git a/src/duckdb/src/include/duckdb/common/file_system.hpp b/src/duckdb/src/include/duckdb/common/file_system.hpp index 76047c611..0ee66ec7b 100644 --- a/src/duckdb/src/include/duckdb/common/file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/file_system.hpp @@ -391,6 +391,7 @@ class FileSystem { DUCKDB_API static bool IsRemoteFile(const string &path, string &extension); DUCKDB_API virtual void SetDisabledFileSystems(const vector &names); + DUCKDB_API virtual vector GetDisabledFileSystems(); DUCKDB_API virtual bool SubSystemIsDisabled(const string &name); //! Check if the filesystem that would handle this path is disabled DUCKDB_API virtual bool IsDisabledForPath(const string &path); diff --git a/src/duckdb/src/include/duckdb/common/logical_type_info.hpp b/src/duckdb/src/include/duckdb/common/logical_type_info.hpp index 6d318fdb5..7619519b2 100644 --- a/src/duckdb/src/include/duckdb/common/logical_type_info.hpp +++ b/src/duckdb/src/include/duckdb/common/logical_type_info.hpp @@ -18,10 +18,10 @@ namespace duckdb { class ParsedExpression; struct DecimalTypeInfo : public LogicalTypeInfo { - DecimalTypeInfo(uint8_t width_p, uint8_t scale_p); + DecimalTypeInfo(uint32_t width_p, uint32_t scale_p); - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; public: void Serialize(Serializer &serializer) const override; diff --git a/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp b/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp index 2b205d6f5..2b2762650 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp @@ -173,6 +173,8 @@ class BaseUnionData { return optional_idx(); } virtual unique_ptr GetStatistics(ClientContext &context, const Identifier &name); + DUCKDB_API virtual unique_ptr GetVirtualColumnStatistics(ClientContext &context, + column_t virtual_column_id); public: template diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp index 0e446aa63..5985047ed 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp @@ -48,6 +48,10 @@ struct MultiFileReaderInterface { unique_ptr options) = 0; virtual void BindReader(ClientContext &context, vector &return_types, vector &names, MultiFileBindData &bind_data) = 0; + //! After a custom MultiFileReader::Bind, open the files for their statistics (maximum_files_for_stats) with the + //! reader options, which only the interface holds + virtual void ReadFilesForStatistics(ClientContext &context, MultiFileBindData &bind_data) { + } //! Combine the schemas of a set of files that were bound individually into a single schema //! The default implementation combines the return types of the files by name virtual void CombineSchemas(ClientContext &context, const vector> &union_data, @@ -170,6 +174,7 @@ class MultiFileFunction : public TableFunction { } result->multi_file_reader->BindOptions(result->file_options, *result->file_list, result->types, result->names, result->reader_bind); + interface.ReadFilesForStatistics(context, *result); bound_on_first_file = false; } else { result->file_options.AutoDetectHivePartitioning(*result->file_list, context); @@ -840,12 +845,16 @@ class MultiFileFunction : public TableFunction { if (file_list.IsEmpty()) { result->readers.clear(); - } else if (!bind_data.union_readers.empty()) { - for (auto &reader : bind_data.union_readers) { - result->readers.push_back(make_uniq(reader)); - } - if (result->readers.size() != file_list.GetTotalFileCount()) { - result->readers.clear(); + } else if (!bind_data.union_readers.empty() && + (bind_data.union_readers.size() == 1 + ? bind_data.union_readers[0]->GetFileName() == file_list.GetFirstFile().path + : bind_data.union_readers.size() == file_list.GetTotalFileCount())) { + for (auto &file : bind_data.union_readers) { + if (bind_data.initial_reader && bind_data.initial_reader->GetFileName() == file->GetFileName()) { + result->readers.push_back(make_uniq(std::move(bind_data.initial_reader))); + } else { + result->readers.push_back(make_uniq(file)); + } } } else if (bind_data.initial_reader) { // we can only use the initial reader if it was constructed from the first file @@ -1144,8 +1153,8 @@ class MultiFileFunction : public TableFunction { auto &bind_data = input.bind_data->Cast(); auto &column_index = input.column_index; - if (!bind_data.initial_reader) { - // no reader + optional_ptr file = bind_data.union_readers.empty() ? nullptr : bind_data.union_readers[0].get(); + if (!file && !bind_data.initial_reader) { return nullptr; } // scanning single file and we have the metadata read already @@ -1161,8 +1170,10 @@ class MultiFileFunction : public TableFunction { if (bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES) { return nullptr; } - return bind_data.initial_reader->GetVirtualColumnStatistics( - context, MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER); + return bind_data.initial_reader + ? bind_data.initial_reader->GetVirtualColumnStatistics( + context, MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER) + : file->GetVirtualColumnStatistics(context, MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER); } // a hive partitioning column overrides any file column of the same name - the statistics stored in the @@ -1192,24 +1203,56 @@ class MultiFileFunction : public TableFunction { } // NOTE: we do not want to parse the file metadata for the sole purpose of getting column statistics const bool multiple_files = bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES; - if (multiple_files && !bind_data.file_options.union_by_name) { - // multiple files, but no union_by_name: no luck! + // multiple files: only if every file was opened at bind (union_by_name, maximum_sample_files or + // maximum_files_for_stats) + if (multiple_files && bind_data.union_readers.size() != bind_data.file_list->GetTotalFileCount()) { return nullptr; } - auto result = bind_data.initial_reader->GetStatistics(context, col_name); - if (result && !bind_data.file_options.bound_schema.empty() && - !bind_data.MatchesPhysicalColumn(primary_index, col_name, result->GetType())) { - // Check the whole root before interpreting an extracted child's positional statistics. - return nullptr; - } - if (result && multiple_files) { - for (idx_t i = 1; i < bind_data.union_readers.size(); i++) { - auto &union_reader = *bind_data.union_readers[i]; - auto stats = union_reader.GetStatistics(context, col_name); - if (!stats || result->GetType() != stats->GetType()) { + auto get_statistics = [&](BaseUnionData &reader) { + unique_ptr stats; + try { + stats = reader.GetStatistics(context, col_name); + } catch (std::exception &ex) { + // statistics that cannot be decoded just mean there are none - the data itself may still read fine + if (ErrorData(ex).Type() == ExceptionType::INTERRUPT) { + throw; + } + return unique_ptr(); + } + if (stats && (stats->GetType() != bind_data.types[primary_index] || + (!bind_data.file_options.bound_schema.empty() && + !bind_data.MatchesPhysicalColumn(primary_index, col_name, stats->GetType())))) { + // Positional child statistics require the physical root to match the scan's output layout. + return unique_ptr(); + } + return stats; + }; + unique_ptr result; + if (multiple_files) { + for (auto &union_reader : bind_data.union_readers) { + auto rows = union_reader->TryGetCardinalityEstimate(); + if (rows.IsValid() && rows.GetIndex() == 0) { + // an empty file has no statistics, and no values the merged bounds must cover + continue; + } + auto stats = get_statistics(*union_reader); + if (!stats) { return nullptr; } - result->Merge(*stats); + if (!result) { + result = std::move(stats); + } else { + result->Merge(*stats); + } + } + } else { + result = bind_data.initial_reader ? bind_data.initial_reader->GetStatistics(context, col_name) + : file->GetStatistics(context, col_name); + if (result && (result->GetType() != bind_data.types[primary_index] || + (!bind_data.file_options.bound_schema.empty() && + !bind_data.MatchesPhysicalColumn(primary_index, col_name, result->GetType())))) { + // Positional child statistics require the physical root to match the scan's output layout. + return nullptr; } } if (!result || !column_index.IsPushdownExtract()) { @@ -1284,14 +1327,19 @@ class MultiFileFunction : public TableFunction { static unique_ptr MultiFileCardinality(ClientContext &context, const FunctionData *bind_data) { auto &data = bind_data->Cast(); if (IsEmptyResult(data)) { - return make_uniq(idx_t(0)); + return make_uniq(idx_t(0), idx_t(0)); } auto file_list_cardinality_estimate = data.file_list->GetCardinality(context); if (file_list_cardinality_estimate) { return file_list_cardinality_estimate; } - if (data.file_options.union_by_name) { - // for UNION BY NAME - check if we can get a cardinality estimate from the (already opened) union readers + // a single file opened at bind for its schema keeps the format's own estimate (e.g. explicit_cardinality); + // files opened for their statistics alone (ReadFilesForStatistics after a custom Bind) are counted here + const bool opened_for_statistics = + data.file_options.union_by_name || data.union_readers.size() > 1 || !data.initial_reader; + if (!data.union_readers.empty() && opened_for_statistics && + data.union_readers.size() == data.file_list->GetTotalFileCount()) { + // check if we can get a cardinality estimate from the (already opened) union readers bool has_exact_cardinality = true; idx_t cardinality = 0; for (auto &union_data : data.union_readers) { @@ -1303,7 +1351,15 @@ class MultiFileFunction : public TableFunction { cardinality += file_cardinality.GetIndex(); } if (has_exact_cardinality) { - return make_uniq(cardinality); + // the files' totals are the estimate; the maximum is what the format proves the scan reads, as a + // footer's total is not checked against the rows it holds + auto result = make_uniq(cardinality); + auto format_stats = data.interface->GetCardinality(context, data, data.union_readers.size()); + if (format_stats && format_stats->has_max_cardinality) { + result->has_max_cardinality = true; + result->max_cardinality = format_stats->max_cardinality; + } + return result; } } // get the file count - for >500 files we allow an estimate diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp index 33e4d8953..75fe4216b 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp @@ -18,6 +18,7 @@ namespace duckdb { class MultiFileList; class NodeStatistics; +class Context; class LogicalGet; class TableFilterSet; struct MultiFileDynamicPushdownInfo; @@ -102,6 +103,10 @@ class MultiFileList { OpenFileInfo GetFirstFile() const; //! Syntactic sugar for GetExpandResult() == FileExpandResult::NO_FILES bool IsEmpty() const; + //! The average row count of the files that are available without further I/O (FileIsAvailable), each estimated + //! from the "file_size" its extended info carries at bytes_per_row, and at least one row. Invalid when there is no + //! such file, or when one of them has no file_size + optional_idx EstimateRowsPerFile(idx_t bytes_per_row) const; //! Virtual functions for subclasses public: @@ -165,7 +170,7 @@ class SimpleMultiFileList : public MultiFileList { //! Lazily expanded MultiFileList class LazyMultiFileList : public MultiFileList { public: - explicit LazyMultiFileList(optional_ptr context); + explicit LazyMultiFileList(optional_ptr context); vector GetAllFiles() const override; FileExpandResult GetExpandResult() const override; @@ -188,7 +193,7 @@ class LazyMultiFileList : public MultiFileList { mutable vector expanded_files; //! Whether or not all files have been expanded mutable bool all_files_expanded = false; - optional_ptr context; + optional_ptr services; }; //! MultiFileList that takes a list of globs and resolves all of the globs lazily into files diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp index 1de90627f..1cf970bc1 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp @@ -30,6 +30,9 @@ struct MultiFileOptions { //! The maximum number of files that are opened to determine the schema - the schemas of the sampled files are //! combined into one. NumericLimits::Maximum() samples every file idx_t maximum_sample_files = 1; + //! A scan of at most this many files (0: none) opens all of them at bind for their exact row count and merged + //! column statistics, without changing the schema. Not serialized + idx_t maximum_files_for_stats = 0; //! Whether the schemas of the sampled files are combined into a union of their columns - files are then allowed //! to be missing columns of the combined schema, the way they are with union_by_name. This is how the schemas of //! sampled files are combined unless the reader combines them itself diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp index 0c03bfd79..cc6b12971 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp @@ -222,6 +222,10 @@ struct MultiFileReader { MultiFileReaderBindData BindFirstReader(ClientContext &context, vector &return_types, vector &names, MultiFileList &files, MultiFileBindData &result, BaseFileReaderOptions &options, MultiFileOptions &file_options); + //! With "maximum_files_for_stats", open every file of a small scan for its row count and column statistics. After + //! a custom Bind no file has been opened yet, and all of them are read + void ReadFilesForStatistics(ClientContext &context, MultiFileList &files, MultiFileBindData &result, + BaseFileReaderOptions &options, MultiFileOptions &file_options); //! Bind the schema on the first "maximum_sample_files" files, combining the schemas of the sampled files MultiFileReaderBindData BindSampledReader(ClientContext &context, vector &return_types, vector &names, MultiFileList &files, diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp index 7ccf59ddd..5e72afdc3 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp @@ -89,7 +89,8 @@ struct MultiFileBindData : public TableFunctionData { //! Table column names - set when using COPY tbl FROM file.parquet vector table_columns; shared_ptr initial_reader; - // The union readers are created (when the union_by_name option is on) during binding + //! Bound file descriptions, retained independently of consumable readers. + //! Contains the first file or all files opened for schema discovery. vector> union_readers; void Initialize(shared_ptr reader) { 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 7cb9fd84f..11aa595c4 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 @@ -239,6 +239,7 @@ class TableFunctionUnionData : public BaseUnionData { return cardinality; } unique_ptr GetStatistics(ClientContext &context, const Identifier &name) override; + unique_ptr GetVirtualColumnStatistics(ClientContext &context, column_t virtual_column_id) override; }; //! Reads a single file by binding and executing the wrapped table function over that file @@ -415,6 +416,7 @@ class TableFunctionMultiFileWrapper : public MultiFileReaderInterface { MultiFileBindData &bind_data) override; void CombineSchemas(ClientContext &context, const vector> &union_data, bool union_by_name, vector &return_types, vector &names) override; + void ReadFilesForStatistics(ClientContext &context, MultiFileBindData &bind_data) override; void FinalizeBindData(MultiFileBindData &multi_file_data) override; void GetVirtualColumns(ClientContext &context, MultiFileBindData &bind_data, virtual_column_map_t &result) override; unique_ptr InitializeGlobalState(ClientContext &context, MultiFileBindData &bind_data, diff --git a/src/duckdb/src/include/duckdb/common/multi_file/union_by_name.hpp b/src/duckdb/src/include/duckdb/common/multi_file/union_by_name.hpp index 5b24d5cb6..13bcfe59b 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/union_by_name.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/union_by_name.hpp @@ -14,6 +14,7 @@ #include "duckdb/common/helper.hpp" #include "duckdb/common/multi_file/base_file_reader.hpp" #include "duckdb/common/multi_file/multi_file_options.hpp" +#include "duckdb/parallel/task_executor.hpp" namespace duckdb { struct MultiFileReader; @@ -30,6 +31,14 @@ class UnionByName { UnionCols(ClientContext &context, const vector &files, vector &union_col_types, vector &union_col_names, BaseFileReaderOptions &options, MultiFileOptions &file_options, MultiFileReader &multi_file_reader, MultiFileReaderInterface &interface); + + //! Read the union data (schema, cardinality, statistics access) of every file in parallel, without combining the + //! schemas. With ignore_errors, a file that cannot be read yields a null entry instead of failing + DUCKDB_API static vector> + ReadUnionData(ClientContext &context, const vector &files, BaseFileReaderOptions &options, + MultiFileOptions &file_options, MultiFileReader &multi_file_reader, + MultiFileReaderInterface &interface, bool ignore_errors = false, + TaskSchedulerType scheduler_type = TaskSchedulerType::REGULAR); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/numeric_utils.hpp b/src/duckdb/src/include/duckdb/common/numeric_utils.hpp index c17b31f58..dec65375d 100644 --- a/src/duckdb/src/include/duckdb/common/numeric_utils.hpp +++ b/src/duckdb/src/include/duckdb/common/numeric_utils.hpp @@ -34,6 +34,21 @@ T RoundToNearestEven(T value) { return std::fmod(truncated, static_cast(2)) == 0 ? truncated : next; } +//! Rounds halves away from zero like the C round, whose mingw-w64 version misrounds the double just below 0.5 +template +T RoundToNearestAwayFromZero(T value) { + static_assert(std::is_floating_point::value, "RoundToNearestAwayFromZero requires a floating point type"); + if (!std::isfinite(value)) { + return value; + } + const T truncated = std::trunc(value); + // the fraction is exact, so the comparison with a half is exact + if (std::fabs(value - truncated) < static_cast(0.5)) { + return truncated; + } + return value < 0 ? truncated - static_cast(1) : truncated + static_cast(1); +} + template struct MakeSigned { using type = typename std::make_signed::type; diff --git a/src/duckdb/src/include/duckdb/common/open_file_info.hpp b/src/duckdb/src/include/duckdb/common/open_file_info.hpp index ea4b85c89..29d4088d9 100644 --- a/src/duckdb/src/include/duckdb/common/open_file_info.hpp +++ b/src/duckdb/src/include/duckdb/common/open_file_info.hpp @@ -18,11 +18,16 @@ namespace duckdb { struct ExtendedOpenFileInfo { unordered_map options; + //! The option that names the secret to open the file with, instead of the one that matches its path + static constexpr const char *SECRET_OPTION = "secret"; + public: //! Read an option as a T - returns false when the option is not set, throws when it is set to a value //! that cannot be read as a T. Only the types specialized below are supported template bool TryGetOption(const string &name, T &result) const; + //! The name of the secret to open the file with - false when the file names none + DUCKDB_API bool TryGetSecretName(string &name) const; }; //! A boolean option - anything that casts to BOOLEAN is accepted diff --git a/src/duckdb/src/include/duckdb/common/opener_file_system.hpp b/src/duckdb/src/include/duckdb/common/opener_file_system.hpp index 309d3a06d..faf91fa9a 100644 --- a/src/duckdb/src/include/duckdb/common/opener_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/opener_file_system.hpp @@ -38,7 +38,9 @@ class OpenerFileSystem : public FileSystem { //! ".duckdb_extension.info" or ".duckdb_extension.repo.json". Matching is on the file name only, so a //! directory that happens to contain the marker does not reserve the files inside it bool IsDuckDBExtensionName(const string &path) { - auto name = FileSystem::ExtractName(path); + // match the canonical name case-insensitively: on the default macOS and Windows file systems a + // differently-cased name refers to the same file + auto name = StringUtil::Lower(FileSystem::ExtractName(CanonicalizePath(path))); return StringUtil::EndsWith(name, ".duckdb_extension") || StringUtil::Contains(name, ".duckdb_extension."); } @@ -240,6 +242,10 @@ class OpenerFileSystem : public FileSystem { GetFileSystem().SetDisabledFileSystems(names); } + vector GetDisabledFileSystems() override { + return GetFileSystem().GetDisabledFileSystems(); + } + bool SubSystemIsDisabled(const string &name) override { return GetFileSystem().SubSystemIsDisabled(name); } diff --git a/src/duckdb/src/include/duckdb/common/operator/add.hpp b/src/duckdb/src/include/duckdb/common/operator/add.hpp index 591f064b8..0c9b8ce55 100644 --- a/src/duckdb/src/include/duckdb/common/operator/add.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/add.hpp @@ -45,11 +45,29 @@ timestamp_t AddOperator::Operation(date_t left, interval_t right); template <> timestamp_t AddOperator::Operation(interval_t left, date_t right); template <> -timestamp_t AddOperator::Operation(timestamp_t left, interval_t right); +timestamp_t AddOperator::Operation(timestamp_sec_t left, interval_t right); template <> -timestamp_t AddOperator::Operation(timestamp_t left, double right); +timestamp_t AddOperator::Operation(timestamp_sec_t left, double right); template <> -timestamp_t AddOperator::Operation(interval_t left, timestamp_t right); +timestamp_t AddOperator::Operation(interval_t left, timestamp_sec_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, interval_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, double right); +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_ms_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_us_t left, interval_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_us_t left, double right); +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_us_t right); +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, interval_t right); +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, double right); +template <> +timestamp_ns_t AddOperator::Operation(interval_t left, timestamp_ns_t right); struct TryAddOperator { template @@ -70,6 +88,8 @@ template <> bool TryAddOperator::Operation(date_t left, int32_t right, date_t &result); template <> bool TryAddOperator::Operation(timestamp_t left, interval_t right, timestamp_t &result); +template <> +bool TryAddOperator::Operation(timestamp_ns_t left, interval_t right, timestamp_ns_t &result); template <> bool TryAddOperator::Operation(int8_t left, int8_t right, int8_t &result); diff --git a/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp b/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp index acf91605d..8b8cc1654 100644 --- a/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp @@ -19,21 +19,21 @@ namespace duckdb { //===--------------------------------------------------------------------===// struct TryCastToDecimal { template - static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { + static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { NotImplementedException::Throw("Unimplemented type for TryCastToDecimal!"); } }; struct TryCastToDecimalCommaSeparated { template - static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { + static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { NotImplementedException::Throw("Unimplemented type for TryCastToDecimal!"); } }; struct TryCastFromDecimal { template - static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { + static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { NotImplementedException::Throw("Unimplemented type for TryCastFromDecimal!"); } }; @@ -42,422 +42,422 @@ struct TryCastFromDecimal { // Cast Decimal <-> bool //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(bool input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(bool input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(bool input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(bool input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(bool input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(bool input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(bool input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(bool input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, bool &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int8_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int16_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int32_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int64_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> hugeint_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uhugeint_t //===--------------------------------------------------------------------===// template <> DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, int16_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, int32_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, int64_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uhugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint8_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, hugeint_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint8_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint16_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint32_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint64_t //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, uint64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> float //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(float input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(float input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(float input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(float input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(float input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(float input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(float input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(float input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, float &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> double //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(double input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(double input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(double input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(double input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(double input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(double input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(double input, hugeint_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(double input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int16_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int16_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int32_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int32_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(int64_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(int64_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> VARCHAR //===--------------------------------------------------------------------===// template <> -DUCKDB_API bool TryCastToDecimal::Operation(string_t input, int16_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(string_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(string_t input, int32_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(string_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> -DUCKDB_API bool TryCastToDecimal::Operation(string_t input, int64_t &result, CastParameters ¶meters, uint8_t width, - uint8_t scale); +DUCKDB_API bool TryCastToDecimal::Operation(string_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); template <> DUCKDB_API bool TryCastToDecimal::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, int16_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, int32_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, int64_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); template <> DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, - uint8_t width, uint8_t scale); + uint32_t width, uint32_t scale); struct StringCastFromDecimal { template - static inline string_t Operation(SRC input, uint8_t width, uint8_t scale, StringHeap &heap) { + static inline string_t Operation(SRC input, uint32_t width, uint32_t scale, StringHeap &heap) { NotImplementedException::Throw("Unimplemented type for string cast!"); } }; template <> -string_t StringCastFromDecimal::Operation(int16_t input, uint8_t width, uint8_t scale, StringHeap &heap); +string_t StringCastFromDecimal::Operation(int16_t input, uint32_t width, uint32_t scale, StringHeap &heap); template <> -string_t StringCastFromDecimal::Operation(int32_t input, uint8_t width, uint8_t scale, StringHeap &heap); +string_t StringCastFromDecimal::Operation(int32_t input, uint32_t width, uint32_t scale, StringHeap &heap); template <> -string_t StringCastFromDecimal::Operation(int64_t input, uint8_t width, uint8_t scale, StringHeap &heap); +string_t StringCastFromDecimal::Operation(int64_t input, uint32_t width, uint32_t scale, StringHeap &heap); template <> -string_t StringCastFromDecimal::Operation(hugeint_t input, uint8_t width, uint8_t scale, StringHeap &heap); +string_t StringCastFromDecimal::Operation(hugeint_t input, uint32_t width, uint32_t scale, StringHeap &heap); //===--------------------------------------------------------------------===// // Cast VARCHAR <-> Decimal @@ -483,16 +483,16 @@ template struct DecimalCastData { using StoreType = T; StoreType result; - uint8_t width; - uint8_t scale; - uint8_t digit_count; - uint8_t decimal_count; + uint32_t width; + uint32_t scale; + uint32_t digit_count; + uint32_t decimal_count; //! Whether we have determined if the result should be rounded bool round_set; //! If the result should be rounded bool should_round; //! Only set when ALLOW_EXPONENT is enabled - uint8_t excessive_decimals; + uint32_t excessive_decimals; ExponentType exponent_type; StoreType limit; }; @@ -562,7 +562,7 @@ struct DecimalCastOperation { // Everything beyond that amount needs to be truncated if (decimal_excess > exponent) { // We've allowed too many decimals - state.excessive_decimals = UnsafeNumericCast(decimal_excess - exponent); + state.excessive_decimals = UnsafeNumericCast(decimal_excess - exponent); exponent = 0; } else { exponent -= decimal_excess; @@ -660,7 +660,7 @@ struct DecimalCastOperation { // if we have not gotten exactly "scale" decimals, we need to multiply the result // e.g. if we have a string "1.0" that is cast to a DECIMAL(9,3), the value needs to be 1000 // but we have only gotten the value "10" so far, so we multiply by 1000 - for (uint8_t i = state.decimal_count; i < state.scale; i++) { + for (uint32_t i = state.decimal_count; i < state.scale; i++) { state.result *= 10; } return WithinLimit(state); @@ -677,14 +677,14 @@ struct DecimalCastOperation { }; template -bool TryDecimalStringCast(string_t input, T &result, CastParameters ¶meters, uint8_t width, uint8_t scale) { +bool TryDecimalStringCast(string_t input, T &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { return TryDecimalStringCast(input.GetData(), input.GetSize(), result, parameters, width, scale); } template bool TryDecimalStringCast(const char *string_ptr, idx_t string_size, T &result, CastParameters ¶meters, - uint8_t width, uint8_t scale) { + uint32_t width, uint32_t scale) { DecimalCastData state; state.result = 0; state.width = width; @@ -709,7 +709,7 @@ bool TryDecimalStringCast(const char *string_ptr, idx_t string_size, T &result, } template -bool TryDecimalStringCast(const char *string_ptr, idx_t string_size, T &result, uint8_t width, uint8_t scale) { +bool TryDecimalStringCast(const char *string_ptr, idx_t string_size, T &result, uint32_t width, uint32_t scale) { DecimalCastData state; state.result = 0; state.width = width; diff --git a/src/duckdb/src/include/duckdb/common/operator/subtract.hpp b/src/duckdb/src/include/duckdb/common/operator/subtract.hpp index 5b11fd797..5f4aeb1fb 100644 --- a/src/duckdb/src/include/duckdb/common/operator/subtract.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/subtract.hpp @@ -42,6 +42,12 @@ timestamp_t SubtractOperator::Operation(date_t left, interval_t right); template <> timestamp_t SubtractOperator::Operation(timestamp_t left, interval_t right); template <> +timestamp_t SubtractOperator::Operation(timestamp_ms_t left, interval_t right); +template <> +timestamp_t SubtractOperator::Operation(timestamp_sec_t left, interval_t right); +template <> +timestamp_ns_t SubtractOperator::Operation(timestamp_ns_t left, interval_t right); +template <> interval_t SubtractOperator::Operation(timestamp_t left, timestamp_t right); template <> int64_t SubtractOperator::Operation(timestamp_t left, timestamp_t right); diff --git a/src/duckdb/src/include/duckdb/common/primitive_dictionary.hpp b/src/duckdb/src/include/duckdb/common/primitive_dictionary.hpp index 94dbec0a0..e9ad6748f 100644 --- a/src/duckdb/src/include/duckdb/common/primitive_dictionary.hpp +++ b/src/duckdb/src/include/duckdb/common/primitive_dictionary.hpp @@ -9,8 +9,10 @@ #pragma once #include "duckdb/common/types/string_type.hpp" +#include "duckdb/common/types/hash.hpp" #include "duckdb/common/allocator.hpp" #include "duckdb/common/serializer/memory_stream.hpp" +#include "duckdb/common/vector.hpp" namespace duckdb { @@ -40,6 +42,8 @@ template class PrimitiveDictionary { private: static constexpr idx_t LOAD_FACTOR = 2; + //! Clear sweeps every slot once the occupied slots exceed this fraction of the capacity + static constexpr idx_t CLEAR_SWEEP_FACTOR = 8; static constexpr uint32_t INVALID_INDEX = static_cast(-1); struct primitive_dictionary_entry_t { @@ -66,7 +70,7 @@ class PrimitiveDictionary { : capacity * sizeof(TGT))), target_stream(allocated_target.get(), allocated_target.GetSize()), dictionary(reinterpret_cast(allocated_dictionary.get())), full(false) { - Clear(); + ClearAllSlots(); } public: @@ -74,9 +78,19 @@ class PrimitiveDictionary { template void Insert(SRC value) { if (full) { + // nothing can be inserted anymore, so do not pay for the hash return; } - auto &entry = Lookup(value); + Insert(value, Hash(value)); + } + + //! Insert value into dictionary (if not full), reusing the hash a Lookup computed for it + template + void Insert(SRC value, hash_t hash) { + if (full) { + return; + } + auto &entry = Lookup(value, hash); if (entry.IsEmpty()) { if (size + 1 > maximum_size || (ADD_TO_TARGET && !AddToTarget(value))) { full = true; @@ -84,6 +98,7 @@ class PrimitiveDictionary { } entry.value = value; entry.index = size++; + occupied.push_back(UnsafeNumericCast(&entry - dictionary)); } } @@ -95,8 +110,8 @@ class PrimitiveDictionary { } //! Iterates over inserted values - template ::value, int>::type = 0> - void IterateValues(const std::function &fun) const { + template ::value, int>::type = 0> + void IterateValues(FUNC &&fun) const { const auto target_values = reinterpret_cast(allocated_target.get()); for (idx_t i = 0; i < capacity; i++) { auto &entry = dictionary[i]; @@ -108,8 +123,8 @@ class PrimitiveDictionary { } //! Specialized template to iterate over string_t values - template ::value, int>::type = 0> - void IterateValues(const std::function &fun) const { + template ::value, int>::type = 0> + void IterateValues(FUNC &&fun) const { for (idx_t i = 0; i < capacity; i++) { auto &entry = dictionary[i]; if (entry.IsEmpty()) { @@ -119,6 +134,28 @@ class PrimitiveDictionary { } } + //! Iterates over the target values in insertion order + template ::value, int>::type = 0> + void IterateTargetValues(FUNC &&fun) const { + const auto target_values = reinterpret_cast(allocated_target.get()); + for (idx_t i = 0; i < size; i++) { + fun(target_values[i]); + } + } + + //! Specialized template to iterate over length-prefixed string_t target values + template ::value, int>::type = 0> + void IterateTargetValues(FUNC &&fun) const { + auto ptr = const_data_ptr_cast(allocated_target.get()); + const auto end = ptr + target_stream.GetPosition(); + while (ptr < end) { + const auto length = Load(ptr); + ptr += sizeof(uint32_t); + fun(string_t(const_char_ptr_cast(ptr), length)); + ptr += length; + } + } + //! Get the number of unique values in the dictionary idx_t GetSize() const { return size; @@ -148,18 +185,30 @@ class PrimitiveDictionary { void Reset() { allocated_dictionary.Reset(); allocated_target.Reset(); + occupied = vector(); } + //! Empty the dictionary, in time proportional to the entries it holds rather than to its capacity void Clear() { - for (idx_t i = 0; i < capacity; i++) { - dictionary[i].index = INVALID_INDEX; + if (occupied.size() * CLEAR_SWEEP_FACTOR < capacity) { + for (auto offset : occupied) { + dictionary[offset].index = INVALID_INDEX; + } + } else { + ClearAllSlots(); } + occupied.clear(); size = 0; full = false; } //! Look up a value in the dictionary using linear probing primitive_dictionary_entry_t &Lookup(const SRC &value) const { - auto offset = Hash(value) & capacity_mask; + return Lookup(value, Hash(value)); + } + + //! Look up a value with its precomputed hash + primitive_dictionary_entry_t &Lookup(const SRC &value, hash_t hash) const { + auto offset = hash & capacity_mask; while (!dictionary[offset].IsEmpty() && dictionary[offset].value != value) { ++offset &= capacity_mask; } @@ -167,6 +216,12 @@ class PrimitiveDictionary { } private: + void ClearAllSlots() { + for (idx_t i = 0; i < capacity; i++) { + dictionary[i].index = INVALID_INDEX; + } + } + //! Write a value to the target data (if source is not string) template ::value, int>::type = 0> bool AddToTarget(const SRC &src_value) { @@ -251,6 +306,8 @@ class PrimitiveDictionary { //! Pointers to allocated regions for convenience primitive_dictionary_entry_t *const dictionary; + //! Offsets of the filled slots, so Clear does not have to sweep the whole capacity + vector occupied; //! More values inserted than possible bool full; diff --git a/src/duckdb/src/include/duckdb/common/query_context.hpp b/src/duckdb/src/include/duckdb/common/query_context.hpp index 895b5324a..acfc2e7d2 100644 --- a/src/duckdb/src/include/duckdb/common/query_context.hpp +++ b/src/duckdb/src/include/duckdb/common/query_context.hpp @@ -9,32 +9,40 @@ #pragma once #include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/winapi.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { class ClientContext; -//! The QueryContext wraps an optional client context. +//! The QueryContext wraps optional execution services. //! It makes query-related information available to operations. class QueryContext { public: - QueryContext() : context(nullptr) { + QueryContext() { } - QueryContext(optional_ptr context) : context(context) { // NOLINT: allow implicit construction - } - QueryContext(ClientContext &context) : context(&context) { // NOLINT: allow implicit construction + DUCKDB_API QueryContext(optional_ptr client_context); // NOLINT: allow implicit construction + DUCKDB_API QueryContext(ClientContext &client_context); // NOLINT: allow implicit construction + QueryContext(Context &context_p) : context(&context_p) { // NOLINT: allow implicit construction } public: bool Valid() const { return context != nullptr; } - optional_ptr GetClientContext() const { + //! The context (null if the context is not valid) + optional_ptr GetContext() const { return context; } + //! The client the QueryContext was created from (null if it was created from a Context) + optional_ptr GetClientContext() const { + return client_context; + } private: - optional_ptr context; + optional_ptr context; + optional_ptr client_context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/random_engine.hpp b/src/duckdb/src/include/duckdb/common/random_engine.hpp index ec14b42e5..5386ace3f 100644 --- a/src/duckdb/src/include/duckdb/common/random_engine.hpp +++ b/src/duckdb/src/include/duckdb/common/random_engine.hpp @@ -37,6 +37,9 @@ class RandomEngine { uint64_t NextRandomInteger64(); void SetSeed(uint64_t seed); + //! A seed for another generator, mixed with OS entropy unless this engine was seeded explicitly + uint64_t NextSeed(); + uint32_t NextSeed32(); void RandomData(duckdb::data_ptr_t data, duckdb::idx_t len); @@ -46,6 +49,8 @@ class RandomEngine { private: unique_ptr random_state; + //! Whether the engine was given a seed (at construction or with SetSeed) rather than seeded from entropy + bool explicitly_seeded; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/row_operations/row_operations.hpp b/src/duckdb/src/include/duckdb/common/row_operations/row_operations.hpp index 6906b0095..7656fdafc 100644 --- a/src/duckdb/src/include/duckdb/common/row_operations/row_operations.hpp +++ b/src/duckdb/src/include/duckdb/common/row_operations/row_operations.hpp @@ -51,7 +51,7 @@ struct RowOperations { idx_t arg_idx, optional_ptr clustered = nullptr); //! filtered update - aligned addresses static void UpdateFilteredStates(RowOperationsState &state, AggregateFilterData &filter_data, AggregateObject &aggr, - Vector &addresses, DataChunk &payload, idx_t arg_idx); + Vector &addresses, idx_t arg_idx); //! clustered update loop shared by grouped and perfect aggregate hash tables static void UpdateStatesClustered(RowOperationsState &state, vector &aggregates, AggregateFilterDataSet *filter_set, const unsafe_vector *filter, diff --git a/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp b/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp index e640a2812..aa000f73a 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp @@ -18,7 +18,7 @@ namespace duckdb { -class ClientContext; +class Context; class CopiedAsyncWriteBuffer; //! WriteStream implementation that registers writes cheaply and drains them on the async task scheduler. @@ -54,7 +54,7 @@ class AsyncFileWriter : public WriteStream, private ManagedAsyncWriteStreamTarge DUCKDB_API static const FileOpenFlags DEFAULT_OPEN_FLAGS; public: - DUCKDB_API AsyncFileWriter(QueryContext context, FileSystem &fs, const string &path, + DUCKDB_API AsyncFileWriter(Context &context, FileSystem &fs, const string &path, const FileOpenFlags &open_flags = DEFAULT_OPEN_FLAGS); DUCKDB_API ~AsyncFileWriter() override; using WriteStream::Write; @@ -143,8 +143,7 @@ class AsyncFileWriter : public WriteStream, private ManagedAsyncWriteStreamTarge void WaitAllInternal(BatchDrainMode batch_drain_mode); private: - QueryContext context; - ClientContext &client_context; + Context &context; FileSystem &fs; string path; unique_ptr handle; diff --git a/src/duckdb/src/include/duckdb/common/serializer/async_memory_governor.hpp b/src/duckdb/src/include/duckdb/common/serializer/async_memory_governor.hpp index 44f31da40..2dadd7b7e 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/async_memory_governor.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/async_memory_governor.hpp @@ -9,10 +9,11 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/common/mutex.hpp" namespace duckdb { -class ClientContext; +class Context; class TemporaryMemoryState; //! Memory policy shared by the managed async queues. @@ -34,7 +35,7 @@ struct ManagedAsyncMemoryConfig { //! queued and in-flight backlog through the same memory logic. class ManagedAsyncMemoryGovernor { public: - explicit ManagedAsyncMemoryGovernor(ClientContext &client_context); + explicit ManagedAsyncMemoryGovernor(Context &context); ~ManagedAsyncMemoryGovernor(); ManagedAsyncMemoryGovernor(const ManagedAsyncMemoryGovernor &) = delete; @@ -50,9 +51,11 @@ class ManagedAsyncMemoryGovernor { void Release(); private: - ClientContext &client_context; + Context &context; //! Temporary memory reservation state used to limit queued async data. Absent when draining synchronously. unique_ptr memory_state; + //! Serializes concurrent reservation updates and releases from multiple producers. + mutex reservation_lock; //! Last remaining-size request sent to TemporaryMemoryManager. Grows monotonically until Release(). idx_t memory_request_bytes = 0; //! Minimum TemporaryMemoryManager reservation while work is outstanding. diff --git a/src/duckdb/src/include/duckdb/common/serializer/async_task_queue.hpp b/src/duckdb/src/include/duckdb/common/serializer/async_task_queue.hpp index b9962aa43..18a0ffb31 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/async_task_queue.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/async_task_queue.hpp @@ -19,7 +19,7 @@ namespace duckdb { -class ClientContext; +class Context; class TaskExecutor; //! Completion callback for one generic async task. The error is set when the task failed. @@ -47,7 +47,7 @@ class AsyncTaskQueue { friend class AsyncTaskQueueTaskGuard; public: - DUCKDB_API explicit AsyncTaskQueue(ClientContext &client_context, idx_t max_active_tasks = 0); + DUCKDB_API explicit AsyncTaskQueue(Context &context, idx_t max_active_tasks = 0); DUCKDB_API ~AsyncTaskQueue(); AsyncTaskQueue(const AsyncTaskQueue &) = delete; @@ -95,7 +95,7 @@ class AsyncTaskQueue { void CancelPendingRequestsAfterFailure(const ErrorData &error) noexcept; private: - ClientContext &client_context; + Context &context; //! Maximum scheduled/running tasks for this queue. idx_t max_active_tasks = 1; @@ -133,7 +133,7 @@ class AsyncTaskQueue { class ManagedAsyncTaskQueue { public: //! max_active_tasks == 0 -> use TaskScheduler::NumberOfAsyncThreads(). - DUCKDB_API explicit ManagedAsyncTaskQueue(ClientContext &client_context, idx_t max_active_tasks = 0); + DUCKDB_API explicit ManagedAsyncTaskQueue(Context &context, idx_t max_active_tasks = 0); DUCKDB_API ~ManagedAsyncTaskQueue(); ManagedAsyncTaskQueue(const ManagedAsyncTaskQueue &) = delete; @@ -182,7 +182,7 @@ class ManagedAsyncTaskQueue { void CancelPendingTasksAfterFailure(const ErrorData &error) noexcept; private: - ClientContext &client_context; + Context &context; //! Low-level one-unit-per-task scheduler. unique_ptr task_queue; //! Shared TemporaryMemoryManager reservation governor bounding queued async task data. diff --git a/src/duckdb/src/include/duckdb/common/serializer/async_write_queue.hpp b/src/duckdb/src/include/duckdb/common/serializer/async_write_queue.hpp index 39a0deb3c..8bc75f5e9 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/async_write_queue.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/async_write_queue.hpp @@ -20,7 +20,7 @@ namespace duckdb { -class ClientContext; +class Context; class TaskExecutor; //! Compile-time policy used by the async write layers. @@ -84,7 +84,7 @@ class AsyncWriteQueue { friend class AsyncWriteQueueTaskGuard; public: - DUCKDB_API AsyncWriteQueue(ClientContext &client_context, AsyncWriteTarget &target); + DUCKDB_API AsyncWriteQueue(Context &context, AsyncWriteTarget &target); DUCKDB_API ~AsyncWriteQueue(); AsyncWriteQueue(const AsyncWriteQueue &) = delete; @@ -153,7 +153,7 @@ class AsyncWriteQueue { void CancelPendingRequestsAfterFailure(const ErrorData &error) noexcept; private: - ClientContext &client_context; + Context &context; AsyncWriteTarget ⌖ //! Maximum scheduled/running write tasks for this queue. idx_t max_active_tasks = 1; @@ -214,7 +214,7 @@ class ManagedAsyncWriteQueue : private AsyncWriteTarget { enum class SchedulePolicy : uint8_t { THRESHOLD, FORCE }; public: - DUCKDB_API ManagedAsyncWriteQueue(ClientContext &client_context, AsyncWriteTarget &target); + DUCKDB_API ManagedAsyncWriteQueue(Context &context, AsyncWriteTarget &target); DUCKDB_API ~ManagedAsyncWriteQueue() override; ManagedAsyncWriteQueue(const ManagedAsyncWriteQueue &) = delete; @@ -299,7 +299,7 @@ class ManagedAsyncWriteQueue : private AsyncWriteTarget { void Write(data_ptr_t buffer, idx_t size, idx_t offset) override; private: - ClientContext &client_context; + Context &context; AsyncWriteTarget ⌖ //! Low-level positional request scheduler. @@ -342,7 +342,7 @@ class ManagedAsyncWriteStreamQueue : private AsyncWriteTarget { enum class BatchDrainMode : uint8_t { PRESERVE_BATCH, FORCE_CLOSE_BATCH }; public: - DUCKDB_API ManagedAsyncWriteStreamQueue(ClientContext &client_context, ManagedAsyncWriteStreamTarget &target); + DUCKDB_API ManagedAsyncWriteStreamQueue(Context &context, ManagedAsyncWriteStreamTarget &target); DUCKDB_API ~ManagedAsyncWriteStreamQueue() override; ManagedAsyncWriteStreamQueue(const ManagedAsyncWriteStreamQueue &) = delete; @@ -437,7 +437,7 @@ class ManagedAsyncWriteStreamQueue : private AsyncWriteTarget { void Write(data_ptr_t buffer, idx_t size, idx_t offset) override; private: - ClientContext &client_context; + Context &context; ManagedAsyncWriteStreamTarget ⌖ //! Managed queue that owns TMM reservation, backpressure, and task scheduling for physical write requests. diff --git a/src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp b/src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp new file mode 100644 index 000000000..ee9f523db --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/serializer/deserialization_policy.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/bitset.hpp" +#include "duckdb/common/limits.hpp" +#include "duckdb/common/types.hpp" +#include "duckdb/parser/literal.hpp" + +namespace duckdb { + +//! Restrictions on the type and literal identifiers a deserializer may reconstruct. +class DeserializationPolicy { +public: + void Disallow(LogicalTypeId type) { + disallowed_types.set(static_cast(type)); + } + + void Disallow(LiteralKind kind) { + disallowed_literals.set(static_cast(kind)); + } + + bool IsAllowed(LogicalTypeId type) const { + return !disallowed_types.test(static_cast(type)); + } + + bool IsAllowed(LiteralKind kind) const { + return !disallowed_literals.test(static_cast(kind)); + } + +private: + using LogicalTypeStorage = std::underlying_type::type; + using LiteralKindStorage = std::underlying_type::type; + + //! Size each bitset for the full range of its enum's underlying type. + bitset(NumericLimits::Maximum()) + 1> disallowed_types; + bitset(NumericLimits::Maximum()) + 1> disallowed_literals; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp b/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp index 47d39ca5f..c514d64a4 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp @@ -9,6 +9,8 @@ #pragma once #include "duckdb/common/enum_util.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/serializer/deserialization_policy.hpp" #include "duckdb/common/serializer/serialization_data.hpp" #include "duckdb/common/serializer/serialization_traits.hpp" #include "duckdb/common/identifier.hpp" @@ -28,6 +30,10 @@ class Deserializer { bool deserialize_enum_from_string = false; SerializationData data; +private: + //! Without a policy, no identifiers are blocked. + optional policy; + public: virtual ~Deserializer() { } @@ -57,6 +63,18 @@ class Deserializer { public: virtual bool CanDeserializeProperty(const field_id_t field_id, const char *tag) = 0; + void SetPolicy(const DeserializationPolicy &policy_p) { + policy = policy_p; + } + + //! Reject identifiers disallowed by the active policy. + template + void CheckAllowed(T value) const { + if (policy && !policy->IsAllowed(value)) { + throw SerializationException("Deserialization of %s is not allowed", EnumUtil::ToString(value)); + } + } + // Read into an existing value template inline void ReadProperty(const field_id_t field_id, const char *tag, T &ret) { diff --git a/src/duckdb/src/include/duckdb/common/types.hpp b/src/duckdb/src/include/duckdb/common/types.hpp index 68c96362d..c9c1945d0 100644 --- a/src/duckdb/src/include/duckdb/common/types.hpp +++ b/src/duckdb/src/include/duckdb/common/types.hpp @@ -486,7 +486,7 @@ struct LogicalType { DUCKDB_API static LogicalType ConstructNestedType(const LogicalType &type, child_list_t children); //! Gets the decimal properties of a numeric type. Fails if the type is not numeric. - DUCKDB_API bool GetDecimalProperties(uint8_t &width, uint8_t &scale) const; + DUCKDB_API bool GetDecimalProperties(uint32_t &width, uint32_t &scale) const; DUCKDB_API void Verify() const; @@ -559,7 +559,7 @@ struct LogicalType { static constexpr const LogicalTypeId ROW_TYPE = LogicalTypeId::BIGINT; // explicitly allowing these functions to be capitalized to be in-line with the remaining functions - DUCKDB_API static LogicalType DECIMAL(uint8_t width, uint8_t scale); // NOLINT + DUCKDB_API static LogicalType DECIMAL(uint32_t width, uint32_t scale); // NOLINT DUCKDB_API static LogicalType VARCHAR_COLLATION(string collation); // NOLINT DUCKDB_API static LogicalType LIST(const LogicalType &child); // NOLINT DUCKDB_API static LogicalType STRUCT(child_list_t children); // NOLINT @@ -602,9 +602,9 @@ struct LogicalType { }; struct DecimalType { - DUCKDB_API static uint8_t GetWidth(const LogicalType &type); - DUCKDB_API static uint8_t GetScale(const LogicalType &type); - DUCKDB_API static uint8_t MaxWidth(); + DUCKDB_API static uint32_t GetWidth(const LogicalType &type); + DUCKDB_API static uint32_t GetScale(const LogicalType &type); + DUCKDB_API static uint32_t MaxWidth(); }; struct StringType { diff --git a/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp b/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp index 2e14ed463..1c07ebf93 100644 --- a/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp +++ b/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp @@ -110,7 +110,7 @@ string_t NumericHelper::FormatSigned(hugeint_t value, StringHeap &heap); struct DecimalToString { template - static int DecimalLength(SIGNED value, uint8_t width, uint8_t scale) { + static int DecimalLength(SIGNED value, uint32_t width, uint32_t scale) { using UNSIGNED = typename MakeUnsigned::type; if (scale == 0) { // scale is 0: regular number @@ -124,12 +124,12 @@ struct DecimalToString { // integer length + 1 happens when the number is outside of that range // in that case we print the integer number, but with one extra character ('.') auto extra_characters = width > scale ? 2 : 1; - return MaxValue(scale + extra_characters + (value < 0 ? 1 : 0), + return MaxValue(UnsafeNumericCast(scale) + extra_characters + (value < 0 ? 1 : 0), NumericHelper::SignedLength(value) + 1); } template - static void FormatDecimal(SIGNED value, uint8_t width, uint8_t scale, char *dst, idx_t len) { + static void FormatDecimal(SIGNED value, uint32_t width, uint32_t scale, char *dst, idx_t len) { using UNSIGNED = typename MakeUnsigned::type; char *end = dst + len; if (value < 0) { @@ -163,7 +163,7 @@ struct DecimalToString { } template - static string_t Format(SIGNED value, uint8_t width, uint8_t scale, StringHeap &heap) { + static string_t Format(SIGNED value, uint32_t width, uint32_t scale, StringHeap &heap) { int len = DecimalLength(value, width, scale); string_t result = heap.EmptyString(NumericCast(len)); FormatDecimal(value, width, scale, result.GetDataWriteable(), UnsafeNumericCast(len)); @@ -173,13 +173,13 @@ struct DecimalToString { }; template <> -int DecimalToString::DecimalLength(hugeint_t value, uint8_t width, uint8_t scale); +int DecimalToString::DecimalLength(hugeint_t value, uint32_t width, uint32_t scale); template <> -string_t DecimalToString::Format(hugeint_t value, uint8_t width, uint8_t scale, StringHeap &heap); +string_t DecimalToString::Format(hugeint_t value, uint32_t width, uint32_t scale, StringHeap &heap); template <> -void DecimalToString::FormatDecimal(hugeint_t value, uint8_t width, uint8_t scale, char *dst, idx_t len); +void DecimalToString::FormatDecimal(hugeint_t value, uint32_t width, uint32_t scale, char *dst, idx_t len); struct UhugeintToStringCast { static string_t Format(uhugeint_t value, StringHeap &heap) { diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_allocator.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_allocator.hpp index 931f2cfb4..0d5fe067d 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_allocator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_allocator.hpp @@ -44,6 +44,8 @@ class ColumnDataAllocator { ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR); ColumnDataAllocator(ClientContext &context, ColumnDataAllocatorType allocator_type, ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR); + ColumnDataAllocator(Context &context, ColumnDataAllocatorType allocator_type, + ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR); ColumnDataAllocator(ColumnDataAllocator &allocator); ~ColumnDataAllocator(); diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp index 9944471d2..843b93d0e 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp @@ -15,6 +15,7 @@ namespace duckdb { class BufferManager; class BlockHandle; class ClientContext; +class Context; struct ColumnDataCopyFunction; class ColumnDataAllocator; class ColumnDataCollection; @@ -47,6 +48,11 @@ class ColumnDataCollection { ColumnDataCollection(ClientContext &context, vector types, ColumnDataAllocatorType type = ColumnDataAllocatorType::BUFFER_MANAGER_ALLOCATOR, ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR); + //! Constructs either an in-memory or a buffer-managed column data collection + DUCKDB_API + ColumnDataCollection(Context &context, vector types, + ColumnDataAllocatorType type = ColumnDataAllocatorType::BUFFER_MANAGER_ALLOCATOR, + ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR); //! Creates a column data collection that inherits the blocks to write to. This allows blocks to be shared //! between multiple column data collections and prevents wasting space. //! Note that after one CDC inherits blocks from another, the other diff --git a/src/duckdb/src/include/duckdb/common/types/decimal.hpp b/src/duckdb/src/include/duckdb/common/types/decimal.hpp index 7c4fe7d27..9d8c2fc55 100644 --- a/src/duckdb/src/include/duckdb/common/types/decimal.hpp +++ b/src/duckdb/src/include/duckdb/common/types/decimal.hpp @@ -17,41 +17,41 @@ struct DecimalWidth {}; template <> struct DecimalWidth { - static constexpr uint8_t max = 4; + static constexpr uint32_t max = 4; }; template <> struct DecimalWidth { - static constexpr uint8_t max = 9; + static constexpr uint32_t max = 9; }; template <> struct DecimalWidth { - static constexpr uint8_t max = 18; + static constexpr uint32_t max = 18; }; template <> struct DecimalWidth { - static constexpr uint8_t max = 38; + static constexpr uint32_t max = 38; }; //! The Decimal class is a static class that holds helper functions for the Decimal type class Decimal { public: - static constexpr uint8_t MAX_WIDTH_INT16 = DecimalWidth::max; - static constexpr uint8_t MAX_WIDTH_INT32 = DecimalWidth::max; - static constexpr uint8_t MAX_WIDTH_INT64 = DecimalWidth::max; - static constexpr uint8_t MAX_WIDTH_INT128 = DecimalWidth::max; - static constexpr uint8_t MAX_WIDTH_DECIMAL = MAX_WIDTH_INT128; + static constexpr uint32_t MAX_WIDTH_INT16 = DecimalWidth::max; + static constexpr uint32_t MAX_WIDTH_INT32 = DecimalWidth::max; + static constexpr uint32_t MAX_WIDTH_INT64 = DecimalWidth::max; + static constexpr uint32_t MAX_WIDTH_INT128 = DecimalWidth::max; + static constexpr uint32_t MAX_WIDTH_DECIMAL = MAX_WIDTH_INT128; public: //! Whether width/scale form a valid DECIMAL type: width in [1, MAX_WIDTH_DECIMAL] and scale not exceeding width. - static bool IsValidWidthScale(uint8_t width, uint8_t scale) { + static bool IsValidWidthScale(uint32_t width, uint32_t scale) { return width >= 1 && width <= MAX_WIDTH_DECIMAL && scale <= width; } - static string ToString(int16_t value, uint8_t width, uint8_t scale); - static string ToString(int32_t value, uint8_t width, uint8_t scale); - static string ToString(int64_t value, uint8_t width, uint8_t scale); - static string ToString(hugeint_t value, uint8_t width, uint8_t scale); + static string ToString(int16_t value, uint32_t width, uint32_t scale); + static string ToString(int32_t value, uint32_t width, uint32_t scale); + static string ToString(int64_t value, uint32_t width, uint32_t scale); + static string ToString(hugeint_t value, uint32_t width, uint32_t scale); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/interval.hpp b/src/duckdb/src/include/duckdb/common/types/interval.hpp index c0f7f607e..2e97480ca 100644 --- a/src/duckdb/src/include/duckdb/common/types/interval.hpp +++ b/src/duckdb/src/include/duckdb/common/types/interval.hpp @@ -50,6 +50,13 @@ struct interval_t { // NOLINT return !(*this == right); } + //! True when the raw (months, days, micros) fields are identical, without normalizing first. Unlike operator== + //! (which falls back to a normalized comparison, so INTERVAL 1 MONTH == INTERVAL 30 DAY), this is a strict + //! field-wise test: two intervals that are only equal after normalization are not the same here. + inline bool SameFields(const interval_t &right) const { + return months == right.months && days == right.days && micros == right.micros; + } + inline bool operator>(const interval_t &right) const { const auto &left = *this; int64_t lmonths, ldays, lmicros; @@ -167,10 +174,14 @@ class Interval { static date_t Add(date_t left, interval_t right); //! Add an interval to a timestamp static timestamp_t Add(timestamp_t left, interval_t right); + //! Add an interval to a timestamp(ns) + static timestamp_ns_t Add(timestamp_ns_t left, interval_t right); //! Add an interval to a date, returns false instead of throwing if the result is out of range static bool TryAdd(date_t left, interval_t right, date_t &result); //! Add an interval to a timestamp, returns false instead of throwing if the result is out of range static bool TryAdd(timestamp_t left, interval_t right, timestamp_t &result); + //! Add an interval to a timestamp(ns), returns false instead of throwing if the result is out of range + static bool TryAdd(timestamp_ns_t left, interval_t right, timestamp_ns_t &result); //! Add an interval to a time. In case the time overflows or underflows, modify the date by the overflow. //! For example if we go from 23:00 to 02:00, we add a day to the date static dtime_t Add(dtime_t left, interval_t right, date_t &date); diff --git a/src/duckdb/src/include/duckdb/common/types/row/tuple_data_layout.hpp b/src/duckdb/src/include/duckdb/common/types/row/tuple_data_layout.hpp index 7cc1ed34c..c56e6446c 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/tuple_data_layout.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/tuple_data_layout.hpp @@ -28,9 +28,13 @@ class TupleDataLayout { TupleDataLayout Copy() const; public: - //! Initializes the TupleDataLayout with the specified types and aggregates to an empty TupleDataLayout + //! Initializes the TupleDataLayout with the specified types and aggregates to an empty TupleDataLayout. + //! An optional trailing region reserves owner-managed bytes at the end of every row, after the aggregate + //! states. The region is opaque to the layout: hashing, comparison, column and aggregate offsets never + //! reach it, and whole-row moves carry it along with the row. void Initialize(vector types_p, Aggregates aggregates_p, TupleDataValidityType validity_type, - TupleDataNestednessType nestedness_type = TupleDataNestednessType::TOP_LEVEL_LAYOUT); + TupleDataNestednessType nestedness_type = TupleDataNestednessType::TOP_LEVEL_LAYOUT, + idx_t trailing_region_width = 0); //! Initializes the TupleDataLayout with the specified types to an empty TupleDataLayout void Initialize(vector types, TupleDataValidityType validity_type, TupleDataNestednessType nestedness_type = TupleDataNestednessType::TOP_LEVEL_LAYOUT); @@ -113,6 +117,15 @@ class TupleDataLayout { inline idx_t GetHeapSizeOffset() const { return heap_size_offset; } + //! Returns the width of the owner-managed trailing region (0 unless requested at initialization) + inline idx_t GetTrailingRegionWidth() const { + return trailing_region_width; + } + //! Returns the offset of the owner-managed trailing region within each row + inline idx_t GetTrailingRegionOffset() const { + D_ASSERT(trailing_region_width > 0); + return trailing_region_offset; + } //! Returns whether any of the aggregates have a destructor inline bool HasDestructor() const { return !aggr_destructor_idxs.empty(); @@ -152,6 +165,9 @@ class TupleDataLayout { vector sort_skippable_bytes; //! The width of the entire row idx_t row_width; + //! The width and offset of the owner-managed trailing region + idx_t trailing_region_width; + idx_t trailing_region_offset; //! The offsets to the columns and aggregate data in each row vector offsets; //! Whether all columns in this layout are constant size diff --git a/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp b/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp index 0da548cb9..960b9457e 100644 --- a/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp +++ b/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp @@ -184,6 +184,8 @@ template <> DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, float &result); template <> DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, double &result); +template <> +DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, long double &result); template <> bool Uhugeint::TryConvert(int8_t value, uhugeint_t &result); diff --git a/src/duckdb/src/include/duckdb/common/types/value.hpp b/src/duckdb/src/include/duckdb/common/types/value.hpp index 7dcfca937..b389dcaa1 100644 --- a/src/duckdb/src/include/duckdb/common/types/value.hpp +++ b/src/duckdb/src/include/duckdb/common/types/value.hpp @@ -166,10 +166,10 @@ class Value { DUCKDB_API static Value ENUM(uint64_t value, const LogicalType &original_type); // Decimal values - DUCKDB_API static Value DECIMAL(int16_t value, uint8_t width, uint8_t scale); - DUCKDB_API static Value DECIMAL(int32_t value, uint8_t width, uint8_t scale); - DUCKDB_API static Value DECIMAL(int64_t value, uint8_t width, uint8_t scale); - DUCKDB_API static Value DECIMAL(hugeint_t value, uint8_t width, uint8_t scale); + DUCKDB_API static Value DECIMAL(int16_t value, uint32_t width, uint32_t scale); + DUCKDB_API static Value DECIMAL(int32_t value, uint32_t width, uint32_t scale); + DUCKDB_API static Value DECIMAL(int64_t value, uint32_t width, uint32_t scale); + DUCKDB_API static Value DECIMAL(hugeint_t value, uint32_t width, uint32_t scale); //! Create a float Value from a specified value DUCKDB_API static Value FLOAT(float value); //! Create a double Value from a specified value 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 e0dbff42a..f9edd0bd0 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 @@ -291,8 +291,8 @@ struct VariantBuilder { case LogicalTypeId::DECIMAL: { variant_type = VariantLogicalType::DECIMAL; auto &type = primitive.type(); - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; type.GetDecimalProperties(width, scale); VariantBuilderAppendVarint(blob, width); VariantBuilderAppendVarint(blob, scale); diff --git a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp index c563943c7..24b9f1c0a 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp @@ -54,12 +54,37 @@ enum class VariantComparisonType : uint8_t { // complemented for negatives. This makes e.g. 1::TINYINT, 1::BIGINT, 1.00::DECIMAL and 1::BIGNUM all // encode identically, and orders them numerically (so -100.5 < 0 < 1.5 < 15 < ...). struct VariantNumberKey { + //! Enough digits to hold the magnitude of any 128-bit value without falling back to the heap + static constexpr idx_t INLINE_DIGITS = 39; + //! 0 = negative, 1 = zero, 2 = positive (so negatives sort before zero before positives) data_t number_class; int64_t adjusted_exponent; - //! significant decimal digits ('0'..'9'), leading digit non-zero, trailing zeros stripped + //! The number of significant decimal digits, leading digit non-zero and trailing zeros stripped + idx_t digit_count; + //! The significant decimal digits ('0'..'9'), used when they fit inline + char inline_digits[INLINE_DIGITS]; + //! The significant decimal digits, used instead of inline_digits when they do not fit (only BIGNUM + //! can produce magnitudes that large) string digits; + //! Set the significant digits from the given span + inline void SetDigits(const char *data, idx_t count) { + digit_count = count; + if (count <= INLINE_DIGITS) { + memcpy(inline_digits, data, count); + } else { + digits.assign(data, count); + } + } + //! The significant digits (nullptr for zero) + inline const char *GetDigits() const { + if (digit_count == 0) { + return nullptr; + } + return digit_count <= INLINE_DIGITS ? inline_digits : digits.data(); + } + bool operator==(const VariantNumberKey &other) const { if (number_class != other.number_class) { return false; @@ -67,10 +92,10 @@ struct VariantNumberKey { if (adjusted_exponent != other.adjusted_exponent) { return false; } - if (digits != other.digits) { + if (digit_count != other.digit_count) { return false; } - return true; + return digit_count == 0 || memcmp(GetDigits(), other.GetDigits(), digit_count) == 0; } }; 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 67cbd92d9..2024c1a3d 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp @@ -94,6 +94,12 @@ struct ShreddedVariantIterator { vector children; //! The logical type of this layer LogicalType logical_type; + //! The type_id shared by all values of this layer, valid only if has_fixed_type_id is set + VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; + //! Whether type_id holds for every value of this layer (BOOLEAN resolves per value) + bool has_fixed_type_id = false; + //! The size of the physical payload of this layer + idx_t type_size = 0; }; class VariantNode; diff --git a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp index 50503e497..abb87fb2e 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp @@ -277,9 +277,11 @@ class VariantVisitor { return object_items; } -private: +public: + //! Visit throws for a value nested this deep static constexpr idx_t MAX_RECURSION_DEPTH = 128; +private: static void CheckDepth(idx_t depth) { if (depth >= MAX_RECURSION_DEPTH) { throw InvalidInputException("VARIANT exceeds maximum recursion depth of %d", MAX_RECURSION_DEPTH); diff --git a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp index edb2ec780..fb00ab727 100644 --- a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp +++ b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp @@ -193,6 +193,10 @@ class VectorBuffer : public enable_shared_from_this { //! Slice the buffer with a selection vector, returning a new buffer virtual buffer_ptr SliceWithCache(SelCache &cache, const LogicalType &type, const SelectionVector &sel, idx_t count); + //! Create a constant buffer of "count" rows holding the entry at "index" of "source". A string or a list shares + //! the heap or the child of the source, which has to stay valid while the result is used, as for a slice. A + //! shredded source is flattened in place first, so that its constants share the unshredded data + static buffer_ptr ConstantReference(const Vector &source, idx_t index, count_t count); //! Create a UnifiedVectorFormat from the buffer's data virtual void ToUnifiedFormat(UnifiedVectorFormat &format) const; //! Serialize the buffer as-is (including the vector_type), returns false if the vector must be serialized flat @@ -206,6 +210,9 @@ class VectorBuffer : public enable_shared_from_this { buffer_ptr ConstantSlice(const LogicalType &type, count_t count); //! Slice a constant vector with a specific count virtual buffer_ptr ConstantSliceInternal(const LogicalType &type, count_t count); + //! Create a constant buffer of "count" rows holding the entry at "index", by default by copying its value + virtual buffer_ptr ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const; //! Slice the buffer with a selection vector, returning a new buffer virtual buffer_ptr SliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count); //! Slice the buffer with an offset range, returning a new buffer diff --git a/src/duckdb/src/include/duckdb/common/vector/array_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/array_vector.hpp index ad361f8e4..f9527c380 100644 --- a/src/duckdb/src/include/duckdb/common/vector/array_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/array_vector.hpp @@ -46,6 +46,8 @@ class VectorArrayBuffer : public VectorBuffer { protected: buffer_ptr SliceInternal(const LogicalType &type, idx_t offset, idx_t end) override; buffer_ptr ConstantSliceInternal(const LogicalType &type, count_t count) override; + buffer_ptr ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const override; void CopyInternal(const Vector &source, const SelectionVector &source_sel, idx_t source_count, idx_t source_offset, idx_t target_offset, idx_t copy_count) override; buffer_ptr FlattenSliceInternal(const LogicalType &type, const SelectionVector &sel, diff --git a/src/duckdb/src/include/duckdb/common/vector/constant_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/constant_vector.hpp index 46acb7d6f..1916f4019 100644 --- a/src/duckdb/src/include/duckdb/common/vector/constant_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/constant_vector.hpp @@ -83,7 +83,9 @@ struct ConstantVector { DUCKDB_API static const SelectionVector *ZeroSelectionVector(); //! Turns "vector" into a constant vector by referencing a value DUCKDB_API static void Reference(Vector &vector, const Value &value, count_t count); - //! Turns "vector" into a constant vector by referencing a value within the source vector + //! Turns "vector" into a constant vector by referencing a value within the source vector. A string or a list + //! shares the data of the source, which has to stay valid while the constant is used, as for a slice. A shredded + //! source is flattened in place first, so that its constants share the unshredded data DUCKDB_API static void Reference(Vector &vector, count_t count, const Vector &source, idx_t position, idx_t source_count); diff --git a/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp index 6190cc143..6a172803c 100644 --- a/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp @@ -94,6 +94,8 @@ class DictionaryBuffer : public VectorBuffer { protected: buffer_ptr SliceInternal(const LogicalType &type, idx_t offset, idx_t end) override; buffer_ptr SliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) override; + buffer_ptr ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const override; buffer_ptr FlattenSliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) const override; void VerifyInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) const override; diff --git a/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp index 301c688bb..5dc609485 100644 --- a/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp @@ -56,6 +56,8 @@ class StandardVectorBuffer : public VectorBuffer { buffer_ptr SliceInternal(const LogicalType &type, idx_t offset, idx_t end) override; buffer_ptr SliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) override; buffer_ptr ConstantSliceInternal(const LogicalType &type, count_t count) override; + buffer_ptr ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const override; void CopyInternal(const Vector &source, const SelectionVector &source_sel, idx_t source_count, idx_t source_offset, idx_t target_offset, idx_t copy_count) override; buffer_ptr FlattenSliceInternal(const LogicalType &type, const SelectionVector &sel, diff --git a/src/duckdb/src/include/duckdb/common/vector/fsst_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/fsst_vector.hpp index 5b934b6f3..82314d679 100644 --- a/src/duckdb/src/include/duckdb/common/vector/fsst_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/fsst_vector.hpp @@ -36,6 +36,8 @@ class VectorFSSTStringBuffer : public VectorStringBuffer { Value GetValue(const LogicalType &type, idx_t index) const override; protected: + buffer_ptr ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const override; buffer_ptr FlattenSliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) const override; void VerifyInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) const override; diff --git a/src/duckdb/src/include/duckdb/common/vector/struct_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/struct_vector.hpp index 8d9f2e389..09408460d 100644 --- a/src/duckdb/src/include/duckdb/common/vector/struct_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/struct_vector.hpp @@ -56,6 +56,8 @@ class VectorStructBuffer : public VectorBuffer { buffer_ptr SliceInternal(const LogicalType &type, idx_t offset, idx_t end) override; buffer_ptr SliceInternal(const LogicalType &type, const SelectionVector &sel, idx_t count) override; buffer_ptr ConstantSliceInternal(const LogicalType &type, count_t count) override; + buffer_ptr ConstantReferenceInternal(const LogicalType &type, idx_t index, + count_t count) const override; void CopyInternal(const Vector &source, const SelectionVector &source_sel, idx_t source_count, idx_t source_offset, idx_t target_offset, idx_t copy_count) override; buffer_ptr FlattenSliceInternal(const LogicalType &type, const SelectionVector &sel, diff --git a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp index 284086aa1..9968ba4fb 100644 --- a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp @@ -76,6 +76,7 @@ class VirtualFileSystem : public FileSystem { std::string GetName() const override; void SetDisabledFileSystems(const vector &names) override; + vector GetDisabledFileSystems() override; bool SubSystemIsDisabled(const string &name) override; bool IsDisabledForPath(const string &path) override; diff --git a/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp index 893f77f9f..0cee0f02a 100644 --- a/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp @@ -77,7 +77,8 @@ class GroupedAggregateHashTable : public BaseAggregateHashTable { GroupedAggregateHashTable(ClientContext &context, Allocator &allocator, vector group_types, vector payload_types, vector aggregates, idx_t initial_capacity = InitialCapacity(), idx_t radix_bits = 0, - TupleDataValidityType group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES); + TupleDataValidityType group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES, + idx_t trailing_region_width = 0); GroupedAggregateHashTable(ClientContext &context, Allocator &allocator, vector group_types, TupleDataValidityType group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES); ~GroupedAggregateHashTable() override; @@ -182,6 +183,8 @@ class GroupedAggregateHashTable : public BaseAggregateHashTable { private: ClientContext &context; + //! Zeroes the layout's trailing region of freshly created rows so owners find defined bytes + void ZeroTrailingRegion(Vector &row_locations, idx_t count) const; //! Efficiently matches groups RowMatcher row_matcher; diff --git a/src/duckdb/src/include/duckdb/execution/executor.hpp b/src/duckdb/src/include/duckdb/execution/executor.hpp index d8987ea9f..4b7271752 100644 --- a/src/duckdb/src/include/duckdb/execution/executor.hpp +++ b/src/duckdb/src/include/duckdb/execution/executor.hpp @@ -35,6 +35,7 @@ class Task; struct PipelineEventStack; struct ProducerToken; struct ScheduleEventData; +struct PipelineSchedule; class Executor { friend class Pipeline; @@ -154,7 +155,8 @@ class Executor { bool ResultStoreCanPark(); void InitializeInternal(PhysicalOperator &physical_plan); - void ScheduleEvents(const vector> &meta_pipelines); + void ScheduleEvents(const vector> &meta_pipelines, + unique_ptr resolved_schedule = nullptr); void ScheduleEventsInternal(ScheduleEventData &event_data); static void VerifyScheduledEvents(const vector> &events); diff --git a/src/duckdb/src/include/duckdb/execution/expression_executor.hpp b/src/duckdb/src/include/duckdb/execution/expression_executor.hpp index 30e4ac603..e06aee6c9 100644 --- a/src/duckdb/src/include/duckdb/execution/expression_executor.hpp +++ b/src/duckdb/src/include/duckdb/execution/expression_executor.hpp @@ -76,6 +76,8 @@ class ExpressionExecutor { //! Execute the expression with index `expr_idx` and store the result in the result vector DUCKDB_API void ExecuteExpression(idx_t expr_idx, Vector &result); + //! 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(ClientContext &context, const Expression &expr, bool allow_unfoldable = false); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art.hpp index 3f1a125e1..1755ff8b3 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art.hpp @@ -133,6 +133,8 @@ class ART : public BoundIndex { //! Reset all ART storage. void ResetStorage(IndexLock &index_lock) override DUCKDB_REQUIRES(index_lock); + //! Reset all ART storage without freeing its on-disk blocks. + void DisownStorage(IndexLock &index_lock) override DUCKDB_REQUIRES(index_lock); //! Build an ART from a vector of sorted keys and their row IDs. ARTConflictType Build(unsafe_vector &keys, unsafe_vector &row_ids, const idx_t row_count); diff --git a/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp b/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp index a10a0d6e8..e6e0122b9 100644 --- a/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp @@ -129,6 +129,11 @@ class BoundIndex : public Index { virtual void ResetStorage(IndexLock &index_lock) DUCKDB_REQUIRES(index_lock) = 0; //! Obtains a lock and calls ResetStorage while holding that lock. void ResetStorage() override DUCKDB_EXCLUDES(lock); + //! Clears the index without freeing the on-disk blocks it was created from, which stay owned by the unbound + //! index. Called when binding the index fails after the index was created from its storage information. + virtual void DisownStorage(IndexLock &index_lock) DUCKDB_REQUIRES(index_lock); + //! Obtains a lock and calls DisownStorage while holding that lock. + void DisownStorage() DUCKDB_EXCLUDES(lock); //! Delete a chunk of entries from the index. The index lock must be held. //! Returns the amount of rows successfully deleted from the index. diff --git a/src/duckdb/src/include/duckdb/execution/index/fixed_size_allocator.hpp b/src/duckdb/src/include/duckdb/execution/index/fixed_size_allocator.hpp index 9a1435f50..52ce40881 100644 --- a/src/duckdb/src/include/duckdb/execution/index/fixed_size_allocator.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/fixed_size_allocator.hpp @@ -103,6 +103,9 @@ class FixedSizeAllocator { //! Resets the allocator, e.g., during 'DELETE FROM table' void Reset(); + //! Resets the allocator without freeing the on-disk blocks of its buffers. + //! The blocks stay owned by the storage information the allocator was initialized from. + void DisownBuffers(); //! Returns the in-memory size in bytes idx_t GetInMemorySize() const; diff --git a/src/duckdb/src/include/duckdb/execution/index/fixed_size_buffer.hpp b/src/duckdb/src/include/duckdb/execution/index/fixed_size_buffer.hpp index 909aa21e0..e57d287c8 100644 --- a/src/duckdb/src/include/duckdb/execution/index/fixed_size_buffer.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/fixed_size_buffer.hpp @@ -44,6 +44,9 @@ class FixedSizeBuffer : public BlockPackable { public: void Finalize(shared_ptr block_handle_p, uint32_t offset) override; + //! Drops the reference to the on-disk block without marking it as modified, i.e., without freeing it. + //! The block stays owned by the storage information this buffer was created from. + void DisownBlock(); public: bool IsEmpty() const { diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp index 3fd137b63..b8b50d1ae 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp @@ -50,26 +50,46 @@ struct AggregateObject { // NOLINT: work-around bug in clang-tidy }; struct AggregateFilterData { - AggregateFilterData(ClientContext &context, const Expression &filter_expr, - const vector &payload_types); + AggregateFilterData(ClientContext &context, const Expression &filter_expr, DataChunk &filtered_payload); + //! Evaluates the filter on the chunk into true_sel and selected_count + idx_t Select(DataChunk &chunk); + //! Evaluates the filter and slices the payload columns in sliced_columns into filtered_payload idx_t ApplyFilter(DataChunk &payload); ExpressionExecutor filter_executor; - DataChunk filtered_payload; + //! Shared by all filters of the set: this filter only fills its own sliced_columns + DataChunk &filtered_payload; SelectionVector true_sel; + //! The number of rows selected by the last Select + idx_t selected_count = 0; + //! The non-distinct aggregates that use this filter + unsafe_vector aggregates; + //! The payload columns (the children of those aggregates) that ApplyFilter slices + unsafe_vector sliced_columns; }; +//! The filters of a set of aggregates: aggregates with an identical filter share one AggregateFilterData struct AggregateFilterDataSet { AggregateFilterDataSet(); + //! One buffer-less chunk for the whole set: the filters slice disjoint payload columns into it + unique_ptr filtered_payload; + //! One entry per distinct filter expression vector> filter_data; public: + //! Initializes the filters of the aggregates; ApplyFilter expects the payload to hold their children void Initialize(ClientContext &context, const vector &aggregates, const vector &payload_types); AggregateFilterData &GetFilterData(idx_t aggr_idx); + //! Applies each filter used by one of the aggregates in aggregate_indices (all aggregates if not given) once + void ApplyFilters(DataChunk &payload, optional_ptr> aggregate_indices = nullptr); + +private: + //! Per aggregate: index into filter_data, or DConstants::INVALID_INDEX for aggregates without a filter + unsafe_vector aggregate_filter_idx; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/grouped_aggregate_data.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/grouped_aggregate_data.hpp index a07fd4098..5d115ff24 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/grouped_aggregate_data.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/grouped_aggregate_data.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/unordered_map.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/aggregate_function.hpp" #include "duckdb/parser/group_by_node.hpp" @@ -47,6 +48,11 @@ class GroupedAggregateData { //! Initialize a GroupedAggregateData object for use with distinct aggregates void InitializeDistinct(const unique_ptr &aggregate, const vector> *groups_p); + //! Points the filters of the aggregates at payload columns following the children (one per distinct filter) and + //! appends their types; returns the input column that each of those payload columns is read from + static unordered_map AddFilterColumns(const vector> &aggregates, + vector &payload_types); + private: void InitializeDistinctGroups(const vector> *groups); void InitializeGroupbyGroups(vector> groups); diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp index 0fb4a54a3..94e0a3a13 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp @@ -88,7 +88,8 @@ class PhysicalHashAggregate : public PhysicalOperator { unsafe_vector non_distinct_filter; unsafe_vector distinct_filter; - reference_map_t filter_indexes; + //! The payload column of each distinct filter and the input column it is read from + unordered_map filter_columns; public: // Source interface diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_perfecthash_aggregate.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_perfecthash_aggregate.hpp index ee191422a..48a2cd49f 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_perfecthash_aggregate.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_perfecthash_aggregate.hpp @@ -8,9 +8,9 @@ #pragma once +#include "duckdb/common/unordered_map.hpp" #include "duckdb/execution/physical_operator.hpp" #include "duckdb/execution/base_aggregate_hashtable.hpp" -#include "duckdb/common/reference_map.hpp" namespace duckdb { class ClientContext; @@ -87,7 +87,8 @@ class PhysicalPerfectHashAggregate : public PhysicalOperator { //! The number of bits we need to completely cover each of the groups vector required_bits; - reference_map_t filter_indexes; + //! The payload column of each distinct filter and the input column it is read from + unordered_map filter_columns; }; } // namespace duckdb 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 87540e6ab..bf63f963a 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 @@ -56,7 +56,7 @@ class CSVBuffer { bool last_buffer); //! Creates a new buffer with the next part of the CSV File - shared_ptr Next(CSVFileHandle &file_handle, idx_t buffer_size, bool &has_seeked) const; + shared_ptr Next(CSVFileHandle &file_handle, idx_t buffer_size) const; //! Allocates the buffer and fills it sequentially from the file handle's current position void Load(CSVFileHandle &file_handle); @@ -73,10 +73,8 @@ class CSVBuffer { //! Allocates internal buffer, sets 'block' and 'handle' variables. void AllocateBuffer(idx_t buffer_size); - void Reload(CSVFileHandle &file_handle); - //! Wrapper for the Pin Function, if it can seek, it means that the buffer might have been destroyed, hence we must - //! Scan it from the disk file again. - shared_ptr Pin(CSVFileHandle &file_handle, bool &has_seeked); + //! Pins the buffer, re-reading a destroyed random-access buffer from the file + shared_ptr Pin(CSVFileHandle &file_handle); //! Pins the buffer only if it is in memory and no load is in flight; never performs I/O and never blocks bool TryPin(shared_ptr &pinned); //! Wrapper for unpin @@ -87,9 +85,10 @@ class CSVBuffer { bool IsUnloaded() const { return block->GetMemory().IsUnloaded(); } - //! Whether the underlying block is loaded in memory + //! Whether the buffer can be pinned without reading from the file (spilled sequential buffers are reloaded by the + //! buffer manager) bool IsInMemory() const { - return block && (is_pipe || !block->GetMemory().IsUnloaded()); + return block && (!random_access || !block->GetMemory().IsUnloaded()); } //! By default, we use CSV_BUFFER_SIZE to allocate each buffer @@ -110,8 +109,6 @@ class CSVBuffer { idx_t requested_size; //! Global position from the CSV File where this buffer starts idx_t global_csv_start = 0; - //! If this file is being fed by a pipe. - bool is_pipe; //! If this is a random access buffer bool random_access = false; //! Buffer Index, used as a batch index for insertion-order preservation diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer_manager.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer_manager.hpp index 9e12b5378..20d268c7e 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer_manager.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_buffer_manager.hpp @@ -80,7 +80,7 @@ class CSVBufferManager { //! The size of the buffer, if the csv file has a smaller size than this, we will use that instead to malloc less idx_t buffer_size; //! Because the buffer manager can be accessed in Parallel we need a mutex. - mutex main_mutex; + mutable mutex main_mutex; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_casting.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_casting.hpp index 6932d360b..506bff705 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_casting.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_casting.hpp @@ -40,7 +40,7 @@ class CSVCast { template static bool TemplatedTryCastDecimalVector(const CSVReaderOptions &options, Vector &input_vector, Vector &result_vector, idx_t count, CastParameters ¶meters, - uint8_t width, uint8_t scale, idx_t &line_error) { + uint32_t width, uint32_t scale, idx_t &line_error) { D_ASSERT(input_vector.GetType().id() == LogicalTypeId::VARCHAR); bool all_converted = true; auto &validity_mask = FlatVector::ValidityMutable(result_vector); diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp index 2c245b67e..6f63e6e31 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp @@ -63,6 +63,14 @@ class CSVFileHandle { idx_t UncompressedBytesRead() const { return uncompressed_bytes_read.load(std::memory_order_relaxed); } + //! The bytes of the stored file read since the last call - for a compressed file, its compressed bytes. Bytes read + //! again are not returned again + idx_t TakeStoredBytesRead() { + return stored_bytes_untaken.exchange(0); + } + void AddStoredBytesRead(idx_t bytes) { + stored_bytes_untaken += bytes; + } private: QueryContext context; @@ -73,6 +81,9 @@ class CSVFileHandle { bool on_disk_file = false; bool is_pipe = false; atomic uncompressed_bytes_read {0}; + atomic stored_bytes_untaken {0}; + //! How far into the stored file sequential reads have counted, so a read again after a seek is not counted twice + idx_t stored_bytes_counted = 0; idx_t file_size = 0; 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 b62ed51d8..f8d3df880 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 @@ -73,6 +73,10 @@ class CSVFileScan { shared_ptr state_machine; //! How many bytes were read up to this point atomic bytes_read {0}; + //! The bytes of the stored file scanned but not yet reported to the profiler + atomic bytes_scanned_unreported {0}; + //! Counts the stored bytes the file was read for since the last call as scanned + void CountBytesScanned(CSVBufferManager &manager); //! The progress of a compressed file is estimated - keeps it monotonic MonotonicProgress compressed_progress; //! Size of this file diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_random_access_buffer_manager.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_random_access_buffer_manager.hpp index 217ea5f3d..74ef1a036 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_random_access_buffer_manager.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_random_access_buffer_manager.hpp @@ -26,6 +26,11 @@ class CSVRandomAccessBufferManager : public CSVBufferManager { void ResetBufferManager() override; private: + //! Creates the buffer at `pos`, counting its stored bytes the first time - a buffer released and read again is + //! not counted again + shared_ptr CreateBuffer(idx_t pos); + //! The buffers created at least once + vector created; //! Sizes the buffer table and eagerly materializes the first buffer (sniffing and newline detection //! always read it) void Initialize(); diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_sequential_buffer_manager.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_sequential_buffer_manager.hpp index 627253487..1b6e11e20 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_sequential_buffer_manager.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_sequential_buffer_manager.hpp @@ -36,8 +36,6 @@ class CSVSequentialBufferManager : public CSVBufferManager { idx_t global_csv_pos = 0; //! If this buffer manager is done (i.e., no more buffers to read beyond the ones that were cached bool done = false; - //! If the file_handle used seek - bool has_seeked = false; unordered_set reset_when_possible; bool is_pipe; }; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp index c737c02d6..667f2c681 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp @@ -54,6 +54,10 @@ class CSVEncoder { idx_t Encode(FileHandle &file_handle_input, char *output_buffer, const idx_t decoded_buffer_size); //! Resets the encoder so the file can be read again from the beginning void Reset(); + //! The encoded bytes read from the file + idx_t EncodedBytesRead() const { + return encoded_bytes_read; + } string encoding_name; private: @@ -68,5 +72,6 @@ class CSVEncoder { //! Pass-on Byte, used to check if we are done with the file, but must be appended to next buffer char pass_on_byte; bool has_pass_on_byte = false; + idx_t encoded_bytes_read = 0; }; } // namespace duckdb 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 e874e3741..85c7e8159 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 @@ -173,8 +173,8 @@ struct ParseTypeInfo { bool validate_utf8; LogicalTypeId type_id; PhysicalType internal_type; - uint8_t scale; - uint8_t width; + uint32_t scale; + uint32_t width; }; class StringValueResult : public ScannerResult { 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 e9b402745..417af2d5d 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 @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" #include "duckdb/parallel/interrupt.hpp" #include "duckdb/storage/buffer_manager.hpp" @@ -20,7 +21,7 @@ class BatchMemoryManager : public StateWithBlockableTasks { BatchMemoryManager(ClientContext &context, idx_t initial_memory_request) : context(context), unflushed_memory_usage(0), min_batch_index(0), available_memory(0), can_increase_memory(true) { - memory_state = TemporaryMemoryManager::Get(context).Register(context); + memory_state = TemporaryMemoryManager::Get(context.GetContext()).Register(context.GetContext()); SetMemorySize(initial_memory_request); } @@ -48,7 +49,7 @@ class BatchMemoryManager : public StateWithBlockableTasks { return; } - memory_state->SetRemainingSizeAndUpdateReservation(context, size); + memory_state->SetRemainingSizeAndUpdateReservation(context.GetContext(), size); auto next_reservation = memory_state->GetReservation(); if (available_memory >= next_reservation) { // we tried to ask for more memory but were declined diff --git a/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp b/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp index b1ef99565..b8f57ea36 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp @@ -47,6 +47,9 @@ class PhysicalTableInOutFunction : public PhysicalOperator { //! Information for WITH ORDINALITY optional_idx ordinality_idx; + //! Whether the function consumes a TABLE parameter: its input rows form one invocation, + //! so the ordinality numbering continues across them instead of restarting per row + bool table_input = false; OrderPreservationType OperatorOrder() const override { return function.order_preservation_type; diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_cte.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_cte.hpp index 169fde9f3..eef96b2ca 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_cte.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_cte.hpp @@ -126,6 +126,9 @@ class PhysicalCTE : public PhysicalOperator { bool ShouldUseBufferedConsumer(Pipeline &pipeline) const; void RegisterBufferedConsumer(Pipeline &pipeline, idx_t consumer_idx); void RegisterMaterializedConsumer(idx_t consumer_idx); + //! Converts an already registered buffered consumer to a materialized one, before execution starts. Used when + //! the schedule gates the consumer's execute behind its own producer's completion, so it could never drain. + void DemoteBufferedConsumer(idx_t consumer_idx); CTEExecutionMode GetExecutionMode() const; bool UseStreamingExchange() const; diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp index 13d47206b..c5516dd0e 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp @@ -27,6 +27,10 @@ struct RecursiveCTEPipelineSchedulePlan; class PhysicalColumnDataScan; class Pipeline; class PipelineExecutor; +class InterruptState; + +//! Result of driving one recursive epoch +enum class RecursiveEpochResult : uint8_t { COMPLETE, BLOCKED }; class RecursiveCTEPartialKeySpec { public: @@ -65,6 +69,9 @@ struct RecursiveCTEKeyedProperties { bool can_reuse_changed_group_candidates = false; //! Some payload column compares through a SQL-level expression rather than by value bool has_payload_comparisons = false; + //! Every aggregate result fits a fixed-width or string slot, so the commit can materialize the finalized values + //! per group and reads consume them without invoking aggregate callbacks + bool materialize_finalized_values = false; static RecursiveCTEKeyedProperties Derive(const PhysicalRecursiveCTE &op); }; @@ -176,7 +183,11 @@ class PhysicalRecursiveCTE : public PhysicalOperator { vector> GetSources() const override; private: - void ExecuteRecursivePipelines(ExecutionContext &context) const; + //! Drives one recursive epoch. BLOCKED means the epoch suspended on blocked inner work: the + //! caller must return SourceResultType::BLOCKED and will be re-entered through the given + //! interrupt state once the blocking work completes. The epoch resumes where it stopped. + RecursiveEpochResult ExecuteRecursivePipelines(ExecutionContext &context, + const InterruptState &interrupt_state) const; idx_t NextMetricsInvocation() const; private: diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp index c63fab532..e476e7a29 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp @@ -21,7 +21,9 @@ class RecursiveCTEGroupAddressSet { }; struct RecursiveCTEKeyDeltaState { - RecursiveCTEKeyDeltaState(ClientContext &context, const PhysicalRecursiveCTE &op); + //! With materialized finalized values (address_only_previous) the previous rows carry only group addresses, + //! because the old payload values stay readable from the rows themselves until the commit overwrites them + RecursiveCTEKeyDeltaState(ClientContext &context, const PhysicalRecursiveCTE &op, bool address_only_previous); void Reset(); void PrepareCollections(); @@ -70,8 +72,12 @@ struct RecursiveCTEKeyDeltaState { ColumnDataCollection previous_rows; ColumnDataCollection new_keys; + //! Finalized rows buffered by the changed-candidate validation until it either succeeds and publishes them + //! or fails and the regular delta finalization takes over + ColumnDataCollection pending_finalized; ColumnDataAppendState previous_append_state; ColumnDataAppendState new_key_append_state; + ColumnDataAppendState pending_finalized_append_state; DataChunk selected_keys; DataChunk aggregate_rows; DataChunk updated_aggregate_rows; diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp index 494450866..313ee2190 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp @@ -14,6 +14,8 @@ namespace duckdb { class RecursiveCTEKeyedLocalState; struct RecursiveCTEKeyDeltaState; +struct AuxiliaryDataSet; +class StringHeap; //! Turns candidate rows into the normalized key columns and the aggregate inputs of the keyed state. Classification, //! pre-aggregation and commits each own one, so every path applies the same key normalization. @@ -38,6 +40,61 @@ class RecursiveCTEKeyedCandidateExtractor { DataChunk raw_keys; }; +//! The finalized aggregate values of every group, stored in the trailing region of the hash table rows and +//! refreshed by the commit for every touched or new group. Reads gather these values instead of invoking +//! aggregate callbacks, so frozen-state reads stay plain loads. String values live in a shared-ownership heap +//! that emitted vectors reference, so gathers emit the stored strings without copying. Compaction at commit +//! swaps in a fresh heap and migrates every live slot; the old heap stays alive until the last referencing +//! vector releases it. +class RecursiveCTEFinalizedValues { +public: + RecursiveCTEFinalizedValues(ClientContext &context, const PhysicalRecursiveCTE &op); + + //! The trailing region bytes the operator's hash tables must reserve for this plan + static idx_t RegionWidthFor(const PhysicalRecursiveCTE &op); + + bool Enabled() const { + return enabled; + } + idx_t RegionWidth() const { + return region_width; + } + //! Records the trailing region offset of the persistent hash table's layout + void BindLayout(const TupleDataLayout &layout); + //! Writes finalized values (aggregate order) at addresses[sel[i]] from values row sel[i] + void Scatter(const Vector &addresses, const SelectionVector &sel, idx_t count, DataChunk &values); + //! Writes candidate rows standing in for finalized values of new groups, mapping each aggregate to its + //! first input column; valid under the single-value-identity proof of the candidate-reuse paths + void ScatterCandidates(const Vector &addresses, const SelectionVector &sel, idx_t count, DataChunk &payload); + //! Reads finalized values (aggregate order) from addresses[sel[i]] into values row i + void Gather(const Vector &addresses, const SelectionVector &sel, idx_t count, DataChunk &values); + //! Reclaims replaced string bytes once they outweigh the live ones; the caller guarantees no readers + void MaybeCompact(GroupedAggregateHashTable &target); + +private: + void ScatterColumns(const Vector &addresses, const SelectionVector &sel, idx_t count, DataChunk &values, + const vector &source_columns); + string_t CopyStringToArena(string_t value); + +private: + bool enabled = false; + idx_t region_width = 0; + idx_t region_offset = 0; + //! Offset of each aggregate's value slot relative to the region start; validity bytes precede the slots + vector value_offsets; + vector value_types; + //! The identity mapping, for scattering finalized chunks in aggregate order + vector identity_source_columns; + //! Per aggregate, the column of its first input in the evaluated payload chunk + vector candidate_source_columns; + //! Shared-ownership storage for non-inlined finalized strings; emitted vectors hold references to it + buffer_ptr string_arena; + //! The heap inside string_arena's holder; only the single-threaded commit writes to it + optional_ptr string_heap; + idx_t string_live_bytes = 0; + idx_t string_garbage_bytes = 0; +}; + //! USING KEY recursion. Every key owns one aggregate state in a shared hash table. Within an iteration the state is //! read by recurring scans and direct probes, member rows are collected as update candidates, and the commit at the //! end of the iteration applies them and assembles the next frontier from the keys whose finalized payload changed. @@ -49,8 +106,8 @@ class RecursiveCTEKeyedState : public RecursiveCTEState { unique_ptr GetLocalSinkState(ExecutionContext &context) const override; SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) override; SinkCombineResultType Combine(ExecutionContext &context, OperatorSinkCombineInput &input) override; - SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source) override; + SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state) override; const ColumnDataCollection &CurrentInputTable() const override; idx_t RecurringStateRows() const override; idx_t RecurringStateChunks() const override; @@ -73,15 +130,26 @@ class RecursiveCTEKeyedState : public RecursiveCTEState { void CombineOutput(ColumnDataCollection &output); void RegisterLocalPreaggregation(unique_ptr local_ht, idx_t candidate_rows, idx_t classification_work_ns, idx_t preaggregation_work_ns); + //! Result rows from frozen state addresses: gathered from the finalized values when they are materialized, + //! finalized from the aggregate states under the lock otherwise void FinalizeStateRows(RowOperationsState &row_state, Vector &addresses, DataChunk &keys, DataChunk &aggregates, DataChunk &result); + bool UsesFinalizedValues() const { + return finalized.Enabled(); + } + //! Gathers the finalized values at the addresses and assembles result rows; no aggregate callbacks run + void ReadStateRows(const Vector &addresses, DataChunk &keys, DataChunk &aggregates, DataChunk &result); private: + //! Finalizes the aggregate states themselves; the commit uses this to produce the values it materializes + void FinalizeStateRowsFromStates(RowOperationsState &row_state, Vector &addresses, DataChunk &keys, + DataChunk &aggregates, DataChunk &result); void FinalizeAggregateRows(RowOperationsState &row_state, Vector &addresses, DataChunk &aggregates, idx_t count); void AssembleStateRows(DataChunk &keys, DataChunk &aggregates, DataChunk &result) const; template SourceResultType GetUsingKeyDataInternal(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source); + RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state); template void CommitUsingKeyUpdatesInternal(); template @@ -109,6 +177,7 @@ class RecursiveCTEKeyedState : public RecursiveCTEState { private: unique_ptr ht; vector> partial_key_indexes; + RecursiveCTEFinalizedValues finalized; RecursiveCTEKeyedCandidateExtractor extractor; DataChunk payload_rows; Vector new_group_addresses; diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp index fa660d034..53fbf4d75 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp @@ -9,8 +9,12 @@ #include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/parallel/pipeline_schedule.hpp" +#include + namespace duckdb { +class Event; +class InterruptState; class Logger; struct RecursiveExecutorPool { @@ -22,10 +26,49 @@ enum class RecursiveCTESourcePhase : uint8_t { INITIAL, SCANNING_UNION, RECURSING_KEY, + //! A recursive epoch is in progress; its per-iteration setup already ran and must not rerun + EXECUTING_RECURSION, DRAINING_FINAL_KEY_STATE, FINISHED }; +//! Progress of an inline stage within a suspended recursive epoch +enum class RecursiveCTEStageStep : uint8_t { START, PIPELINE_RUNNING, EVENT_WAIT, FINISH_FINALIZE, FINISH_EVENT_WAIT }; + +//! Progress of one recursive epoch across BLOCKED suspensions of the operator's source. +//! ExecuteRecursivePipelines runs its prologue exactly once per epoch, the drive advances this +//! state and suspends by returning BLOCKED up the stack, and the epilogue resets it. +struct RecursiveCTEEpochProgress { + RecursiveCTEEpochProgress(); + ~RecursiveCTEEpochProgress(); + + //! Whether an epoch is in progress (the prologue has run) + bool active = false; + //! Whether this epoch runs the cached inline dependency plan or the event schedule + bool inline_execution = false; + //! Position in the inline ready-stage list and progress within the current stage + idx_t ready_idx = 0; + RecursiveCTEStageStep step = RecursiveCTEStageStep::START; + //! Operator-finalize resume point of a suspended inline finish stage + idx_t finish_operator_idx = 0; + //! Stage event of a suspended inline wait and the wake event that re-enters the source + shared_ptr stage_event; + shared_ptr wake_event; + //! Live events of an event-schedule epoch + vector> events; + //! Prologue decisions and metric snapshots consumed by the epilogue + idx_t max_worker_count = 1; + idx_t scheduler_input_rows = 0; + idx_t frontier_rows = 0; + idx_t frontier_chunks = 0; + idx_t frontier_storage_bytes = 0; + idx_t frontier_allocation_bytes = 0; + idx_t epoch_task_start = 0; + std::chrono::steady_clock::time_point epoch_start; + + void Reset(); +}; + enum class RecursiveCTEPipelineMetricType : uint8_t { RECURSIVE, INVARIANT_BUILD, INVARIANT_CTE_MATERIALIZATION }; //! Epoch-stable secondary index over a proper subset of USING KEY columns. @@ -76,8 +119,21 @@ struct RecursiveCTEScheduleStage { idx_t dependency_count; }; +struct RecursiveCTESchedulePipeline { + RecursiveCTESchedulePipeline(Pipeline &pipeline_p, bool is_invariant_p) + : pipeline(pipeline_p), is_invariant(is_invariant_p) { + } + + reference pipeline; + //! Whether the pipeline's meta-pipeline is invariant; invariant producers keep the configured thread count + bool is_invariant; +}; + struct RecursiveCTEPipelineSchedulePlan { vector stages; + //! Every pipeline of the meta-pipelines this plan schedules, in traversal order, for the per-iteration resets + //! and executor registration; a pipeline shared by two meta-pipelines appears once per meta-pipeline + vector pipelines; vector> initialize_on_schedule_pipelines; //! Deduplicated intermediate operators of this plan's execute stages. Their global operator //! state is invalidated exactly once per iteration, before any stage prepares or executes. @@ -293,9 +349,10 @@ class RecursiveCTEState : public GlobalSinkState { virtual unique_ptr GetLocalSinkState(ExecutionContext &context) const = 0; virtual SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) = 0; virtual SinkCombineResultType Combine(ExecutionContext &context, OperatorSinkCombineInput &input) = 0; - //! Source side: hands out result rows and drives the recursive iterations - virtual SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source) = 0; + //! Source side: hands out result rows and drives the recursive iterations. May return BLOCKED + //! while a recursive epoch waits for blocked inner work; the interrupt state re-enters it. + virtual SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state) = 0; //! Frontier the recursive member scans in the current iteration virtual const ColumnDataCollection &CurrentInputTable() const = 0; //! Rows and chunks of the recurring state the member can scan in the current iteration @@ -326,6 +383,9 @@ class RecursiveCTEState : public GlobalSinkState { const RecursiveCTESchedulerState &GetScheduler() const { return scheduler; } + RecursiveCTEEpochProgress &GetEpochProgress() { + return epoch_progress; + } bool AllowsExecutorReuse() const { return allow_executor_reuse; } @@ -345,6 +405,7 @@ class RecursiveCTEState : public GlobalSinkState { const bool allow_executor_reuse; RecursiveCTEMetrics metrics; RecursiveCTESchedulerState scheduler; + RecursiveCTEEpochProgress epoch_progress; RecursiveCTESourcePhase source_phase = RecursiveCTESourcePhase::INITIAL; //! Whether invariant recursive meta-pipelines have already been materialized for this state bool invariant_meta_pipelines_materialized = false; diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_union_state.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_union_state.hpp index a18c9cd50..019818e9c 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_union_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_union_state.hpp @@ -26,8 +26,8 @@ class RecursiveCTEUnionState : public RecursiveCTEState { unique_ptr GetLocalSinkState(ExecutionContext &context) const override; SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) override; SinkCombineResultType Combine(ExecutionContext &context, OperatorSinkCombineInput &input) override; - SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, - RecursiveCTEGlobalSourceState &source) override; + SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, RecursiveCTEGlobalSourceState &source, + const InterruptState &interrupt_state) override; const ColumnDataCollection &CurrentInputTable() const override; idx_t RecurringStateRows() const override; idx_t RecurringStateChunks() const override; 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 efccfac14..09f472231 100644 --- a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp +++ b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp @@ -192,7 +192,8 @@ class PhysicalPlanGenerator { PhysicalOperator &PlanDelimJoin(LogicalComparisonJoin &op); PhysicalOperator &ExtractAggregateExpressions(PhysicalOperator &child, vector> &expressions, vector> &groups, - optional_ptr> grouping_sets); + optional_ptr> grouping_sets, + bool extract_filters = true); private: ClientContext &context; 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 64a012803..0c2f1ff81 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 @@ -86,6 +86,8 @@ struct RadixHTConfig { static constexpr idx_t AGGREGATE_STATE_PRESSURE_DIVISOR = 2; //! Estimated memory amplification when importing exported states static constexpr idx_t EXPORTED_STATE_MEMORY_MULTIPLIER = 2; + //! Minimum amount of data to combine and scan per thread in the Source phase + static constexpr idx_t MINIMUM_SOURCE_BYTES_PER_THREAD = 262144; }; class RadixHTGlobalSinkState : public GlobalSinkState { @@ -160,6 +162,8 @@ class RadixHTGlobalSinkState : public GlobalSinkState { TupleDataPinProperties scan_pin_properties; //! Total count before combining idx_t count_before_combining; + //! Total size in bytes of the partitions before combining + idx_t size_before_combining; //! Maximum partition size if all unique idx_t max_partition_size; }; diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp index 3d311f634..9e4b5f6f9 100644 --- a/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp @@ -344,8 +344,8 @@ bool ConvertPrimitiveToVariant(ToVariantSourceData &source, ToVariantGlobalResul return ConvertPrimitiveTemplated( source, result, count, selvec, values_index_selvec, empty_payload, is_root); case LogicalTypeId::DECIMAL: { - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; type.GetDecimalProperties(width, scale); DecimalConversionPayloadToVariant payload(width, scale); diff --git a/src/duckdb/src/include/duckdb/function/cast/vector_cast_helpers.hpp b/src/duckdb/src/include/duckdb/function/cast/vector_cast_helpers.hpp index c86a3010b..910dc9040 100644 --- a/src/duckdb/src/include/duckdb/function/cast/vector_cast_helpers.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/vector_cast_helpers.hpp @@ -82,13 +82,13 @@ struct VectorTryCastStringOperator { }; struct VectorDecimalCastData { - VectorDecimalCastData(Vector &result, CastParameters ¶meters, uint8_t width_p, uint8_t scale_p) + VectorDecimalCastData(Vector &result, CastParameters ¶meters, uint32_t width_p, uint32_t scale_p) : vector_cast_data(result, parameters), width(width_p), scale(scale_p) { } VectorTryCastData vector_cast_data; - uint8_t width; - uint8_t scale; + uint32_t width; + uint32_t scale; }; template @@ -149,7 +149,7 @@ struct VectorCastHelpers { template static bool TemplatedDecimalCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters, - uint8_t width, uint8_t scale) { + uint32_t width, uint32_t scale) { VectorDecimalCastData input(result, parameters, width, scale); UnaryExecutor::GenericExecute>(source, result, count, input, parameters.error_message); diff --git a/src/duckdb/src/include/duckdb/function/encoding_function.hpp b/src/duckdb/src/include/duckdb/function/encoding_function.hpp index 86494b701..8e7cd70d1 100644 --- a/src/duckdb/src/include/duckdb/function/encoding_function.hpp +++ b/src/duckdb/src/include/duckdb/function/encoding_function.hpp @@ -13,6 +13,7 @@ #include "duckdb/common/map.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/function/function.hpp" +#include "duckdb/function/map_entry_encoding.hpp" #include "duckdb/storage/data_pointer.hpp" #include "duckdb/storage/storage_info.hpp" @@ -28,14 +29,6 @@ typedef void (*encode_t)(CSVEncoderBuffer &encoded_buffer, char *decoded_buffer, const idx_t decoded_buffer_size, char *remaining_bytes_buffer, idx_t &remaining_bytes_size, EncodingFunction *encoding_function); -//! Encoding Map Entry Struct used for byte replacement -typedef struct { - size_t key_len; - const char *key; - size_t value_len; - const char *value; -} map_entry_encoding; - class EncodingFunction { public: DUCKDB_API EncodingFunction() : encode_function(nullptr), max_bytes_per_iteration(0) { diff --git a/src/duckdb/src/include/duckdb/function/function_binder.hpp b/src/duckdb/src/include/duckdb/function/function_binder.hpp index 265f147ba..86b232459 100644 --- a/src/duckdb/src/include/duckdb/function/function_binder.hpp +++ b/src/duckdb/src/include/duckdb/function/function_binder.hpp @@ -394,6 +394,8 @@ class FunctionBinder { optional_ptr binder; ClientContext &context; + //! Set when the arguments were bound before, so their collations are not pushed again + bool arguments_collated = false; public: //! Overload selection: the cheapest overload of a function set that a call with the given arguments binds to. @@ -409,6 +411,10 @@ class FunctionBinder { DUCKDB_API unique_ptr BindTableFunction(const TableFunctionSet &functions, vector> &positional_arguments, vector>> &named_arguments, ErrorData &error); + //! Select a table in-out function using input column types and bind its named scalar options. + DUCKDB_API unique_ptr + BindTableInOutFunction(const TableFunctionSet &functions, const vector &input_types, + vector>> &named_arguments, ErrorData &error); //! Bind a pragma function, as BindTableFunction binds a table function DUCKDB_API unique_ptr BindPragmaFunction(const PragmaFunctionSet &functions, vector> &positional_arguments, diff --git a/src/duckdb/src/include/duckdb/function/function_serialization.hpp b/src/duckdb/src/include/duckdb/function/function_serialization.hpp index 210890a43..60b222cd4 100644 --- a/src/duckdb/src/include/duckdb/function/function_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/function_serialization.hpp @@ -419,6 +419,7 @@ class FunctionSerializer { // Lookup the function (and the correct overload) FunctionBinder binder(context); + binder.arguments_collated = true; const auto func_idx = FunctionBinder::SelectFunction(context, functions, {positional_types, keyword_types}); // Ensure the function overload was found diff --git a/src/duckdb/src/include/duckdb/function/map_entry_encoding.hpp b/src/duckdb/src/include/duckdb/function/map_entry_encoding.hpp new file mode 100644 index 000000000..85e9d5040 --- /dev/null +++ b/src/duckdb/src/include/duckdb/function/map_entry_encoding.hpp @@ -0,0 +1,24 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/function/map_entry_encoding.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +// Deliberately doesn't include DuckDB headers, so the encodings extension can use compilation caches efficiently. +#include + +namespace duckdb { + +//! Encoding Map Entry Struct used for byte replacement +typedef struct { + size_t key_len; + const char *key; + size_t value_len; + const char *value; +} map_entry_encoding; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/scalar/list/contains_or_position.hpp b/src/duckdb/src/include/duckdb/function/scalar/list/contains_or_position.hpp index 482eb13cb..cca0d2a56 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/list/contains_or_position.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/list/contains_or_position.hpp @@ -34,17 +34,18 @@ idx_t ListSearchSimpleOp(const Vector &input_list, const Vector &list_child, con const bool target_valid = target_entry.IsValid(); + // An empty list never contains anything, not even NULL. + if (list.length == 0 && !return_pos) { + result_data.WriteValue(RETURN_TYPE(false)); + continue; + } + // We are finished, if we are not looking for NULL, and the target is NULL. const auto finished = !FIND_NULLS && !target_valid; // We did not find the target (finished, or list is empty). if (finished || list.length == 0) { - if (finished || return_pos) { - // Return NULL as the position. - result_data.WriteNull(); - } else { - // Set 'contains' to false. - result_data.WriteValue(RETURN_TYPE(false)); - } + // Return NULL as the position. + result_data.WriteNull(); continue; } diff --git a/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp b/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp index a105c1639..d1fb227b4 100644 --- a/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp +++ b/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp @@ -11,21 +11,25 @@ #include "duckdb/common/common.hpp" #include "duckdb/common/optional_idx.hpp" #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/catalog/entry_scan_filters.hpp" #include "duckdb/function/function.hpp" #include "duckdb/function/table_function.hpp" namespace duckdb { -//! Bind data for the system table functions that emit the catalog/schema identity columns -//! (database_name, database_oid, schema_name, schema_oid). Filter pushdown is restricted to these columns. +//! Bind data for the system table functions that emit the identity columns of a catalog entry: the catalog +//! (database_name, database_oid), the schema (schema_name, schema_oid) and the entry itself (e.g. table_name, +//! table_oid). Filter pushdown is restricted to these columns. struct SystemCatalogScannerData : public FunctionData { //! Position of each identity column in the function's output; invalid when the function lacks it. optional_idx database_name_idx; optional_idx database_oid_idx; optional_idx schema_name_idx; optional_idx schema_oid_idx; + optional_idx entry_name_idx; + optional_idx entry_oid_idx; - //! Whether the given column index is one of the four identity columns. + //! Whether the given column index is one of the identity columns. bool IsIdentityColumn(idx_t column_index) const; unique_ptr Copy() const override; @@ -38,20 +42,41 @@ struct SystemCatalogScannerStats { idx_t catalogs_scanned = 0; idx_t schemas_total = 0; idx_t schemas_scanned = 0; + //! Entries the schemas returned (of any type) / entries the filters accepted. + idx_t entries_total = 0; + idx_t entries_scanned = 0; }; class SystemCatalogScanner { public: - //! Bind helper: locate the identity columns by name in `names`. Always returns non-null bind data. - static unique_ptr CreateBindData(const vector &names); - //! Init helper: the schemas that satisfy the pushed-down filters, in Catalog::GetAllSchemas order. - //! Without filters this is exactly Catalog::GetAllSchemas(context). + //! Bind helper: locate the identity columns by name in `names`. A column counts only when its declared type is + //! the one the filters are evaluated against (VARCHAR for names, BIGINT for oids). `entry_name_column` and + //! `entry_oid_column` name the function's entry identity columns (e.g. "table_name", "table_oid"); pass nullptr + //! for a function without them. Always returns non-null bind data. + static unique_ptr CreateBindData(const vector &names, + const vector &return_types, + const char *entry_name_column = nullptr, + const char *entry_oid_column = nullptr); + //! Init helper: the schemas that satisfy the pushed-down catalog and schema filters, in Catalog::GetAllSchemas + //! order. Without such filters this is exactly Catalog::GetAllSchemas(context). static vector> GetSchemas(ClientContext &context, TableFunctionInitInput &input, SystemCatalogScannerStats &stats); + //! Init helper: the pushed-down entry filters of this scan; empty without scanner bind data or filters. + static EntryScanFilters GetEntryFilters(TableFunctionInitInput &input); + //! Init helper: the entries of `type` in one schema that satisfy `filters`, in the order the schema returns them. + //! Every entry the schema returns is re-checked against `filters`. + static vector> GetSchemaEntries(ClientContext &context, SchemaCatalogEntry &schema, + CatalogType type, const EntryScanFilters &filters, + SystemCatalogScannerStats &stats); + //! Init helper: GetSchemaEntries over every schema GetSchemas returns, in that order. Without entry filters this + //! is exactly Scan(type) over those schemas. A function calls either GetSchemas or GetEntries, not both: the + //! catalog and schema counters are incremented by the schema enumeration. + static vector> GetEntries(ClientContext &context, TableFunctionInitInput &input, + CatalogType type, SystemCatalogScannerStats &stats); //! get_metrics helper: writes the counters into input.operator_metrics via AddExtraInfo. static void ReportMetrics(TableFunctionGetMetricsInput &input, const SystemCatalogScannerStats &stats); - //! Enables filter pushdown on the identity columns only. get_metrics is per function because - //! it needs the function's own GlobalTableFunctionState type to reach the stats. + //! Enables filter pushdown on the identity columns only, for filters that cannot throw. get_metrics is per + //! function because it needs the function's own GlobalTableFunctionState type to reach the stats. static void RegisterPushdown(TableFunction &function); }; diff --git a/src/duckdb/src/include/duckdb/function/table_function.hpp b/src/duckdb/src/include/duckdb/function/table_function.hpp index 9b8d54b6a..d9c88962b 100644 --- a/src/duckdb/src/include/duckdb/function/table_function.hpp +++ b/src/duckdb/src/include/duckdb/function/table_function.hpp @@ -378,9 +378,6 @@ typedef bool (*table_function_supports_pushdown_type_t)(const FunctionData &bind typedef bool (*table_function_supports_pushdown_extract_t)(const FunctionData &bind_data, const LogicalIndex &col_idx); -//! Whether repeated executions with the same bound data are stable within one query. -typedef bool (*table_function_is_repeatable_t)(optional_ptr bind_data); - typedef double (*table_function_progress_t)(ClientContext &context, const FunctionData *bind_data, const GlobalTableFunctionState *global_state); typedef void (*table_function_dependency_t)(LogicalDependencyList &dependencies, const FunctionData *bind_data); @@ -532,8 +529,15 @@ class BaseTableFunction { table_function_supports_pushdown_type_t supports_pushdown_type; //! (Optional) If this scanner supports projection pushdown of struct extracts table_function_supports_pushdown_extract_t supports_pushdown_extract; - //! Optional repeatability capability. An absent callback is treated conservatively as unknown. - table_function_is_repeatable_t is_repeatable; + //! The declared stability of the scan's executions. The default CONSISTENT_WITHIN_QUERY guarantees that repeated + //! executions with the same bound data and input rows return equivalent rows within one query, and that changing + //! how often the scan executes has no observable side effects (e.g. no counters, logs, or tables written per + //! execution). Used by optimizers that may share or repeat a scan. Separately bound scans additionally need + //! equivalent identities before their results may be shared - stability alone does not establish that two calls + //! are the same scan. Declare VOLATILE when execution reads live execution state or mutable external state, or + //! writes any state per execution. A stability that depends on the bound call is set during binding through + //! TableFunctionBindInput::table_function instead. + FunctionStability stability = FunctionStability::CONSISTENT_WITHIN_QUERY; //! Get partition info of the table table_function_get_partition_info_t get_partition_info; //! (Optional) get a list of all the partition stats of the table diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp index 3d200fef6..6fce1e628 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp @@ -50,6 +50,13 @@ struct VariantShreddingStats { public: void Update(const Vector &input, idx_t count); + //! A value is nested too deep for the visitors that write the shredded data, so the column stays unshredded + void SetTooDeep() { + too_deep = true; + } + bool IsTooDeep() const { + return too_deep; + } //! If force_partial is set, every level keeps its 'untyped_value_index' (overlay) column even when the //! sampled values are fully consistent - allowing later inconsistent values to be partially shredded. LogicalType GetShreddedType(bool force_partial = false) const; @@ -63,6 +70,7 @@ struct VariantShreddingStats { vector columns; //! Owns the field names referenced by the 'field_stats' of the columns StringHeap field_names; + bool too_deep = false; }; struct VariantShredding { diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp index 7a0e147da..32b5b763e 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp @@ -93,13 +93,13 @@ struct ValueConverter { template static Value VisitDecimal(T val, uint32_t width, uint32_t scale) { if (std::is_same::value) { - return Value::DECIMAL(val, static_cast(width), static_cast(scale)); + return Value::DECIMAL(val, width, scale); } else if (std::is_same::value) { - return Value::DECIMAL(val, static_cast(width), static_cast(scale)); + return Value::DECIMAL(val, width, scale); } else if (std::is_same::value) { - return Value::DECIMAL(val, static_cast(width), static_cast(scale)); + return Value::DECIMAL(val, width, scale); } else if (std::is_same::value) { - return Value::DECIMAL(val, static_cast(width), static_cast(scale)); + return Value::DECIMAL(val, width, scale); } else { throw InternalException("Unhandled decimal type"); } diff --git a/src/duckdb/src/include/duckdb/logging/log_manager.hpp b/src/duckdb/src/include/duckdb/logging/log_manager.hpp index 5d42f6c9e..2115d8bcb 100644 --- a/src/duckdb/src/include/duckdb/logging/log_manager.hpp +++ b/src/duckdb/src/include/duckdb/logging/log_manager.hpp @@ -33,9 +33,14 @@ class LogManager { void Initialize(); DUCKDB_API static LogManager &Get(ClientContext &context); - unique_ptr CreateLogger(LoggingContext context, bool thread_safe = true, bool mutable_settings = false); + unique_ptr CreateLogger(const LoggingContext &context, bool thread_safe = true, + bool mutable_settings = false); + //! Creates a logger from the snapshot without locking, unless the config changed since the snapshot was taken + unique_ptr CreateLogger(const LoggingContext &context, const LogConfigSnapshot &snapshot); + //! Refreshes the snapshot if the config changed since it was taken, and creates a logger from it + unique_ptr CreateLogger(const LoggingContext &context, LogConfigSnapshot &snapshot); - RegisteredLoggingContext RegisterLoggingContext(LoggingContext &context); + RegisteredLoggingContext RegisterLoggingContext(const LoggingContext &context); DUCKDB_API bool RegisterLogStorage(const string &name, shared_ptr &storage); @@ -75,7 +80,7 @@ class LogManager { DUCKDB_API void RegisterDefaultLogTypes(); protected: - RegisteredLoggingContext RegisterLoggingContextInternal(LoggingContext &context); + RegisteredLoggingContext RegisterLoggingContextInternal(const LoggingContext &context); // This is to be called by the Loggers only, it does not verify log_level and log_type void WriteLogEntry(timestamp_t, const char *log_type, LogLevel log_level, const char *log_message, @@ -83,25 +88,33 @@ class LogManager { // This allows efficiently pushing a cached set of log entries into the log manager void FlushCachedLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context); - void SetLogStorageInternal(DatabaseInstance &db, const string &storage_name); + //! 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); - optional_ptr LookupLogTypeInternal(const string &type); + optional_ptr LookupLogTypeInternal(const string &type) DUCKDB_REQUIRES(lock); - void SetConfigInternal(LogConfig config); + //! The only way to change the config: publishes it to the global logger and to newly created loggers + void SetConfigInternal(LogConfig new_config) DUCKDB_REQUIRES(lock); + unique_ptr CreateLoggerInternal(const LoggingContext &context, + const shared_ptr &logger_config); protected: - mutex lock; - LogConfig config; + annotated_mutex lock; + //! Shared by the created loggers; replaced only by SetConfigInternal + shared_ptr config DUCKDB_GUARDED_BY(lock); + //! Incremented whenever config is replaced, invalidating the snapshots of it + PaddedAtomic config_version {0}; shared_ptr global_logger; - shared_ptr log_storage; + shared_ptr log_storage DUCKDB_GUARDED_BY(lock); DatabaseInstance &db_instance; - idx_t next_registered_logging_context_index = 0; + PaddedAtomic next_registered_logging_context_index {0}; // Any additional LogStorages registered (by extensions for example) - case_insensitive_map_t> registered_log_storages; - case_insensitive_map_t> registered_log_types; + case_insensitive_map_t> registered_log_storages DUCKDB_GUARDED_BY(lock); + case_insensitive_map_t> registered_log_types DUCKDB_GUARDED_BY(lock); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/logging/logger.hpp b/src/duckdb/src/include/duckdb/logging/logger.hpp index a5b6d1243..db96d9d72 100644 --- a/src/duckdb/src/include/duckdb/logging/logger.hpp +++ b/src/duckdb/src/include/duckdb/logging/logger.hpp @@ -96,7 +96,7 @@ class Logger { DUCKDB_API virtual bool IsMutable() { return false; }; - DUCKDB_API virtual void UpdateConfig(LogConfig &new_config) { + DUCKDB_API virtual void UpdateConfig(const LogConfig &new_config) { throw InternalException("Cannot update the config of this logger!"); } DUCKDB_API virtual const LogConfig &GetConfig() const = 0; @@ -111,8 +111,7 @@ class Logger { // Thread-safe logger class ThreadSafeLogger : public Logger { public: - explicit ThreadSafeLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager); - explicit ThreadSafeLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager); + ThreadSafeLogger(shared_ptr config_p, RegisteredLoggingContext context_p, LogManager &manager); // Main Logger API bool ShouldLog(const char *log_type, LogLevel log_level) override; @@ -123,12 +122,11 @@ class ThreadSafeLogger : public Logger { return true; } const LogConfig &GetConfig() const override { - return config; + return *config; } protected: - const LogConfig config; - mutex lock; + const shared_ptr config; const RegisteredLoggingContext context; }; @@ -159,8 +157,8 @@ class ThreadLocalLogger : public Logger { // Thread-safe Logger with mutable log settings class MutableLogger : public Logger { public: - explicit MutableLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager); - explicit MutableLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager); + explicit MutableLogger(const LogConfig &config_p, LoggingContext &context_p, LogManager &manager); + explicit MutableLogger(const LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager); // Main Logger API bool ShouldLog(const char *log_type, LogLevel log_level) override; @@ -176,7 +174,7 @@ class MutableLogger : public Logger { const LogConfig &GetConfig() const override { return config; } - void UpdateConfig(LogConfig &new_config) override; + void UpdateConfig(const LogConfig &new_config) override; protected: // Atomics for lock-free log setting checks diff --git a/src/duckdb/src/include/duckdb/logging/logging.hpp b/src/duckdb/src/include/duckdb/logging/logging.hpp index 8c74d38fa..2631046a1 100644 --- a/src/duckdb/src/include/duckdb/logging/logging.hpp +++ b/src/duckdb/src/include/duckdb/logging/logging.hpp @@ -73,4 +73,10 @@ struct RegisteredLoggingContext { LoggingContext context; }; +//! An immutable LogConfig, together with the config version it was published at +struct LogConfigSnapshot { + shared_ptr config; + idx_t version = 0; +}; + } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/active_query_context.hpp b/src/duckdb/src/include/duckdb/main/active_query_context.hpp index 9ab5ef6ee..1f855fdc9 100644 --- a/src/duckdb/src/include/duckdb/main/active_query_context.hpp +++ b/src/duckdb/src/include/duckdb/main/active_query_context.hpp @@ -49,6 +49,8 @@ struct ActiveQueryContext { bool inside_submission = false; //! Whether the statement runs on the CONNECT-ed database, outside the local transaction bool outside_local_transaction = false; + //! Whether the registered states saw the begin of the running statement and not yet its end + bool statement_began = false; public: void SetOpenResult(BaseQueryResult &result) { diff --git a/src/duckdb/src/include/duckdb/main/capi/cast/to_decimal.hpp b/src/duckdb/src/include/duckdb/main/capi/cast/to_decimal.hpp index 39c4ab7e7..f5445070e 100644 --- a/src/duckdb/src/include/duckdb/main/capi/cast/to_decimal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi/cast/to_decimal.hpp @@ -15,8 +15,8 @@ namespace duckdb { template struct ToCDecimalCastWrapper { template - static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { + static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { throw NotImplementedException("Type not implemented for CDecimalCastWrapper"); } }; @@ -25,8 +25,8 @@ struct ToCDecimalCastWrapper { template <> struct ToCDecimalCastWrapper { template - static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { + static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { hugeint_t intermediate_result; if (!TryCastToDecimal::Operation(input, intermediate_result, parameters, width, @@ -34,8 +34,8 @@ struct ToCDecimalCastWrapper { result = FetchDefaultValue::Operation(); return false; } - result.scale = scale; - result.width = width; + result.scale = NumericCast(scale); + result.width = NumericCast(width); duckdb_hugeint hugeint_value; hugeint_value.upper = intermediate_result.upper; @@ -50,8 +50,8 @@ struct ToCDecimalCastWrapper { template <> struct ToCDecimalCastWrapper { template - static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { + static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { int16_t intermediate_result; if (!TryCastToDecimal::Operation(input, intermediate_result, parameters, width, scale)) { @@ -60,8 +60,8 @@ struct ToCDecimalCastWrapper { } hugeint_t hugeint_result = Hugeint::Convert(intermediate_result); - result.scale = scale; - result.width = width; + result.scale = NumericCast(scale); + result.width = NumericCast(width); duckdb_hugeint hugeint_value; hugeint_value.upper = hugeint_result.upper; @@ -74,8 +74,8 @@ struct ToCDecimalCastWrapper { template <> struct ToCDecimalCastWrapper { template - static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { + static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { int32_t intermediate_result; if (!TryCastToDecimal::Operation(input, intermediate_result, parameters, width, scale)) { @@ -84,8 +84,8 @@ struct ToCDecimalCastWrapper { } hugeint_t hugeint_result = Hugeint::Convert(intermediate_result); - result.scale = scale; - result.width = width; + result.scale = NumericCast(scale); + result.width = NumericCast(width); duckdb_hugeint hugeint_value; hugeint_value.upper = hugeint_result.upper; @@ -98,8 +98,8 @@ struct ToCDecimalCastWrapper { template <> struct ToCDecimalCastWrapper { template - static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint8_t width, - uint8_t scale) { + static bool Operation(SOURCE_TYPE input, duckdb_decimal &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { int64_t intermediate_result; if (!TryCastToDecimal::Operation(input, intermediate_result, parameters, width, scale)) { @@ -108,8 +108,8 @@ struct ToCDecimalCastWrapper { } hugeint_t hugeint_result = Hugeint::Convert(intermediate_result); - result.scale = scale; - result.width = width; + result.scale = NumericCast(scale); + result.width = NumericCast(width); duckdb_hugeint hugeint_value; hugeint_value.upper = hugeint_result.upper; @@ -120,7 +120,7 @@ struct ToCDecimalCastWrapper { }; template -duckdb_decimal TryCastToDecimalCInternal(SOURCE_TYPE source, uint8_t width, uint8_t scale) { +duckdb_decimal TryCastToDecimalCInternal(SOURCE_TYPE source, uint32_t width, uint32_t scale) { duckdb_decimal result; try { CastParameters parameters; @@ -134,7 +134,7 @@ duckdb_decimal TryCastToDecimalCInternal(SOURCE_TYPE source, uint8_t width, uint } template -duckdb_decimal TryCastToDecimalCInternal(duckdb_result *result, idx_t col, idx_t row, uint8_t width, uint8_t scale) { +duckdb_decimal TryCastToDecimalCInternal(duckdb_result *result, idx_t col, idx_t row, uint32_t width, uint32_t scale) { return TryCastToDecimalCInternal(UnsafeFetch(result, col, row), width, scale); } diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp index eedc6ce06..c667d34ba 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp @@ -71,40 +71,49 @@ namespace capiv2 { //---------------------------------------------------------------------------------------------------------------------- // Conversion Helpers //---------------------------------------------------------------------------------------------------------------------- -inline auto Convert(duckdb_v2_str str) -> std::string_view { - if (!str.ptr) { - if (str.len > 0) { +inline auto Convert(const char *ptr, idx_t len) -> std::string_view { + if (!ptr) { + if (len > 0) { throw InvalidInputException("byte range cannot be null unless it is empty"); } return std::string_view(); } - return std::string_view(str.ptr, str.len); + return std::string_view(ptr, len); } -inline auto Convert(const duckdb_v2_str *str) -> std::string_view { - if (!str) { - throw InvalidInputException("byte range cannot be null"); - } - return Convert(*str); +// Writes a borrowed string to an out-param pointer/length pair. +inline void SetStringOut(const char **out, idx_t *out_length, std::string_view str) { + *out = str.data(); + *out_length = str.size(); +} +inline void SetStringOut(const char **out, idx_t *out_length, const Identifier &ident) { + *out = ident.c_str(); + *out_length = ident.size(); } -// Validates identifier UTF-8 and returns its text; throws on invalid input. Defined in capi_v2_utf8.cpp. -auto ConvertIdentifierName(duckdb_v2_identifier_t name) -> std::string_view; -inline auto ConvertIdentifierName(const duckdb_v2_identifier_t *name) -> std::string_view { - if (!name) { - throw InvalidInputException("identifier cannot be null"); +//! A borrowed, parallel pointer/length UTF-8 string array of `count` entries as passed through the API. A NULL array +//! reads as all-empty entries. +class string_view_array { +public: + string_view_array(const char **ptrs, const idx_t *lengths, idx_t count) + : ptrs(ptrs), lengths(lengths), count(count) { } - return ConvertIdentifierName(*name); -} -inline auto Convert(std::string_view str) -> duckdb_v2_str { - return duckdb_v2_str {str.data(), str.size()}; -} -inline auto Convert(const string &str) -> duckdb_v2_str { - return duckdb_v2_str {str.data(), str.size()}; -} -inline auto Convert(const Identifier &ident) -> duckdb_v2_identifier_t { - return duckdb_v2_identifier_t {ident.c_str(), ident.size()}; -} +public: + bool empty() const { + return !ptrs || count == 0; + } + //! Validates entry `i` and returns it; throws on a malformed entry or invalid UTF-8. Defined in capi_v2_utf8.cpp. + std::string_view operator[](idx_t i) const; + +private: + const char **ptrs; + const idx_t *lengths; + idx_t count; +}; + +// Validates identifier UTF-8 and returns its text; throws on invalid input. Defined in capi_v2_utf8.cpp. +auto ConvertIdentifierName(const char *name, idx_t name_length) -> std::string_view; + inline auto Convert(duckdb_v2_hugeint_t value) -> hugeint_t { return hugeint_t(value.upper, value.lower); } @@ -735,8 +744,9 @@ bool IsNullArgument(const T &arg) { return arg == nullptr; } -inline bool IsNullArgument(const duckdb_v2_str *arg) { - return !arg || (!arg->ptr && arg->len > 0); +// A string argument is invalid when its pointer is null while it carries a non-zero length. +inline bool IsNullArgument(const char *arg, idx_t arg_length) { + return !arg && arg_length > 0; } // Check if an argument is null and return DUCKDB_V2_ERROR_INPUT_INVALID with a message if it is. @@ -748,6 +758,13 @@ inline bool IsNullArgument(const duckdb_v2_str *arg) { return duckdb::capiv2::NullArgumentError(err, __func__, #arg); \ } \ } while (0) +// The pointer/length form of DUCKDB_CHECK_ARG for a string argument. +#define DUCKDB_CHECK_STR_ARG(arg, arg_length) \ + do { \ + if (duckdb::capiv2::IsNullArgument(arg, arg_length)) { \ + return duckdb::capiv2::NullArgumentError(err, __func__, #arg); \ + } \ + } while (0) // Error code <-> exception type conversion auto GetErrorCodeFromExceptionType(ExceptionType type) -> DUCKDB_V2_ERROR; @@ -851,7 +868,7 @@ struct ConnectionBusySlotV2 : public ClientContextState { inline shared_ptr GetBusySlot(ClientContext &context) { constexpr auto BUSY_SLOT_STATE_KEY = "v2_connection_busy_slot"; - return context.registered_state->GetOrCreate(BUSY_SLOT_STATE_KEY); + return context.GetContext().GetRegisteredState().GetOrCreate(BUSY_SLOT_STATE_KEY); } //---------------------------------------------------------------------------------------------------------------------- @@ -861,11 +878,11 @@ inline shared_ptr GetBusySlot(ClientContext &context) { //! the sink sees the full length up front. Its only influence on the outcome is //! the error slot: a code it sets is rethrown as the matching exception type, //! which WithErrorHandler then maps straight back. -inline void InvokeTextSink(duckdb_v2_text_sink_fn sink, duckdb_v2_str text, void *user_data) { +inline void InvokeTextSink(duckdb_v2_text_sink_fn sink, std::string_view text, void *user_data) { // The slot is always live: sinks populate it, they never allocate or destroy it. CV2ErrorInfo info; auto handle = Convert(&info); - sink(&text, user_data, &handle); + sink(text.data(), text.size(), user_data, &handle); if (info.HasError()) { info.ThrowAsException(); } @@ -980,21 +997,16 @@ class CV2UserData { // Misc //---------------------------------------------------------------------------------------------------------------------- -inline void BuildParameterMap(const duckdb_v2_identifier_t *parameter_names, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - const char *function_name, identifier_map_t &out) { +inline void BuildParameterMap(const string_view_array ¶meter_names, const duckdb_v2_value_handle *parameter_values, + idx_t parameter_count, const char *function_name, + identifier_map_t &out) { for (idx_t i = 0; i < parameter_count; i++) { - auto name = parameter_names ? parameter_names[i] : duckdb_v2_identifier_t {nullptr, 0}; - // A {NULL, 0} view is a valid (empty) name; only a null pointer with a nonzero length is malformed. - if (!name.ptr && name.len > 0) { - throw InvalidInputException("malformed parameter name passed to %s", function_name); - } + // Named iff the name is non-empty; otherwise positional + auto name = parameter_names[i]; if (!parameter_values[i]) { throw InvalidInputException("null parameter value passed to %s", function_name); } - // Named iff the name view is non-empty; otherwise positional - auto str = ConvertIdentifierName(name); - Identifier key = (name.ptr && name.len > 0) ? Identifier(str) : Identifier(std::to_string(i + 1)); + Identifier key = name.empty() ? Identifier(std::to_string(i + 1)) : Identifier(name); out[key] = BoundParameterData(*Convert(parameter_values[i])); } } diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_result_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_result_internal.hpp index 031190fa6..ccf74b914 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_result_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_result_internal.hpp @@ -122,7 +122,7 @@ auto Convert(duckdb_v2_arrow_result_handle handle) -> ResultWrapperV2 *; //! Submits a borrowed statement in `format`. Throws ResourceInUseException while a statement on the connection is //! still running. auto ExecuteStatementV2(const shared_ptr &context, const SQLStatement &statement, - const duckdb_v2_identifier_t *parameter_names, const duckdb_v2_value_handle *parameter_values, + const string_view_array ¶meter_names, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, const char *function_name, shared_ptr format) -> unique_ptr; //! Runs a prepared statement. `context` is the session the result holds on to, so it 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 ff958b0a6..d11b1acbe 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 @@ -53,7 +53,7 @@ typedef struct { (duckdb_v2_config_handle config, idx_t index, duckdb_v2_option_handle *out_option, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_get_option_by_name) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, duckdb_v2_option_handle *out_option, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_option_handle *out_option, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_get_option_count) (duckdb_v2_config_handle config, idx_t *out_count, duckdb_v2_error_info_handle *err); @@ -86,46 +86,51 @@ typedef struct { (duckdb_v2_environment_handle env, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_error_info_destroy)(duckdb_v2_error_info_handle *info); DUCKDB_V2_ERROR (*duckdb_v2_error_info_get_code)(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR *out_code); - DUCKDB_V2_ERROR (*duckdb_v2_error_info_get_raw_text)(duckdb_v2_error_info_handle info, duckdb_v2_str *out_raw_text); - DUCKDB_V2_ERROR (*duckdb_v2_error_info_get_text)(duckdb_v2_error_info_handle info, duckdb_v2_str *out_text); + DUCKDB_V2_ERROR(*duckdb_v2_error_info_get_raw_text) + (duckdb_v2_error_info_handle info, const char **out_raw_text, idx_t *out_raw_text_length); + DUCKDB_V2_ERROR(*duckdb_v2_error_info_get_text) + (duckdb_v2_error_info_handle info, const char **out_text, idx_t *out_text_length); DUCKDB_V2_ERROR (*duckdb_v2_error_info_set_code)(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR code); - DUCKDB_V2_ERROR (*duckdb_v2_error_info_set_text)(duckdb_v2_error_info_handle info, const duckdb_v2_str *text); + DUCKDB_V2_ERROR(*duckdb_v2_error_info_set_text) + (duckdb_v2_error_info_handle info, const char *text, idx_t text_length); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_id) - (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_name) - (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_text) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *text, duckdb_v2_logical_type_handle *out_type, + (duckdb_v2_factory_handle factory, const char *text, idx_t text_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_with_alias) - (duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle base_type, - const duckdb_v2_identifier_t *alias_name, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle base_type, const char *alias_name, + idx_t alias_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_attach) - (duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, const duckdb_v2_str *path, + (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, const char *path, idx_t path_length, duckdb_v2_attach_options_handle options, bool make_default, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_create) (duckdb_v2_environment_handle env, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_create_with_options) - (duckdb_v2_environment_handle env, const duckdb_v2_str *option_names, const duckdb_v2_str *option_values, - idx_t option_count, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); + (duckdb_v2_environment_handle env, const char **option_names, const idx_t *option_names_lengths, + const char **option_values, const idx_t *option_values_lengths, idx_t option_count, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_instance_destroy)(duckdb_v2_instance_handle *instance); DUCKDB_V2_ERROR(*duckdb_v2_instance_detach) - (duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR (*duckdb_v2_library_version)(duckdb_v2_str *out_version, duckdb_v2_error_info_handle *err); + (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_library_version) + (const char **out_version, idx_t *out_version_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_copy) (duckdb_v2_logical_type_handle type, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_logical_type_destroy)(duckdb_v2_logical_type_handle *type); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_id) (duckdb_v2_logical_type_handle type, DUCKDB_V2_LOGICAL_TYPE_ID *out_id, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_name) - (duckdb_v2_logical_type_handle type, duckdb_v2_identifier_t *out_name, duckdb_v2_error_info_handle *err); + (duckdb_v2_logical_type_handle type, const char **out_name, idx_t *out_name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_param) - (duckdb_v2_logical_type_handle type, idx_t index, duckdb_v2_identifier_t *out_name, + (duckdb_v2_logical_type_handle type, idx_t index, const char **out_name, idx_t *out_name_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_param_count) (duckdb_v2_logical_type_handle type, idx_t *out_count, duckdb_v2_error_info_handle *err); @@ -137,17 +142,19 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_option_destroy)(duckdb_v2_option_handle *option); DUCKDB_V2_ERROR(*duckdb_v2_option_get_alias) - (duckdb_v2_option_handle option, idx_t index, duckdb_v2_identifier_t *out_alias, duckdb_v2_error_info_handle *err); + (duckdb_v2_option_handle option, idx_t index, const char **out_alias, idx_t *out_alias_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_alias_count) (duckdb_v2_option_handle option, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_default_value) (duckdb_v2_option_handle option, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_description) - (duckdb_v2_option_handle option, duckdb_v2_str *out_description, duckdb_v2_error_info_handle *err); + (duckdb_v2_option_handle option, const char **out_description, idx_t *out_description_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_name) - (duckdb_v2_option_handle option, duckdb_v2_identifier_t *out_name, duckdb_v2_error_info_handle *err); + (duckdb_v2_option_handle option, const char **out_name, idx_t *out_name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_parse_sql) - (duckdb_v2_connection_handle conn, const char *sql, bool apply_invalidation_policy, + (duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, bool apply_invalidation_policy, duckdb_v2_statement_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_result_destroy)(duckdb_v2_result_handle *result); DUCKDB_V2_ERROR(*duckdb_v2_result_drain) @@ -161,8 +168,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_result_get_statement_type) (duckdb_v2_result_handle result, DUCKDB_V2_STATEMENT_TYPE *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_result_render_box) - (duckdb_v2_result_handle *result, idx_t max_rows, idx_t max_width, idx_t max_col_width, - const duckdb_v2_str *null_value, idx_t render_mode, idx_t limit, duckdb_v2_text_sink_fn sink, void *user_data, + (duckdb_v2_result_handle *result, idx_t max_rows, idx_t max_width, idx_t max_col_width, const char *null_value, + idx_t null_value_length, idx_t render_mode, idx_t limit, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_result_step) (duckdb_v2_result_handle result, duckdb_v2_data_chunk_handle *out_chunk, DUCKDB_V2_RESULT_STEP_STATUS *out_status, @@ -172,16 +179,16 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_schema_get_count) (duckdb_v2_schema_handle schema, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_schema_get_field) - (duckdb_v2_schema_handle schema, idx_t index, duckdb_v2_identifier_t *out_name, + (duckdb_v2_schema_handle schema, idx_t index, const char **out_name, idx_t *out_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_sql_statement_destroy)(duckdb_v2_sql_statement_handle *statement); DUCKDB_V2_ERROR(*duckdb_v2_statement_bind) (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, duckdb_v2_schema_handle *out_schema, duckdb_v2_schema_handle *out_parameters, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_statement_iterator_destroy)(duckdb_v2_statement_iterator_handle *iterator); DUCKDB_V2_ERROR(*duckdb_v2_statement_iterator_next) (duckdb_v2_statement_iterator_handle iterator, duckdb_v2_sql_statement_handle *out_statement, @@ -196,13 +203,13 @@ typedef struct { (duckdb_v2_factory_handle factory, int64_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_bignum) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_bit) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_blob) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_bool) (duckdb_v2_factory_handle factory, bool in_value, duckdb_v2_value_handle *out_value, @@ -242,8 +249,9 @@ typedef struct { (duckdb_v2_factory_handle factory, int16_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_struct) - (duckdb_v2_factory_handle factory, const duckdb_v2_identifier_t *names, const duckdb_v2_value_handle *children, - idx_t field_count, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, const char **names, const idx_t *names_lengths, + const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_time) (duckdb_v2_factory_handle factory, int64_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); @@ -299,13 +307,13 @@ typedef struct { (duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_varchar) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_value_destroy)(duckdb_v2_value_handle *value); DUCKDB_V2_ERROR(*duckdb_v2_value_get_bigint) (duckdb_v2_value_handle value, int64_t *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_blob) - (duckdb_v2_value_handle value, duckdb_v2_str *out, duckdb_v2_error_info_handle *err); + (duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_bool) (duckdb_v2_value_handle value, bool *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_child) @@ -366,7 +374,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_value_get_uuid) (duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_varchar) - (duckdb_v2_value_handle value, duckdb_v2_str *out, duckdb_v2_error_info_handle *err); + (duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_is_null) (duckdb_v2_value_handle value, bool *out_is_null, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_to_string) @@ -410,12 +418,12 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_register_scalar_function) (duckdb_v2_connection_handle conn, duckdb_v2_scalar_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_log) - (duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + (duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, const char *log_type, idx_t log_type_length, + const char *message, idx_t message_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_scalar_function) (duckdb_v2_extension_handle extension, duckdb_v2_scalar_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_signature_add_parameter) - (duckdb_v2_function_signature_handle sig, const duckdb_v2_identifier_t *name, duckdb_v2_logical_type_handle type, + (duckdb_v2_function_signature_handle sig, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_value_handle value, DUCKDB_V2_FUNCTION_PARAMETER_KIND kind, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_signature_set_return_type) (duckdb_v2_function_signature_handle sig, duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); @@ -458,7 +466,7 @@ typedef struct { (duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_init_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_name) - (duckdb_v2_scalar_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_user_data) (duckdb_v2_scalar_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_bind_set_return_type) @@ -525,7 +533,7 @@ typedef struct { (duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_init_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_name) - (duckdb_v2_aggregate_function_handle function, const duckdb_v2_identifier_t *name, + (duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_size_callback) (duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_size_callback_fn callback, @@ -571,7 +579,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_extension_register_table_function) (duckdb_v2_extension_handle extension, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_add_result_column) - (duckdb_v2_table_function_bind_info_handle info, const duckdb_v2_identifier_t *name, + (duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_set_cardinality) (duckdb_v2_table_function_bind_info_handle info, idx_t cardinality, bool is_exact, @@ -630,7 +638,7 @@ typedef struct { (duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_local_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_name) - (duckdb_v2_table_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_table_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_progress_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_progress_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -678,7 +686,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_custom_type_set_base_type) (duckdb_v2_custom_type_handle type, duckdb_v2_logical_type_handle base_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_type_set_name) - (duckdb_v2_custom_type_handle type, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_custom_type_handle type, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_cast_function) (duckdb_v2_extension_handle extension, duckdb_v2_cast_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_custom_type) @@ -694,7 +702,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_file_open_options_set_flag) (duckdb_v2_file_open_options_handle options, DUCKDB_V2_FILE_FLAG flag, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_open_options_set_value) - (duckdb_v2_file_open_options_handle options, const duckdb_v2_str *name, duckdb_v2_value_handle value, + (duckdb_v2_file_open_options_handle options, const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_read) (duckdb_v2_file_handle file, void *buffer, idx_t buffer_size, idx_t *bytes_read, duckdb_v2_error_info_handle *err); @@ -705,7 +713,7 @@ typedef struct { DUCKDB_V2_ERROR (*duckdb_v2_file_size)(duckdb_v2_file_handle file, idx_t *size, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_file_sync)(duckdb_v2_file_handle file, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_open) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *file_path, + (duckdb_v2_file_system_handle file_system, const char *file_path, idx_t file_path_length, duckdb_v2_file_open_options_handle options, duckdb_v2_file_handle *file, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_tell) (duckdb_v2_file_handle file, idx_t *position, duckdb_v2_error_info_handle *err); @@ -718,26 +726,26 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_register_replacement_scan) (duckdb_v2_instance_handle instance, duckdb_v2_replacement_scan_handle scan, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_create) - (const duckdb_v2_identifier_t *parts, idx_t part_count, duckdb_v2_qname_handle *name, + (const char **parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_qname_destroy)(duckdb_v2_qname_handle *name); DUCKDB_V2_ERROR(*duckdb_v2_qname_equals) (duckdb_v2_qname_handle left, duckdb_v2_qname_handle right, bool *result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_get_part) - (duckdb_v2_qname_handle name, idx_t index, duckdb_v2_identifier_t *part, duckdb_v2_error_info_handle *err); + (duckdb_v2_qname_handle name, idx_t index, const char **part, idx_t *part_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_get_part_count) (duckdb_v2_qname_handle name, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_hash) (duckdb_v2_qname_handle name, uint64_t *hash, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_parse) - (const duckdb_v2_str *text, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); + (const char *text, idx_t text_length, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_render) (duckdb_v2_qname_handle name, char *out_text, idx_t out_capacity, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_add_argument) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_add_named_argument) - (duckdb_v2_replacement_scan_info_handle info, const duckdb_v2_identifier_t *name, duckdb_v2_value_handle value, + (duckdb_v2_replacement_scan_info_handle info, const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_create) (duckdb_v2_factory_handle factory, duckdb_v2_replacement_scan_handle *scan, duckdb_v2_error_info_handle *err); @@ -747,26 +755,28 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_get_user_data) (duckdb_v2_replacement_scan_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_alias) - (duckdb_v2_replacement_scan_info_handle info, const duckdb_v2_identifier_t *alias, + (duckdb_v2_replacement_scan_info_handle info, const char *alias, idx_t alias_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_callback) (duckdb_v2_replacement_scan_handle scan, duckdb_v2_replacement_scan_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_collection) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const duckdb_v2_identifier_t *column_names, idx_t column_count, duckdb_v2_error_info_handle *err); + 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_replacement_scan_set_function_name) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_qname_handle name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_subquery) - (duckdb_v2_replacement_scan_info_handle info, const duckdb_v2_str *sql, duckdb_v2_error_info_handle *err); + (duckdb_v2_replacement_scan_info_handle info, const char *sql, idx_t sql_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_user_data) (duckdb_v2_replacement_scan_handle scan, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_append) (duckdb_v2_arrow_exporter_handle exporter, duckdb_v2_data_chunk_handle *chunk, bool consume, bool flush, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_create) - (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const duckdb_v2_str *names, - idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err); + (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const char **names, + const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_arrow_exporter_destroy)(duckdb_v2_arrow_exporter_handle *exporter); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_get_schema) (duckdb_v2_arrow_exporter_handle exporter, struct ArrowSchema *out_schema, duckdb_v2_error_info_handle *err); @@ -786,7 +796,8 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_column_description_destroy)(duckdb_v2_column_description_handle *column); DUCKDB_V2_ERROR(*duckdb_v2_column_description_get_name) - (duckdb_v2_column_description_handle column, duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_column_description_handle column, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_column_description_get_type) (duckdb_v2_column_description_handle column, duckdb_v2_logical_type_handle *type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_column_description_has_default) @@ -801,17 +812,18 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_column_count) (duckdb_v2_copy_from_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_column_name) - (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_from_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_column_type) (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_file_path) - (duckdb_v2_copy_from_bind_info_handle info, duckdb_v2_str *path, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_from_bind_info_handle info, const char **path, idx_t *path_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_option_count) (duckdb_v2_copy_from_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_option_name) - (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_from_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_option_value) (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_value_handle *value, @@ -875,7 +887,7 @@ typedef struct { (duckdb_v2_factory_handle factory, duckdb_v2_copy_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_copy_function_destroy)(duckdb_v2_copy_function_handle *function); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_set_name) - (duckdb_v2_copy_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_set_user_data) (duckdb_v2_copy_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_batch_get_bind_data) @@ -898,17 +910,17 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_column_count) (duckdb_v2_copy_to_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_column_name) - (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_to_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_column_type) (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_file_path) - (duckdb_v2_copy_to_bind_info_handle info, duckdb_v2_str *path, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_to_bind_info_handle info, const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_option_count) (duckdb_v2_copy_to_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_option_name) - (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_to_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_option_value) (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_value_handle *value, @@ -934,7 +946,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_get_bind_data) (duckdb_v2_copy_to_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_get_file_path) - (duckdb_v2_copy_to_init_info_handle info, duckdb_v2_str *path, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_to_init_info_handle info, const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_get_user_data) (duckdb_v2_copy_to_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_set_init_data) @@ -964,7 +976,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_expression_constant_get_value) (duckdb_v2_expression_handle expression, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_function_get_name) - (duckdb_v2_expression_handle expression, duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_expression_handle expression, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_function_get_qname) (duckdb_v2_expression_handle expression, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_get_child) @@ -979,14 +991,14 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_extension_register_copy_function) (duckdb_v2_extension_handle extension, duckdb_v2_copy_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_identifier_render_quoted) - (const duckdb_v2_identifier_t *name, char *out_text, idx_t out_capacity, idx_t *out_length, + (const char *name, idx_t name_length, char *out_text, idx_t out_capacity, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_create) (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, bool require_cacheable, duckdb_v2_prepared_statement_handle *out_prepared, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_prepared_statement_destroy)(duckdb_v2_prepared_statement_handle *prepared); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute) - (duckdb_v2_prepared_statement_handle prepared, const duckdb_v2_identifier_t *parameter_names, + (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_reuses_plan) @@ -1040,10 +1052,11 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_parameter_count) (duckdb_v2_sql_statement_handle statement, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_parameter_name) - (duckdb_v2_sql_statement_handle statement, idx_t index, duckdb_v2_identifier_t *out_name, + (duckdb_v2_sql_statement_handle statement, idx_t index, const char **out_name, idx_t *out_name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_text) - (duckdb_v2_sql_statement_handle statement, duckdb_v2_str *out_text, duckdb_v2_error_info_handle *err); + (duckdb_v2_sql_statement_handle statement, const char **out_text, idx_t *out_text_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_type) (duckdb_v2_sql_statement_handle statement, DUCKDB_V2_STATEMENT_TYPE *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_token_iterator_destroy)(duckdb_v2_token_iterator_handle *iterator); @@ -1053,17 +1066,17 @@ typedef struct { (duckdb_v2_token_iterator_handle iterator, DUCKDB_V2_TOKEN_TYPE *out_type, idx_t *out_start, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_tokenize_sql) - (duckdb_v2_connection_handle conn, const duckdb_v2_str *sql, duckdb_v2_token_iterator_handle *out_iterator, + (duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, duckdb_v2_token_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_attach_options_create) (duckdb_v2_instance_handle instance, duckdb_v2_attach_options_handle *out_options, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_attach_options_destroy)(duckdb_v2_attach_options_handle *options); DUCKDB_V2_ERROR(*duckdb_v2_attach_options_set) - (duckdb_v2_attach_options_handle options, const duckdb_v2_identifier_t *key, const duckdb_v2_str *setting, - duckdb_v2_error_info_handle *err); + (duckdb_v2_attach_options_handle options, const char *key, idx_t key_length, const char *setting, + idx_t setting_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_set_default) - (duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_bind_data) (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_global_state) @@ -1104,7 +1117,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_partitioning_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR (*duckdb_v2_validate_utf8)(const duckdb_v2_str *text, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_validate_utf8)(const char *text, idx_t text_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_multi_file_function) (duckdb_v2_connection_handle conn, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_set_statistics_callback) @@ -1130,13 +1143,17 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_multi_file_function_destroy)(duckdb_v2_multi_file_function_handle *function); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_file_extension) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *extension, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *extension, idx_t extension_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_name) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_reader_type) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *reader_type, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *reader_type, idx_t reader_type_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_single_file_function) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_bind_data) (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_global_state) @@ -1154,10 +1171,10 @@ typedef struct { (duckdb_v2_function_bind_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_index) - (duckdb_v2_function_bind_info_handle info, const duckdb_v2_identifier_t *name, idx_t *index, bool *found, + (duckdb_v2_function_bind_info_handle info, const char *name, idx_t name_length, idx_t *index, bool *found, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_name) - (duckdb_v2_function_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_type) (duckdb_v2_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, @@ -1191,14 +1208,13 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_arrow_result_wait) (duckdb_v2_arrow_result_handle result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute_arrow) - (duckdb_v2_prepared_statement_handle prepared, const duckdb_v2_identifier_t *parameter_names, + (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute_arrow) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, - duckdb_v2_error_info_handle *err); + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_stats_callback) (duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_stats_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1263,8 +1279,8 @@ typedef struct { (duckdb_v2_table_function_get_bind_info_info_handle info, idx_t column_index, const idx_t *child_path, idx_t child_path_length, duckdb_v2_value_handle identifier, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_get_bind_info_set_option) - (duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_str *key, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); + (duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_get_bind_info_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_get_bind_info_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1277,21 +1293,21 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_set_bind_data) (duckdb_v2_scalar_function_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_get_option_value) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, duckdb_v2_value_handle *out_value, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_value_handle *out_value, DUCKDB_V2_SETTING_SCOPE *out_scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_set_option_text) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, const duckdb_v2_str *setting, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, const char *setting, idx_t setting_length, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_set_option_value) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, duckdb_v2_value_handle value, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_value_handle value, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_get_config) (duckdb_v2_connection_handle conn, duckdb_v2_config_handle *out_config, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_get_file_system) (duckdb_v2_connection_handle conn, duckdb_v2_file_system_handle *file_system, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_log) - (duckdb_v2_connection_handle conn, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + (duckdb_v2_connection_handle conn, DUCKDB_V2_LOG_LEVEL level, const char *log_type, idx_t log_type_length, + const char *message, idx_t message_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_get_config) (duckdb_v2_context_handle ctx, duckdb_v2_config_handle *out_config, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_get_config) @@ -1299,8 +1315,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_get_file_system) (duckdb_v2_instance_handle instance, duckdb_v2_file_system_handle *file_system, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_log) - (duckdb_v2_instance_handle instance, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + (duckdb_v2_instance_handle instance, DUCKDB_V2_LOG_LEVEL level, const char *log_type, idx_t log_type_length, + const char *message, idx_t message_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_default_scope) (duckdb_v2_option_handle option, DUCKDB_V2_SETTING_SCOPE *out_scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_supports_scope) @@ -1317,12 +1333,14 @@ typedef struct { (duckdb_v2_factory_handle factory, const duckdb_v2_logical_type_handle *types, idx_t type_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_docs_add_category) - (duckdb_v2_function_docs_handle docs, const duckdb_v2_str *category, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_function_docs_add_example) - (duckdb_v2_function_docs_handle docs, const duckdb_v2_str *title, const duckdb_v2_str *example, + (duckdb_v2_function_docs_handle docs, const char *category, idx_t category_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_function_docs_add_example) + (duckdb_v2_function_docs_handle docs, const char *title, idx_t title_length, const char *example, + idx_t example_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_docs_set_description) - (duckdb_v2_function_docs_handle docs, const duckdb_v2_str *description, duckdb_v2_error_info_handle *err); + (duckdb_v2_function_docs_handle docs, const char *description, idx_t description_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_pragma_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_pragma_function_destroy)(duckdb_v2_pragma_function_handle *function); @@ -1332,12 +1350,13 @@ typedef struct { (duckdb_v2_pragma_function_handle function, duckdb_v2_function_signature_handle *sig, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_query_set_query) - (duckdb_v2_pragma_function_query_info_handle info, const duckdb_v2_str *query, duckdb_v2_error_info_handle *err); + (duckdb_v2_pragma_function_query_info_handle info, const char *query, idx_t query_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_set_exec_callback) (duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_exec_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_set_name) - (duckdb_v2_pragma_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_pragma_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_set_query_callback) (duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_query_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1357,9 +1376,10 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_default_value) (duckdb_v2_custom_option_handle option, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_description) - (duckdb_v2_custom_option_handle option, const duckdb_v2_str *description, duckdb_v2_error_info_handle *err); + (duckdb_v2_custom_option_handle option, const char *description, idx_t description_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_name) - (duckdb_v2_custom_option_handle option, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_custom_option_handle option, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_supports_scope) (duckdb_v2_custom_option_handle option, DUCKDB_V2_SETTING_SCOPE scope, bool supported, duckdb_v2_error_info_handle *err); @@ -1387,13 +1407,13 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_extension_register_macro_function) (duckdb_v2_extension_handle extension, duckdb_v2_macro_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_exists) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, bool *out_exists, + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, bool *out_exists, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_expand) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, duckdb_v2_text_sink_fn sink, void *user_data, - duckdb_v2_error_info_handle *err); + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, duckdb_v2_text_sink_fn sink, + void *user_data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_is_remote) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, bool *out_is_remote, + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, bool *out_is_remote, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_register_log_sink) (duckdb_v2_instance_handle instance, duckdb_v2_log_sink_handle sink, duckdb_v2_error_info_handle *err); @@ -1403,7 +1423,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_flush_callback) (duckdb_v2_log_sink_handle sink, duckdb_v2_log_sink_flush_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_name) - (duckdb_v2_log_sink_handle sink, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_log_sink_handle sink, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_user_data) (duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_write_callback) @@ -1426,9 +1446,9 @@ typedef struct { (duckdb_v2_macro_function_handle function, duckdb_v2_function_signature_handle *sig, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_macro_function_set_body) - (duckdb_v2_macro_function_handle function, const duckdb_v2_str *body, duckdb_v2_error_info_handle *err); + (duckdb_v2_macro_function_handle function, const char *body, idx_t body_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_macro_function_set_name) - (duckdb_v2_macro_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_macro_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_vector_cast) (duckdb_v2_factory_handle factory, duckdb_v2_vector_handle source, duckdb_v2_vector_handle target, DUCKDB_V2_CAST_MODE mode, bool *out_converted, duckdb_v2_error_info_handle *cast_err, @@ -1438,16 +1458,17 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_get_query_metrics) (duckdb_v2_connection_handle conn, duckdb_v2_query_metrics_handle *metrics, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_set_file_extension) - (duckdb_v2_copy_function_handle function, const duckdb_v2_str *extension, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_function_handle function, const char *extension, idx_t extension_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_data_chunk_clear)(duckdb_v2_data_chunk_handle chunk, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_glob) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *pattern, + (duckdb_v2_file_system_handle file_system, const char *pattern, idx_t pattern_length, duckdb_v2_file_system_path_glob_callback_fn callback, void *user_data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_move) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *source, const duckdb_v2_str *target, - duckdb_v2_error_info_handle *err); + (duckdb_v2_file_system_handle file_system, const char *source, idx_t source_length, const char *target, + idx_t target_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_remove) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, bool *out_removed, + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, bool *out_removed, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_query_metrics_destroy)(duckdb_v2_query_metrics_handle *metrics); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_get_root) @@ -1459,21 +1480,22 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_child_count) (duckdb_v2_query_metrics_node_handle node, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric) - (duckdb_v2_query_metrics_node_handle node, const duckdb_v2_str *name, duckdb_v2_value_handle *value, bool *present, - duckdb_v2_error_info_handle *err); + (duckdb_v2_query_metrics_node_handle node, const char *name, idx_t name_length, duckdb_v2_value_handle *value, + bool *present, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric_count) (duckdb_v2_query_metrics_node_handle node, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric_name) - (duckdb_v2_query_metrics_node_handle node, idx_t index, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_query_metrics_node_handle node, idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric_value) (duckdb_v2_query_metrics_node_handle node, idx_t index, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_name) - (duckdb_v2_query_metrics_node_handle node, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_query_metrics_node_handle node, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_add_collection) - (duckdb_v2_sql_statement_handle statement, const duckdb_v2_identifier_t *name, - duckdb_v2_column_data_collection_handle collection, const duckdb_v2_identifier_t *column_names, idx_t column_count, - duckdb_v2_error_info_handle *err); + (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_ext_api_v2; //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/main/client_config.hpp b/src/duckdb/src/include/duckdb/main/client_config.hpp index cddfde387..fa0256cab 100644 --- a/src/duckdb/src/include/duckdb/main/client_config.hpp +++ b/src/duckdb/src/include/duckdb/main/client_config.hpp @@ -27,6 +27,14 @@ class PreparedStatementData; struct CompiledGrammar; struct ReplacementScan; +//! The grammar a session parses with, together with the grammar registry version and the effective +//! selection snapshot (session or database default, compared by identity) it was composed from +struct CachedSessionGrammar { + shared_ptr grammar; + idx_t registry_version; + shared_ptr> selection; +}; + typedef std::function(ClientContext &context, PreparedStatementData &data)> get_result_collector_t; @@ -88,10 +96,16 @@ struct ClientConfig { get_result_collector_t get_result_collector = nullptr; optional current_dialect; - //! The (ordered) list of grammar extensions currently used by the parser - vector active_grammar_extensions; - //! The compiled grammar active for the connection - shared_ptr cached_grammar; + //! The (ordered) list of explicitly activated grammar extensions: nullptr means not set (the + //! database default applies), a non-null empty list is an explicit opt-out. An immutable + //! snapshot replaced on SET/RESET and loaded atomically because parsing can run without the + //! client context lock + shared_ptr> active_grammar_extensions; + //! The grammar composed for the connection; recomposed lazily when unset or stale. The snapshot + //! is immutable and stored/loaded atomically (see active_grammar_extensions); its validity is + //! keyed on the registry version and the selection identity, so a parse that raced a SET cannot + //! install a grammar that passes as composed from the new selection + shared_ptr cached_grammar; //! The grammar of the database this client is CONNECT-ed to; unset when not connected shared_ptr connected_grammar; diff --git a/src/duckdb/src/include/duckdb/main/client_context.hpp b/src/duckdb/src/include/duckdb/main/client_context.hpp index 1b7c97489..b3225e048 100644 --- a/src/duckdb/src/include/duckdb/main/client_context.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context.hpp @@ -22,6 +22,7 @@ #include "duckdb/common/pair.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/winapi.hpp" +#include "duckdb/logging/logging.hpp" #include "duckdb/main/client_config.hpp" #include "duckdb/main/client_context_state.hpp" #include "duckdb/main/client_properties.hpp" @@ -43,6 +44,7 @@ class CatalogSearchPath; class ColumnDataCollection; class DatabaseInstance; class FileOpener; +class Context; class LogicalOperator; class PreparedStatement; class PreparedStatementData; @@ -128,12 +130,8 @@ class ClientContext : public enable_shared_from_this { shared_ptr base_context; //! The number of internal connections between this client and its base client (0 for a base client) idx_t internal_depth = 0; - //! Set of optional states (e.g. Caches) that can be held by the ClientContext - unique_ptr registered_state; - //! The logger to be used by this ClientContext - shared_ptr logger; - //! The client configuration - ClientConfig config; + //! The context of this ClientContext: owns the client configuration, logger, query profiler, file system, ... + shared_ptr context; //! The set of client-specific data unique_ptr client_data; //! Data for the currently running transaction @@ -303,9 +301,20 @@ class ClientContext : public enable_shared_from_this { //! Return the current logger Logger &GetLogger() const; + const LogConfigSnapshot &GetLogConfig() const { + return log_config; + } + + //! The Context (client configuration, logging, metrics, file system) owned by this client context + Context &GetContext() const { + return *context; + } //! Returns the current query string (if any) const string &GetCurrentQuery(); + //! Whether the statement that runs now is the last of the active query. A statement that expands into several + //! runs them as one query in one transaction; for any other query this is always true + DUCKDB_API bool ActiveQueryIsLastStatement() const; connection_t GetConnectionId() const; @@ -418,6 +427,8 @@ class ClientContext : public enable_shared_from_this { void BeginStatementInternal(ClientContextLock &lock, const string &query); //! Refreshes the logger for the statement that begins void RefreshLoggerInternal(); + //! Replaces the logger with one created from the up-to-date log config + void ResetLoggerInternal(const LoggingContext &logging_context); //! Ends the statement of a query that expands into several once it finished, and starts the next one QueryResultState StartNextStatementInternal(ClientContextLock &lock); //! Ends the statement that finished and starts the next one. Returns the result object a collector built for it, @@ -426,8 +437,10 @@ class ClientContext : public enable_shared_from_this { //! Whether this query or, for an internal connection, the base client's query has a deadline bool HasQueryDeadline() const; bool QueryDeadlinePassed() const; - //! Ends the statement of the active query that finished, when another one follows - void EndStatementInternal(ClientContextLock &lock); + //! Ends the statement that finished: releases its executor and plan and notifies every registered state, also + //! when one of them fails. Returns the first failure + ErrorData EndStatementInternal(ClientContextLock &lock, optional_ptr error); + void NotifyStatementBeginInternal(ClientContextLock &lock); ErrorData EndQueryInternal(ClientContextLock &lock, bool success, bool invalidate_transaction, optional_ptr previous_error); //! End the query in the profiler; a failure to emit the profile becomes the error unless there is one already @@ -476,6 +489,9 @@ class ClientContext : public enable_shared_from_this { QueryProgress query_progress; //! The connection corresponding to this client context connection_t connection_id; + //! The log config used to create loggers for this ClientContext and its ThreadContexts. Only refreshed (with the + //! logger) at query begin and end, when no tasks that could read it from other threads are running + LogConfigSnapshot log_config; //! Type of connection (USER or INTERNAL) ConnectionType connection_type = ConnectionType::USER; //! Routing target for SQL execution while CONNECT-ed (CONNECT/DISCONNECT). When is_connected is diff --git a/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp b/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp index 2d66d03e3..350aa44f3 100644 --- a/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp @@ -12,27 +12,27 @@ namespace duckdb { -class ClientContext; +class Context; -//! ClientContext-specific FileOpener implementation. -//! This object is owned by ClientContext and never outlives it. +//! FileOpener implementation backed by a Context. +//! The Context must outlive the opener. class ClientContextFileOpener : public FileOpener { public: - explicit ClientContextFileOpener(ClientContext &context_p) : context(context_p) { + explicit ClientContextFileOpener(Context &context_p) : context(context_p) { } Logger &GetLogger() const override; SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result, FileOpenerInfo &info) override; SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) override; - optional_ptr TryGetClientContext() override { - return &context; + Context &TryGetContext() override { + return context; } optional_ptr TryGetDatabase() override; HTTPUtil &GetHTTPUtil() override; private: - ClientContext &context; + Context &context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/client_context_state.hpp b/src/duckdb/src/include/duckdb/main/client_context_state.hpp index 240dd0a1d..7e74d8883 100644 --- a/src/duckdb/src/include/duckdb/main/client_context_state.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context_state.hpp @@ -18,6 +18,7 @@ namespace duckdb { class ClientContext; +class Context; class ErrorData; class MetaTransaction; class PreparedStatementData; @@ -46,6 +47,16 @@ class ClientContextState { virtual void QueryEnd(ClientContext &context, optional_ptr error) { QueryEnd(context); } + //! A statement of the active query starts, after QueryBegin and before it is planned. A statement that expands + //! into several runs them as one query, with a StatementBegin and StatementEnd for each + virtual void StatementBegin(ClientContext &context) { + } + //! A statement of the active query released its executor and plan, before the next one starts + virtual void StatementEnd(ClientContext &context) { + } + virtual void StatementEnd(ClientContext &context, optional_ptr error) { + StatementEnd(context); + } virtual void TransactionBegin(MetaTransaction &transaction, ClientContext &context) { } virtual void TransactionCommit(MetaTransaction &transaction, ClientContext &context) { @@ -72,9 +83,9 @@ class ClientContextState { } virtual void WriteProfilingInformation(std::ostream &ss) { } - virtual void OnTaskStart(ClientContext &context) { + virtual void OnTaskStart(Context &context) { } - virtual void OnTaskStop(ClientContext &context) { + virtual void OnTaskStop(Context &context) { } public: @@ -93,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()) { @@ -156,7 +167,7 @@ class RegisteredStateManager { return snapshot; } lock_guard l(lock); - snapshot = state_snapshot; + snapshot = state_snapshot.atomic_load(); if (!snapshot && !registered_state.empty()) { snapshot = make_shared_ptr>>(StatesInternal()); state_snapshot.atomic_store(snapshot); diff --git a/src/duckdb/src/include/duckdb/main/client_data.hpp b/src/duckdb/src/include/duckdb/main/client_data.hpp index 405594c57..ce74627eb 100644 --- a/src/duckdb/src/include/duckdb/main/client_data.hpp +++ b/src/duckdb/src/include/duckdb/main/client_data.hpp @@ -22,7 +22,6 @@ class FileSystem; class QueryProfiler; class PreparedStatementData; class RandomEngine; -class BufferManager; struct ClientData { public: @@ -30,9 +29,6 @@ struct ClientData { ~ClientData(); public: - //! The query profiler of this client. - shared_ptr profiler; - //! The set of temporary objects belonging to this client. shared_ptr temporary_objects; //! The set of bound prepared statements belonging to this client. @@ -48,13 +44,6 @@ struct ClientData { //! calls only affect new clients. Empty when there was none. Identifier default_database; - //! The file opener of the client context. - unique_ptr file_opener; - //! The clients' file system wrapper. - unique_ptr client_file_system; - //! The clients' buffer manager wrapper. - unique_ptr client_buffer_manager; - //! The writer used to log queries, if logging is enabled. //! DEPRECATED: Now, queries are written to the generic log. unique_ptr log_query_writer; diff --git a/src/duckdb/src/include/duckdb/main/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 6cc646c88..8e611c76b 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -258,6 +258,10 @@ struct DBConfig { shared_ptr path_manager; //! Database configuration variables as controlled by SET GlobalUserSettings user_settings; + //! The grammar extensions sessions parse with when active_grammar_extensions is not set: an + //! immutable snapshot replaced on SET GLOBAL and loaded atomically because sessions read it at + //! parse time without the config lock (nullptr when unset) + shared_ptr> default_grammar_extensions; public: DUCKDB_API static DBConfig &GetConfig(ClientContext &context); @@ -397,6 +401,10 @@ struct DBConfig { HTTPUtil &GetHTTPUtil() const; //! Replace how external extensions are installed and loaded, before the database runs queries DUCKDB_API void SetExternalExtensionProvider(const shared_ptr &new_provider); + //! Returns a copy of the forced variant shredding type (INVALID if unset), safe to call while it is being modified + DUCKDB_API LogicalType GetForceVariantShredding() const; + //! Returns a copy of the allowed_configs set, safe to call while it is being modified + DUCKDB_API identifier_set_t GetAllowedConfigs() const; DUCKDB_API ExternalExtensionProvider &GetExternalExtensionProvider() const; DUCKDB_API HTTPTransportManager &GetHTTPTransportManager(); DUCKDB_API const HTTPTransportManager &GetHTTPTransportManager() const; diff --git a/src/duckdb/src/include/duckdb/main/context.hpp b/src/duckdb/src/include/duckdb/main/context.hpp new file mode 100644 index 000000000..2c4db4f2c --- /dev/null +++ b/src/duckdb/src/include/duckdb/main/context.hpp @@ -0,0 +1,119 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/main/context.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/helper.hpp" +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/shared_ptr.hpp" +#include "duckdb/common/unique_ptr.hpp" +#include "duckdb/main/setting_info.hpp" + +namespace duckdb { + +struct ClientConfig; +class BufferManager; +class ClientContext; +struct CatalogTransaction; +class DatabaseInstance; +class FileOpener; +class FileSystem; +class Logger; +class MetricsManager; +class QueryProfiler; +class RegisteredStateManager; +class TaskScheduler; +class Value; + +//! Context owns the services that operations need to do their work: reading settings, logging, recording +//! metrics and accessing the file system. +//! A ClientContext owns one (see ClientContext::GetContext) that holds all of its connection-specific services. +//! A DatabaseInstance can create one (see DatabaseInstance::Services) that only provides database-wide services. +class Context { +public: + //! Creates database-wide services + //! The database must outlive the services + DUCKDB_API explicit Context(DatabaseInstance &db); + DUCKDB_API ~Context(); + + //! Turns these into the services of the given client context: creates the client config, the query profiler, + //! the file opener and the client file system. The connection logger is set by the context (see SetLogger). + //! The context must own these services - it is kept as a back reference. + void InitializeClient(ClientContext &context); + +public: + //! The database instance the services belong to + DUCKDB_API DatabaseInstance &GetDatabase() const; + //! The client context owning the services (if any) - only present for the services of a ClientContext + DUCKDB_API optional_ptr TryGetClientContext() const; + //! Null-safe variants for optional services + DUCKDB_API static optional_ptr TryGetClientContext(optional_ptr services); + DUCKDB_API static optional_ptr TryGetQueryProfiler(optional_ptr services); + //! 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) + DUCKDB_API bool IsInterrupted() const; + //! A catalog transaction on the system catalog: the client's own for client services, otherwise a system one + DUCKDB_API CatalogTransaction GetSystemCatalogTransaction(); + + //! The client config - only present for the services of a ClientContext + DUCKDB_API optional_ptr TryGetClientConfig() const; + DUCKDB_API ClientConfig &GetClientConfig() const; + + //! Equivalent to CURRENT_SETTING(key) SQL function. + DUCKDB_API SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) const; + //! Typed variant, leaves result untouched if not found + template + SettingLookupResult TryGetCurrentSetting(const Identifier &key, TYPE &result) const { + Value output; + auto lookup_result = TryGetCurrentSetting(key, output); + if (lookup_result) { + result = output.GetValue(); + } + return lookup_result; + } + //! Returns the value of the current setting set by the user - if the user has set it. + DUCKDB_API SettingLookupResult TryGetCurrentUserSetting(idx_t setting_index, Value &result) const; + + //! The logger: connection-scoped for the services of a ClientContext, otherwise the global logger + DUCKDB_API Logger &GetLogger() const; + //! Re-creates the connection logger (e.g. after the logging configuration changed) + DUCKDB_API void SetLogger(shared_ptr new_logger); + DUCKDB_API const shared_ptr &GetLoggerPtr() const; + //! The file system: client-specific for the services of a ClientContext, otherwise the database file system + DUCKDB_API FileSystem &GetFileSystem() const; + //! The file opener of the client - only present for the services of a ClientContext + DUCKDB_API optional_ptr TryGetFileOpener() const; + //! The buffer manager wrapper: forwards to the database buffer manager, tracking the allocations of the services + DUCKDB_API BufferManager &GetBufferManager() const; + //! The database-wide task scheduler + DUCKDB_API TaskScheduler &GetTaskScheduler() const; + //! The database-wide metrics manager + DUCKDB_API MetricsManager &GetMetricsManager() const; + //! The states (e.g. caches) registered by extensions - only present for the services of a ClientContext + DUCKDB_API RegisteredStateManager &GetRegisteredState() const; + //! The query profiler of the client - only present for the services of a ClientContext + DUCKDB_API optional_ptr TryGetQueryProfiler() const; + DUCKDB_API QueryProfiler &GetQueryProfiler() const; + DUCKDB_API const shared_ptr &GetQueryProfilerPtr() const; + +private: + DatabaseInstance &db; + //! Back reference to the owning client context + optional_ptr context; + unique_ptr config; + shared_ptr logger; + shared_ptr profiler; + unique_ptr registered_state; + unique_ptr file_opener; + unique_ptr client_file_system; + //! The buffer manager wrapper of the services + unique_ptr buffer_manager; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/database.hpp b/src/duckdb/src/include/duckdb/main/database.hpp index 041f3119d..e40a13320 100644 --- a/src/duckdb/src/include/duckdb/main/database.hpp +++ b/src/duckdb/src/include/duckdb/main/database.hpp @@ -40,6 +40,7 @@ struct DatabaseCacheEntry; class LogManager; class OSUtil; class MetricsManager; +class Context; class ExternalFileCache; class ResultSetManager; struct ParserCache; @@ -90,6 +91,9 @@ 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(); + DUCKDB_API shared_ptr GetEncryptionUtil(bool read_only = false); shared_ptr GetMbedTLSUtil(bool force_mbedtls) const; diff --git a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp index e6d5b248c..3d8792f01 100644 --- a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp @@ -12,6 +12,7 @@ #include "duckdb/common/local_file_system.hpp" #include "duckdb/common/opener_file_system.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/logging/log_manager.hpp" #include "duckdb/main/http/http_util.hpp" @@ -21,7 +22,7 @@ class DatabaseInstance; class DatabaseFileOpener : public FileOpener { public: - explicit DatabaseFileOpener(DatabaseInstance &db_p) : db(db_p) { + explicit DatabaseFileOpener(DatabaseInstance &db_p) : db(db_p), context(db_p.Services()) { } Logger &GetLogger() const override { @@ -36,8 +37,8 @@ class DatabaseFileOpener : public FileOpener { return db.TryGetCurrentSetting(key, result); } - optional_ptr TryGetClientContext() override { - return nullptr; + Context &TryGetContext() override { + return *context; } optional_ptr TryGetDatabase() override { @@ -49,6 +50,7 @@ class DatabaseFileOpener : public FileOpener { private: DatabaseInstance &db; + shared_ptr context; }; class DatabaseFileSystem : public OpenerFileSystem { diff --git a/src/duckdb/src/include/duckdb/main/extension_callback_manager.hpp b/src/duckdb/src/include/duckdb/main/extension_callback_manager.hpp index fca546d2e..aef59b24b 100644 --- a/src/duckdb/src/include/duckdb/main/extension_callback_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_callback_manager.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/atomic.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/shared_ptr.hpp" @@ -63,25 +64,37 @@ class ExtensionCallbackManager { optional_ptr FindStorageExtension(const string &name) const; optional_ptr FindGrammarExtension(const string &name) const; case_insensitive_map_t> GrammarExtensions() const; + //! Monotonic version bumped on every grammar extension registration, so sessions can detect + //! that their composed grammar is stale (e.g. after a LOAD mid-session) + idx_t GrammarRegistryVersion() const { + return grammar_registry_version.load(); + } optional_ptr FindProfilerExtension(const string &name) const; bool HasParserExtensions() const; optional_ptr GetDialectExtension(const string &name) const; private: - mutex registry_lock; - shared_ptr callback_registry; + shared_ptr CopyRegistry() const; + void PublishRegistry(shared_ptr new_registry); + +private: + mutable mutex registry_lock; + //! The current registry, read without locking or reference counting + atomic callback_registry; + //! Every published registry, kept alive so that readers of an older one stay valid + vector> registry_versions; vector extension_schemas; + atomic grammar_registry_version {0}; }; template class ExtensionCallbackIteratorHelper { public: - ExtensionCallbackIteratorHelper(const vector &vec, shared_ptr callback_registry); + explicit ExtensionCallbackIteratorHelper(const vector &vec); ~ExtensionCallbackIteratorHelper(); private: const vector &vec; - shared_ptr callback_registry; public: typename vector::const_iterator begin() { // NOLINT: match stl API diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index 6ae3713ff..a8023dd38 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -385,6 +385,7 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"glue_replace_columns", "glue", CatalogType::TABLE_FUNCTION_ENTRY}, {"glue_set_partition_location", "glue", CatalogType::TABLE_FUNCTION_ENTRY}, {"glue_set_table_location", "glue", CatalogType::TABLE_FUNCTION_ENTRY}, + {"gpu_execution", "sirius", CatalogType::TABLE_FUNCTION_ENTRY}, {"grade_up", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"greatest", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"greatest_common_divisor", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -764,6 +765,7 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"read_ndjson_objects", "json", CatalogType::TABLE_FUNCTION_ENTRY}, {"read_parquet", "parquet", CatalogType::TABLE_FUNCTION_ENTRY}, {"read_postgres_binary", "postgres_scanner", CatalogType::TABLE_FUNCTION_ENTRY}, + {"read_single_avro_file", "avro", CatalogType::TABLE_FUNCTION_ENTRY}, {"read_single_json_file", "json", CatalogType::TABLE_FUNCTION_ENTRY}, {"read_single_parquet_file", "parquet", CatalogType::TABLE_FUNCTION_ENTRY}, {"read_xlsx", "excel", CatalogType::TABLE_FUNCTION_ENTRY}, @@ -806,6 +808,7 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"signbit", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"sin", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"sinh", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"sirius_status", "sirius", CatalogType::TABLE_FUNCTION_ENTRY}, {"skewness", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, {"sleep_ms", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"sql_auto_complete", "autocomplete", CatalogType::TABLE_FUNCTION_ENTRY}, @@ -1079,12 +1082,14 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',INTERVAL]>STRUCT"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME]>STRUCT"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP]>STRUCT"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP_NS]>STRUCT"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMETZ]>STRUCT"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME_NS]>STRUCT"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>DOUBLE"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>DOUBLE"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME]>DOUBLE"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>DOUBLE"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>DOUBLE"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>DOUBLE"}, {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME_NS]>DOUBLE"}, {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ]>STRUCT"}, @@ -1109,12 +1114,14 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',INTERVAL]>STRUCT"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME]>STRUCT"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP]>STRUCT"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP_NS]>STRUCT"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMETZ]>STRUCT"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME_NS]>STRUCT"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>DOUBLE"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>DOUBLE"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME]>DOUBLE"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>DOUBLE"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>DOUBLE"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>DOUBLE"}, {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME_NS]>DOUBLE"}, {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ]>STRUCT"}, @@ -1163,6 +1170,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>DOUBLE"}, {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>DOUBLE"}, {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DOUBLE"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>DOUBLE"}, {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>DOUBLE"}, {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>DOUBLE"}, {"epoch", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DOUBLE"}, @@ -1182,6 +1190,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1208,6 +1217,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"microsecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1221,6 +1231,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"millisecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1229,6 +1240,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1256,6 +1268,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"second", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1273,11 +1286,16 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ"}, {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,TIMESTAMPTZ]>TIMESTAMPTZ"}, {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,VARCHAR]>TIMESTAMPTZ"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS]>TIMESTAMPTZ"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,INTERVAL]>TIMESTAMPTZ"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,TIMESTAMPTZ]>TIMESTAMPTZ"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,VARCHAR]>TIMESTAMPTZ"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMETZ]>TIMETZ"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1291,6 +1309,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"timezone_hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1299,6 +1318,7 @@ static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, {"timezone_minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, @@ -1379,6 +1399,7 @@ static constexpr ExtensionEntry EXTENSION_SETTINGS[] = { {"glue_get_partitions_segments", "glue"}, {"glue_metadata_cache_scope", "glue"}, {"glue_network_calls_via_duckdb", "glue"}, + {"gpu_execution", "sirius"}, {"hf_max_per_page", "httpfs"}, {"hive_partition_listing_threshold", "glue"}, {"hnsw_ef_search", "vss"}, @@ -1419,6 +1440,7 @@ static constexpr ExtensionEntry EXTENSION_SETTINGS[] = { {"mysql_session_time_zone", "mysql_scanner"}, {"mysql_time_as_time", "mysql_scanner"}, {"mysql_tinyint1_as_boolean", "mysql_scanner"}, + {"parquet_can_have_nan", "parquet"}, {"parquet_metadata_cache", "parquet"}, {"parquet_prefetch_column_gap", "parquet"}, {"parquet_use_page_index", "parquet"}, @@ -1487,6 +1509,7 @@ static constexpr ExtensionEntry EXTENSION_SETTINGS[] = { {"s3_url_compatibility_mode", "httpfs"}, {"s3_url_scheme_aliases", "httpfs"}, {"s3_url_style", "httpfs"}, + {"s3_use_global_endpoint", "httpfs"}, {"s3_use_ssl", "httpfs"}, {"s3_version_id_pinning", "httpfs"}, {"sqlite_all_varchar", "sqlite_scanner"}, @@ -1516,6 +1539,11 @@ static constexpr ExtensionEntry EXTENSION_SECRET_TYPES[] = { {"uc", "unity_catalog"}, {"unity_catalog", "unity_catalog"}, }; // END_OF_EXTENSION_SECRET_TYPES +// Resource types registered by extensions: CREATE/REGISTER EXTERNAL RESOURCE '' autoloads the extension +static constexpr ExtensionEntry EXTENSION_EXTERNAL_RESOURCE_TYPES[] = { + {"aws:cloudformation:quack-on-ec2", "aws"}, +}; // END_OF_EXTENSION_EXTERNAL_RESOURCE_TYPES + // Note: these are currently hardcoded in scripts/generate_extensions_function.py // TODO: automate by passing though to script via duckdb static constexpr ExtensionEntry EXTENSION_COPY_FUNCTIONS[] = { diff --git a/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp b/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp index 8121e3f1d..43a6c6954 100644 --- a/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp +++ b/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp @@ -59,6 +59,11 @@ class ExternalResourceTypeRegistry { vector List() const; //! The registered type with the given name, or nullptr if none. unique_ptr Lookup(const string &name) const; + //! Lookup that, for a type not registered yet, first autoloads the extension known to provide it (see + //! EXTENSION_EXTERNAL_RESOURCE_TYPES in extension_entries.hpp) + static unique_ptr LookupOrAutoload(DatabaseInstance &db, const string &name); + //! The extension known to provide the type, or empty if none + static string ProvidingExtension(const string &name); private: mutable mutex lock; diff --git a/src/duckdb/src/include/duckdb/main/query_profiler.hpp b/src/duckdb/src/include/duckdb/main/query_profiler.hpp index c414e8d8d..d553ee1d9 100644 --- a/src/duckdb/src/include/duckdb/main/query_profiler.hpp +++ b/src/duckdb/src/include/duckdb/main/query_profiler.hpp @@ -33,6 +33,7 @@ namespace duckdb { class BaseTreeRenderer; class ClientContext; +class Context; class ExpressionExecutor; class ProfilingNode; class PhysicalOperator; @@ -96,6 +97,7 @@ class QueryProfiler { DUCKDB_API string GetSaveLocation() const; DUCKDB_API static QueryProfiler &Get(ClientContext &context); + DUCKDB_API static QueryProfiler &Get(Context &context); DUCKDB_API void Start(const string &query); DUCKDB_API void Reset(); diff --git a/src/duckdb/src/include/duckdb/main/secret/secret.hpp b/src/duckdb/src/include/duckdb/main/secret/secret.hpp index 7299301da..e9fc28dc7 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret.hpp @@ -17,6 +17,7 @@ namespace duckdb { class BaseSecret; +class Context; struct SecretEntry; struct FileOpenerInfo; struct CreateSecretInfo; @@ -221,6 +222,9 @@ class KeyValueSecret : public BaseSecret { Value redact_set_value; deserializer.ReadProperty(202, "redact_keys", redact_set_value); + if (redact_set_value.IsNull() || redact_set_value.type().id() != LogicalTypeId::LIST) { + throw SerializationException("Secret redact_keys must be a non-NULL list"); + } for (const auto &entry : ListValue::GetChildren(redact_set_value)) { result->redact_keys.insert(Identifier(entry.ToString())); } @@ -346,7 +350,7 @@ class KeyValueSecretReader { //! Secrets/settings will be fetched either through a context (local + global settings) or a databaseinstance //! (global only) optional_ptr db; - optional_ptr context; + optional_ptr context; string path; }; 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 09b92dfd9..d32be4236 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp @@ -222,7 +222,8 @@ class SecretManager { //! The DefaultGenerator for persistent secrets. This is used to store lazy loaded secrets in the catalog class DefaultSecretGenerator : public DefaultGenerator { public: - DefaultSecretGenerator(Catalog &catalog, SecretManager &secret_manager, identifier_set_t &persistent_secrets); + DefaultSecretGenerator(Catalog &catalog, SecretManager &secret_manager, identifier_set_t &persistent_secrets, + shared_ptr files); public: unique_ptr CreateDefaultEntry(CatalogTransaction transaction, const Identifier &entry_name) override; @@ -238,6 +239,7 @@ class DefaultSecretGenerator : public DefaultGenerator { SecretManager &secret_manager; mutex lock; identifier_set_t persistent_secrets; + shared_ptr files; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp b/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp index 9671a5147..6dfd69585 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp @@ -24,6 +24,7 @@ class Catalog; class CatalogSet; struct CatalogTransaction; class DatabaseInstance; +class FileSystem; struct SecretMatch; struct SecretEntry; class SecretManager; @@ -155,6 +156,8 @@ class CatalogSetSecretStorage : public SecretStorage { unique_ptr secrets; //! DB instance for accessing the system catalog transaction DatabaseInstance &db; + //! Serializes stores and drops, WriteSecret and RemoveSecret included, so a secret's file and entry change together + mutex store_lock; }; class TemporarySecretStorage : public CatalogSetSecretStorage { @@ -168,11 +171,37 @@ class TemporarySecretStorage : public CatalogSetSecretStorage { protected: }; +//! The file of each persistent secret. The file name alone does not identify the secret: names are escaped in file +//! names, and files written before that are named after the plain secret name, so one file name can belong to two +//! different secrets (the escaped `a/b` and the plain `a%2Fb`). +class PersistentSecretFiles { +public: + //! Registers the file that holds the secret + void Set(const Identifier &secret_name, const string &path); + //! Unregisters the secret + void Remove(const Identifier &secret_name); + //! The file that holds the secret, or an empty string if the secret has no file + string Get(const Identifier &secret_name); + //! Whether the file at the path holds a secret other than the given one + bool TryGetOtherSecretAt(const string &path, const Identifier &secret_name, string &other_secret_name); + +private: + mutex lock; + identifier_map_t paths; +}; + class LocalFileSecretStorage : public CatalogSetSecretStorage { public: LocalFileSecretStorage(SecretManager &manager, DatabaseInstance &db, const string &name_p, const string &secret_path); +public: + //! The file name of a persistent secret: path separators, ':', NUL, '%' and a leading '.' in the name are + //! percent-encoded + static string SecretFileName(const string &secret_name); + //! The secret name for a persistent secret file name (reverses SecretFileName) + static string SecretNameFromFileName(const string &file_name); + protected: //! Implements the writes to disk void WriteSecret(const BaseSecret &secret, OnCreateConflict on_conflict) override; @@ -181,6 +210,8 @@ class LocalFileSecretStorage : public CatalogSetSecretStorage { //! Set of persistent secrets that are lazily loaded identifier_set_t persistent_secrets; + //! The files of the persistent secrets, shared with the generator that loads them + shared_ptr files; //! Path that is searched for secrets; string secret_path; }; diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index 98f4df43b..4529cfb32 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -13,6 +13,8 @@ namespace duckdb { +class Context; + struct Settings { template static typename std::enable_if::value, typename OP::RETURN_TYPE>::type @@ -88,6 +90,7 @@ struct Settings { static bool TryGetSettingInternal(const DatabaseInstance &db, idx_t setting_index, Value &result); static bool TryGetSettingInternal(const DBConfig &config, idx_t setting_index, Value &result); static bool TryGetSettingInternal(const ClientContext &context, idx_t setting_index, Value &result); + static bool TryGetSettingInternal(const Context &context, idx_t setting_index, Value &result); static void SetSettingInternal(DatabaseInstance &db, idx_t setting_index, SetScope scope, Value target_value); static void SetSettingInternal(DBConfig &config, idx_t setting_index, SetScope scope, Value target_value); @@ -1051,6 +1054,19 @@ struct DefaultCollationSetting { static void OnSet(SettingCallbackInfo &info, Value &input); }; +struct DefaultGrammarExtensionsSetting { + using RETURN_TYPE = vector; + static constexpr const char *Name = "default_grammar_extensions"; + static constexpr const char *Description = + "The grammar extensions sessions parse with when active_grammar_extensions is not set."; + 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); +}; + struct DefaultNullOrderSetting { using RETURN_TYPE = DefaultOrderByNullType; static constexpr const char *Name = "default_null_order"; @@ -2373,6 +2389,20 @@ struct RegexMatchOperatorSemanticsSetting { static void OnSet(SettingCallbackInfo &info, Value &input); }; +struct ScalarAggregateMergeThresholdSetting { + using RETURN_TYPE = idx_t; + static constexpr const char *Name = "scalar_aggregate_merge_threshold"; + static constexpr const char *Description = + "The number of rows a table needs for sibling scalar aggregates over it to be computed in one pass. 0 computes " + "them in one pass only over table functions such as read_parquet."; + static constexpr const char *InputType = "UBIGINT"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "0"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct ScalarSubqueryErrorOnMultipleRowsSetting { using RETURN_TYPE = bool; static constexpr const char *Name = "scalar_subquery_error_on_multiple_rows"; diff --git a/src/duckdb/src/include/duckdb/main/user_settings.hpp b/src/duckdb/src/include/duckdb/main/user_settings.hpp index b7f1cb85b..73ac3ae24 100644 --- a/src/duckdb/src/include/duckdb/main/user_settings.hpp +++ b/src/duckdb/src/include/duckdb/main/user_settings.hpp @@ -41,11 +41,13 @@ struct GlobalUserSettings; struct CachedGlobalSettings { CachedGlobalSettings(); - CachedGlobalSettings(const GlobalUserSettings &global_user_settings, idx_t version, UserSettingsMap settings); + CachedGlobalSettings(const GlobalUserSettings &global_user_settings, idx_t version, UserSettingsMap settings, + const identifier_map_t &extension_parameters); optional_ptr global_user_settings; idx_t version; UserSettingsMap settings; + identifier_map_t extension_setting_indexes; hugeint_t uuid; }; #endif @@ -65,6 +67,7 @@ struct GlobalUserSettings { idx_t AddExtensionOption(const Identifier &name, ExtensionOption extension_option); identifier_map_t GetExtensionSettings() const; bool TryGetExtensionOption(const Identifier &name, ExtensionOption &result) const; + optional_idx TryGetExtensionSettingIndex(const Identifier &name) const; hugeint_t GetUUID() const; #ifndef __MINGW32__ diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp index ebe038154..2fd8a94fe 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp @@ -12,6 +12,7 @@ #include "duckdb/common/unordered_map.hpp" #include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/expression.hpp" +#include "duckdb/planner/joinside.hpp" #include "duckdb/storage/data_table.hpp" #include @@ -56,6 +57,15 @@ class FilterCombiner { bool HasFilters(); void GenerateEquivalentFilters(const Expression &filter, const std::function filter)> &callback); + //! The expression that a comparison, BETWEEN or IN filter compares with constants, or nullptr for other filters. + //! Such a filter is false for NULL and has the same result for all values equal to that expression. + static optional_ptr GetComparedExpression(const Expression &filter); + //! Generates the comparisons with constants that filters on one side of a join imply for the target side through + //! the equality conditions, e.g. [i = a and i = 500] => [a = 500]. Unlike GenerateEquivalentFilters, it only + //! replaces a compared expression as a whole, so values that are equal but not identical stay apart. + static void GenerateJoinFilters(const vector &conditions, + const vector> &filters, JoinSide target_side, + const std::function filter)> &callback); TableFilterSet GenerateTableScanFilters(const vector &column_ids, vector &pushdown_results); diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp index b6cb1e704..7547fd138 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp @@ -48,10 +48,14 @@ class FilterPullup { unique_ptr PullupJoin(unique_ptr op); //! Pullup filter in a left join unique_ptr PullupFromLeft(unique_ptr op); + //! Pullup filter in a semi join, with the filters on the left that the filters on the right imply + unique_ptr PullupSemiJoin(unique_ptr op); //! Pullup filter in an inner join unique_ptr PullupInnerJoin(unique_ptr op); //! Pullup filter through a distinct unique_ptr PullupDistinct(unique_ptr op); + //! Pullup the filters on the partitions of a window + unique_ptr PullupWindow(unique_ptr op); //! Pullup filter in LogicalIntersect or LogicalExcept op unique_ptr PullupSetOperation(unique_ptr op); //! Pullup filter in both sides of a join diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp index 870931e3a..75f0c856a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp @@ -15,6 +15,7 @@ namespace duckdb { class LogicalGet; +class LogicalWindow; class Optimizer; class FilterPushdown { @@ -35,6 +36,12 @@ class FilterPushdown { //! guaranteed not to remove any rows. A barred expression must never be evaluated on rows that an operator below //! it filters out. static bool BarrierCanPassThrough(LogicalOperatorType type); + //! Whether the filter compares something that every window expression partitions by with constants, so that it + //! keeps or removes whole partitions + static bool ComparesWindowPartitions(const LogicalWindow &window, const Expression &filter); + //! Whether every window expression is a ranking function without arguments, e.g. row_number(), which neither fails + //! nor has side effects, so a filter may change the partitions it runs for + static bool OnlyRanksWithoutArguments(const LogicalWindow &window); struct Filter { unordered_set bindings; diff --git a/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp b/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp index 66a0dfaa7..634306e25 100644 --- a/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp @@ -31,6 +31,10 @@ class InClauseRewriter : public LogicalOperatorVisitor { static constexpr idx_t IN_CLAUSE_REWRITE_THRESHOLD = 6; static bool HasRewritableInClause(const Expression &expr); unique_ptr Rewrite(unique_ptr op); + //! skips error-capture interiors (TRY, has_error) and guarded conjunction/CASE/COALESCE children: + //! the rewrite would move the probe's evaluation (and its errors) below the operator, outside the + //! capture or the guard + void VisitExpression(unique_ptr *expression) override; unique_ptr VisitReplace(BoundOperatorExpression &expr, unique_ptr *expr_ptr) override; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp index 37b6aee15..7604ecb97 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp @@ -10,11 +10,12 @@ #include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/execution/operator/join/join_filter_pushdown.hpp" namespace duckdb { class Optimizer; -struct JoinFilterPushdownColumn; -struct PushdownFilterTarget; +class LogicalCTERef; enum class EqualityPropagation { DISABLED, ENABLED }; @@ -25,19 +26,29 @@ class JoinFilterPushdownOptimizer : public LogicalOperatorVisitor { explicit JoinFilterPushdownOptimizer(Optimizer &optimizer); public: + void Optimize(LogicalOperator &op); void VisitOperator(LogicalOperator &op) override; //! Find scan targets independently for each column, allowing both NULL-retaining and NULL-rejecting filters. //! Equality propagation can return multiple equivalent columns per scan; single-column callers leave it disabled. + //! Only the join filter pushdown continues into secure views (cross_secure_views): the other callers act on what + //! they find, e.g. a target's estimated cardinality, which must not depend on a view's contents static void GetPushdownFilterTargets(LogicalOperator &op, vector columns, vector &targets, - EqualityPropagation equality_propagation = EqualityPropagation::DISABLED); + EqualityPropagation equality_propagation = EqualityPropagation::DISABLED, + bool cross_secure_views = false); static bool IsFiltering(const unique_ptr &op); private: + void CollectCTEFilters(LogicalOperator &op); + void GenerateCTEFilters(LogicalMaterializedCTE &cte); void GenerateJoinFilters(LogicalComparisonJoin &join); + static bool CanGenerateJoinFilters(const LogicalComparisonJoin &join); + static void GetCTEFilterTargets(LogicalOperator &op, vector columns, + reference_map_t> &targets); private: Optimizer &optimizer; + reference_map_t> cte_filters; }; } // 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 6b37a858e..bd32a07fb 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp @@ -8,6 +8,8 @@ #pragma once #include "duckdb/common/reference_map.hpp" +#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/relation_statistics/relation_statistics_helper.hpp" @@ -16,13 +18,10 @@ namespace duckdb { class FilterInfo; class JoinPredicateModel; struct CardinalityEstimatorState; -struct CardinalityHelper; struct CompositeJoinPairStats; -struct DenomInfo; -struct DenominatorState; +struct SelectivityState; struct FilterInfoWithTotalDomains; -struct LeftJoinDenomInfo; -struct Subgraph2Denominator; +struct SelectivitySubgraph; class CardinalityEstimator { public: @@ -30,70 +29,49 @@ class CardinalityEstimator { ~CardinalityEstimator(); public: - void RemoveEmptyTotalDomains(); - void UpdateTotalDomains(optional_ptr set, RelationStats &stats); - void InitEquivalentRelations(); - - void InitCardinalityEstimatorProps(optional_ptr set, RelationStats &stats); - void RestrictFilterDomains(const vector &relation_stats); - - //! cost model needs estimated cardinalities to the fraction since the formula captures - //! distinct count selectivities and multiplicities. Hence the template - template - T EstimateCardinalityWithSet(JoinRelationSet &new_set); - - //! used for debugging. - void AddRelationNamesToRelationStats(vector &stats); - void PrintRelationStats(); + //! Initialize immutable logical statistics before estimating any relation set. + void Initialize(const vector &relations, + const vector> &operators = {}); + //! All equivalent plans in a memo group share this estimate. + CardinalityValue EstimateCardinality(JoinRelationSet &set); private: - double GetNumerator(JoinRelationSet &set); - double GetSubgraphCardinality(const Subgraph2Denominator &subgraph); - const CardinalityHelper &GetCardinalityBeforeFilters(JoinRelationSet &set); - optional EstimateTopLevelSemiAnti(JoinRelationSet &set); - DenomInfo GetDenominator(JoinRelationSet &set); - void ProcessDenominatorEdge(FilterInfoWithTotalDomains &edge, JoinRelationSet &requested_set, - DenominatorState &state); - void CreateDenominatorSubgraph(FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, - JoinRelationSet &edge_right_set, DenominatorState &state); - void ExtendDenominatorSubgraph(idx_t subgraph_index, FilterInfoWithTotalDomains &edge, + void InitEquivalentRelations(); + void UpdateTotalDomains(RelationIndex relation, const RelationStats &stats); + void RestrictFilterDomains(const vector &relation_stats); + bool IsFilterApplicable(const FilterInfo &filter, JoinRelationSet &set) const; + CardinalityValue GetNumerator(JoinRelationSet &set); + CardinalityValue GetInnerSelectivity(JoinRelationSet &set); + CardinalityValue GetJoinSelectivity(JoinRelationSet &set, JoinRelationSet &left, JoinRelationSet &right); + CardinalityValue GetSelectivity(JoinRelationSet &set); + void ProcessSelectivityEdge(FilterInfoWithTotalDomains &edge, JoinRelationSet &requested_set, + SelectivityState &state); + void CreateSelectivitySubgraph(FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, + JoinRelationSet &edge_right_set, SelectivityState &state); + void ExtendSelectivitySubgraph(idx_t subgraph_index, FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, JoinRelationSet &edge_right_set, - bool can_increment_existing_join, DenominatorState &state); - void MergeDenominatorSubgraphs(const vector &subgraph_connections, FilterInfoWithTotalDomains &edge, - DenominatorState &state); - void MergeDisconnectedDenominatorSubgraphs(DenominatorState &state); - void AddCrossProductRelations(JoinRelationSet &set, DenominatorState &state); - DenomInfo CreateDenominatorResult(JoinRelationSet &set, DenominatorState &state); - //! Applied outside the cardinality cache so stored values stay pre-OR. - double ApplyOrFilterSelectivities(JoinRelationSet &new_set, double cardinality) const; - + bool can_increment_existing_join, SelectivityState &state); + void MergeSelectivitySubgraphs(const vector &subgraph_connections, FilterInfoWithTotalDomains &edge, + SelectivityState &state); + void MergeDisconnectedSelectivitySubgraphs(SelectivityState &state); bool SingleColumnFilter(const FilterInfo &filter_info); - //! Denom calculation - double CalculateUpdatedDenom(Subgraph2Denominator left, Subgraph2Denominator right, - FilterInfoWithTotalDomains &filter); - double CalculateInnerJoinDenom(double base_denom, FilterInfoWithTotalDomains &filter); - LeftJoinDenomInfo CalculateLeftJoinDenomInfo(Subgraph2Denominator &left, Subgraph2Denominator &right, - FilterInfoWithTotalDomains &filter); - double CalculateLeftJoinDenom(Subgraph2Denominator &left, Subgraph2Denominator &right, - FilterInfoWithTotalDomains &filter); - double CalculateSemiAntiJoinDenom(Subgraph2Denominator &left, Subgraph2Denominator &right, - FilterInfoWithTotalDomains &filter); - bool ApplyJoinIncrement(double &target_denom, FilterInfoWithTotalDomains &edge, + //! Selectivity calculation + CardinalityValue CalculateInnerJoinSelectivity(CardinalityValue base_selectivity, + FilterInfoWithTotalDomains &filter); + CardinalityValue GetLeftJoinSelectivity(const JoinOrderOperator &join_operator); + bool ApplyJoinIncrement(CardinalityValue &target_selectivity, FilterInfoWithTotalDomains &edge, reference_map_t &inner_join_pair_stats, reference_set_t &capped_join_pairs, JoinRelationSet &scope, optional_ptr join_pair = nullptr); - bool ApplyJoinPairCap(double &target_denom, JoinRelationSet &join_pair, + bool ApplyJoinPairCap(CardinalityValue &target_selectivity, JoinRelationSet &join_pair, reference_map_t &inner_join_pair_stats, reference_set_t &capped_join_pairs); - bool ApplyCompositeJoinPairCaps(double &target_denom, JoinRelationSet &scope, + bool ApplyCompositeJoinPairCaps(CardinalityValue &target_selectivity, JoinRelationSet &scope, reference_map_t &inner_join_pair_stats, reference_set_t &capped_join_pairs); double GetJoinPairCap(JoinRelationSet &join_pair); - JoinRelationSet &UpdateNumeratorRelations(Subgraph2Denominator left, Subgraph2Denominator right, - FilterInfoWithTotalDomains &filter); - void AddRelationStats(const FilterInfo &filter_info); bool EmptyFilter(const FilterInfo &filter_info); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp new file mode 100644 index 000000000..917af4f00 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp @@ -0,0 +1,122 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/cardinality_value.hpp +// +//===----------------------------------------------------------------------===// +#pragma once + +#include "duckdb/common/common.hpp" + +#include +#include + +namespace duckdb { + +//! Retain scaled numerator and denominator products until the final division. +//! Inputs are finite nonnegative row/domain counts or selectivity factors; only accumulated products need extra range. +class CardinalityValue { +public: + explicit CardinalityValue(double value = 1) : CardinalityValue(Product(value), Product(1)) { + } + + bool IsZero() const { + return numerator.significand == 0; + } + + double GetDouble() const { + if (IsZero()) { + return 0; + } + Product quotient(numerator.significand / denominator); + quotient.exponent += numerator.exponent; + if (quotient.exponent > std::numeric_limits::max_exponent) { + // A final overflow remains infinity. Saturating here would also tie costs and can overflow when adding + // them. + return std::numeric_limits::infinity(); + } + if (quotient.exponent < std::numeric_limits::min_exponent - std::numeric_limits::digits) { + return 0; + } + return std::ldexp(quotient.significand, static_cast(quotient.exponent)); + } + + idx_t GetIndex() const { + auto value = GetDouble(); + // Keep a positive estimate from becoming an empty input in subsequent optimization. + if (value < 1) { + return IsZero() ? 0 : 1; + } + auto maximum = std::numeric_limits::max(); + return value >= static_cast(maximum) ? maximum : static_cast(value); + } + + CardinalityValue operator*(const CardinalityValue &other) const { + return CardinalityValue(numerator * other.numerator, Product(denominator * other.denominator)); + } + + CardinalityValue operator/(const CardinalityValue &other) const { + D_ASSERT(!other.IsZero()); + return CardinalityValue(numerator * other.denominator, other.numerator * denominator); + } + + CardinalityValue &operator*=(const CardinalityValue &other) { + *this = *this * other; + return *this; + } + + bool operator>(const CardinalityValue &other) const { + return numerator * other.denominator > other.numerator * denominator; + } + + bool operator<(const CardinalityValue &other) const { + return other > *this; + } + +private: + struct Product { + explicit Product(double value) { + D_ASSERT(std::isfinite(value) && value >= 0); + int value_exponent; + significand = std::frexp(value, &value_exponent); + exponent = value_exponent; + } + + Product operator*(const Product &other) const { + auto result = *this * other.significand; + if (result.significand != 0) { + result.exponent += other.exponent; + } + return result; + } + + Product operator*(double other) const { + Product result(significand * other); + if (result.significand != 0) { + result.exponent += exponent; + } + return result; + } + + bool operator>(const Product &other) const { + if (significand == 0 || other.significand == 0) { + return significand > other.significand; + } + return exponent == other.exponent ? significand > other.significand : exponent > other.exponent; + } + + double significand; + int64_t exponent; + }; + + CardinalityValue(Product numerator, Product denominator) + : numerator(numerator), denominator(denominator.significand) { + // Remove common powers of two without dividing the significands. + this->numerator.exponent -= denominator.exponent; + } + + Product numerator; + double denominator; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp index 4b8c83acf..34e7050a2 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,21 +12,17 @@ namespace duckdb { -class QueryGraphManager; - class CostModel { public: - explicit CostModel(QueryGraphManager &query_graph_manager, CardinalityEstimator &cardinality_estimator); + explicit CostModel(CardinalityEstimator &cardinality_estimator); public: - //! Compute cost of a join relation set - double ComputeCost(DPJoinNode &left, DPJoinNode &right, JoinRelationSet &combination, - const vector> &possible_connections); + //! Compute work for the selected operator and its estimated output. + double ComputeCost(const DPJoinNode &left, const DPJoinNode &right, optional_ptr join_operator, + double output_rows); CardinalityEstimator &GetCardinalityEstimator(); private: - //! query graph storing relation manager information - QueryGraphManager &query_graph_manager; CardinalityEstimator &cardinality_estimator; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/filter_info.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/filter_info.hpp index 7806f2b0d..3a10f536f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/filter_info.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/filter_info.hpp @@ -55,6 +55,9 @@ class FilterInfo { //! Semantic operator sides, including relations not referenced by this predicate. optional_ptr semantic_left_set; optional_ptr semantic_right_set; + //! Identifies transitively connected ON equalities of one LEFT operator: they share a key and + //! only one of them contributes its domain to the denominator. + optional_idx left_equality_group; }; } // 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 a699a6f54..f56cd1ef7 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp @@ -8,6 +8,7 @@ #pragma once #include "duckdb/optimizer/join_order/join_relation_set.hpp" +#include "duckdb/optimizer/join_order/cardinality_value.hpp" namespace duckdb { @@ -43,8 +44,8 @@ class DPJoinNode { //! in the cost model is error prone. If the plan enumerator join node is updated and not the cost model //! the whole Join Order Optimizer can start exhibiting undesired behavior. double cost; - //! used only to populate logical operators with estimated cardinalities after the best join plan has been found. - idx_t cardinality = DConstants::INVALID_INDEX; + //! Candidate output used when composing parent estimates and costs. + CardinalityValue cardinality {0}; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp index 746ba152f..f91e1160f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp @@ -60,6 +60,8 @@ struct JoinOrderOperator { vector conditions; //! Predicate copies used only for cardinality estimation and query-graph connectivity. vector costing_predicate_indices; + //! LEFT ON residuals not covered by a costing predicate or an equivalent equality key. + vector> residual_predicates; //! Whether the complete conditions must be applied by this operator occurrence. This is decided before conflict //! rule simplification, which can erase conflicts already absorbed by the syntactic eligibility set. bool must_apply_as_operator = false; 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 93eb5b3e0..9a6fbb80a 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 @@ -30,6 +30,8 @@ struct JoinOrderUtil { static bool HasValidJoinEndpoints(const FilterInfo &filter); static bool HasDisjointJoinEndpoints(const FilterInfo &filter); static RelationIndex GetBindingRelation(const ColumnBinding &binding); + //! Extract a column binding through invertible, non-TRY casts. + static ColumnBinding GetEquivalenceBinding(const Expression &expression); }; class JoinPredicate { @@ -133,7 +135,6 @@ class JoinPredicateModel { const vector> &GetSelectivityPredicates() const; const vector> &GetGraphPredicates() const; const vector &GetEqualityClasses() const; - bool HasLeftJoinPredicates() const; bool HasDirectCompositeEquality(JoinRelationSet &pair) const; @@ -143,7 +144,6 @@ class JoinPredicateModel { vector> equality_join_predicates; vector> selectivity_predicates; vector> graph_predicates; - bool has_left_join_predicates = false; vector equality_classes; reference_map_t equality_pairs; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp index 60462dfbf..ea1be0c96 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp @@ -55,6 +55,8 @@ class JoinRelationSetManager { JoinRelationSet &GetJoinRelation(unsafe_unique_array relations, idx_t count); //! Union two sets of relations together and create a new relation set JoinRelationSet &Union(JoinRelationSet &left, JoinRelationSet &right); + JoinRelationSet &Intersection(const JoinRelationSet &left, const JoinRelationSet &right); + JoinRelationSet &Difference(const JoinRelationSet &left, const JoinRelationSet &right); string ToString() const; void Print(); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp index 26b41dbd7..044d2bba4 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp @@ -25,12 +25,12 @@ class QueryGraphEdges; struct GenerateJoinRelation { public: - GenerateJoinRelation(optional_ptr set, unique_ptr op_p, idx_t cardinality_p); + GenerateJoinRelation(optional_ptr set, unique_ptr op_p, RelationStats stats_p); public: optional_ptr set; unique_ptr op; - idx_t cardinality; + RelationStats stats; }; //! The QueryGraphManager manages the process of extracting the reorderable and nonreorderable operations @@ -43,9 +43,13 @@ class QueryGraphManager { public: //! Extract the join relations, optimizing non-reoderable relations when encountered bool Build(JoinOrderOptimizer &optimizer, LogicalOperator &op); + //! Prepare an inner-join region without mutating or enumerating its plan. + bool BuildForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op); + optional CombineRelationStats(const vector &bindings, + const vector &relation_stats, + idx_t root_cardinality) const; //! Reconstruct the logical plan using the plan found by the plan enumerator - unique_ptr Reconstruct(unique_ptr plan, - const vector &relation_stats); + GenerateJoinRelation Reconstruct(unique_ptr plan, const vector &relation_stats); //! Plan enumerator may not find a full plan and therefore will need to create cross products to create edges. void CreateQueryGraphCrossProduct(JoinRelationSet &left, JoinRelationSet &right); //! Admit original cross-product edges when the current hyperedges cannot complete enumeration. @@ -61,8 +65,13 @@ class QueryGraphManager { //! Get a reference to the QueryGraphEdges structure that stores edges between nodes and hypernodes. const QueryGraphEdges &GetQueryGraphEdges() const; const JoinPredicateModel &GetPredicateModel() const; + const vector> &GetJoinOperators() const; private: + optional CombineRelationStats(const vector &bindings, + const vector> &inputs, + idx_t root_cardinality) const; + void PreparePredicateModel(LogicalOperator &op); void GetColumnBinding(const Expression &expression, ColumnBinding &binding); void GetEquivalenceBinding(const Expression &expression, ColumnBinding &binding); @@ -71,7 +80,7 @@ class QueryGraphManager { //! Build the normalized predicate model after filter endpoints and stats bindings are populated. void BuildPredicateModel(); - void BuildLeftEqualityPairs(); + void BuildLeftJoinPredicates(); void BuildInnerCompanionSets(); void ClearExtractedExpressions(); idx_t FindGraphComponent(RelationIndex relation); 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 80fac4596..f83d2f7ea 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 @@ -24,6 +24,7 @@ namespace duckdb { class JoinOrderOptimizer; class FilterInfo; +class RelationStatsExtractor; struct JoinOrderExtraction { vector> filters; @@ -53,6 +54,11 @@ class RelationManager { vector> &filter_operators, optional_ptr parent = nullptr); + //! Collect an inner-join region without optimizing or rewriting its leaves. + bool ExtractJoinRelationsForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op, + vector> &filter_operators, + optional_ptr parent = nullptr); + //! for each join filter in the logical plan op, extract the relations that are referred to on //! both sides of the join filter, along with the tables & indexes. JoinOrderExtraction ExtractEdges(LogicalOperator &op, vector> &filter_operators, @@ -77,6 +83,16 @@ class RelationManager { void PrintRelationStats(); private: + struct PendingRelation { + LogicalOperator &op; + optional_ptr parent; + bool optimize_as_leaf; + }; + + bool ExtractJoinRelation(JoinOrderOptimizer &optimizer, PendingRelation relation, + vector> &filter_operators, + vector &pending_relations); + bool RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats); optional_ptr GetJoinRelations(column_binding_set_t &column_bindings, JoinRelationSetManager &set_manager); void GetColumnBindingsFromExpression(const Expression &expression, column_binding_set_t &column_bindings); diff --git a/src/duckdb/src/include/duckdb/optimizer/matcher/expression_matcher.hpp b/src/duckdb/src/include/duckdb/optimizer/matcher/expression_matcher.hpp index 785dca0a7..17b7151d5 100644 --- a/src/duckdb/src/include/duckdb/optimizer/matcher/expression_matcher.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/matcher/expression_matcher.hpp @@ -87,6 +87,17 @@ class CastExpressionMatcher : public ExpressionMatcher { bool Match(Expression &expr, vector> &bindings) override; }; +class NotExpressionMatcher : public ExpressionMatcher { +public: + NotExpressionMatcher() : ExpressionMatcher(ExpressionClass::BOUND_OPERATOR) { + expr_type = make_uniq(ExpressionType::OPERATOR_NOT); + } + //! The matcher for the operand of the NOT (nullptr for ANY) + unique_ptr child; + + bool Match(Expression &expr, vector> &bindings) override; +}; + class InClauseExpressionMatcher : public ExpressionMatcher { public: InClauseExpressionMatcher() : ExpressionMatcher(ExpressionClass::BOUND_OPERATOR) { 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 955f11d6f..f988bcb36 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 @@ -33,6 +33,7 @@ class RelationStatsExtractor { private: optional ExtractInternal(LogicalOperator &op); + optional ExtractJoinStats(LogicalOperator &op); optional ExtractCTERef(LogicalCTERef &cte_ref); private: 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 ed1dff677..42976f54f 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 @@ -10,6 +10,7 @@ #include "duckdb/common/optional.hpp" #include "duckdb/common/enums/join_type.hpp" +#include "duckdb/common/helper.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/logical_operator.hpp" @@ -31,6 +32,7 @@ class LogicalGet; class LogicalLimit; class LogicalProjection; class LogicalWindow; +class RelationStatsExtractor; struct SemiAntiJoinDomain { idx_t total_domain; @@ -49,7 +51,6 @@ class RelationStatisticsHelper { static constexpr double DEFAULT_SELECTIVITY = 0.2; public: - static idx_t InspectTableFilter(idx_t cardinality, const TableFilter &filter, BaseStatistics &base_stats); static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context); static RelationStats ExtractDelimGetStats(LogicalDelimGet &delim_get, ClientContext &context); static RelationStats ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context); @@ -62,6 +63,10 @@ class RelationStatisticsHelper { const RelationStats &child_stats); static optional ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, ClientContext &context); + //! Reuse the caller snapshot for aggregate input refinements. + static optional ExtractAggregationStats(LogicalAggregate &aggregate, + const RelationStats &child_stats, + RelationStatsExtractor &extractor); static optional ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats); static optional ExtractDistinctStats(LogicalDistinct &distinct, const RelationStats &child_stats); static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats); @@ -70,10 +75,25 @@ class RelationStatisticsHelper { static optional ProjectOutputStats(const RelationStats &stats, LogicalOperator &op); static optional RebindOutputStats(const RelationStats &stats, LogicalOperator &op); static optional SelectTotalDomain(const vector &domains); + static void ApplySemiAntiJoinStats(LogicalComparisonJoin &join, const RelationStats &left, + const RelationStats &right, RelationStats &result); + static idx_t CardinalityFromDouble(double cardinality); static idx_t EstimateDistinctCardinality(const vector &distinct_counts, idx_t input_cardinality); static DistinctCount EstimateCurrentDomain(const DistinctCount ¤t_domain, idx_t input_cardinality, idx_t output_cardinality); static void ApplyCardinality(RelationStats &stats, idx_t output_cardinality); + //! Share fallback policy between ordinary statistics and scaled join cardinalities. + template + static T EstimateSemiAntiJoinFallbackCardinality(const T &preserved_cardinality, idx_t rhs_cardinality, + JoinType join_type) { + auto is_anti = join_type == JoinType::ANTI || join_type == JoinType::RIGHT_ANTI; + if (rhs_cardinality == 0) { + return is_anti ? MaxValue(T(0), preserved_cardinality) : T(0); + } + // Retain fractional estimates while composing costs. + auto estimate = MinValue(preserved_cardinality, MaxValue(T(1), preserved_cardinality * T(DEFAULT_SELECTIVITY))); + return MaxValue(T(0), estimate); + } static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoinFallback(double preserved_cardinality, idx_t rhs_cardinality, JoinType join_type); static SemiAntiJoinCardinalityEstimate diff --git a/src/duckdb/src/include/duckdb/optimizer/rule/list.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/list.hpp index e515866c1..24e5b6197 100644 --- a/src/duckdb/src/include/duckdb/optimizer/rule/list.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/rule/list.hpp @@ -15,6 +15,8 @@ #include "duckdb/optimizer/rule/move_constants.hpp" #include "duckdb/optimizer/rule/not_comparison_simplification.hpp" #include "duckdb/optimizer/rule/not_conjunction_simplification.hpp" +#include "duckdb/optimizer/rule/not_constant_or_null_simplification.hpp" +#include "duckdb/optimizer/rule/or_range_merge.hpp" #include "duckdb/optimizer/rule/enum_comparison.hpp" #include "duckdb/optimizer/rule/regex_optimizations.hpp" #include "duckdb/optimizer/rule/struct_extract_struct_pack_folding.hpp" diff --git a/src/duckdb/src/include/duckdb/optimizer/rule/not_constant_or_null_simplification.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/not_constant_or_null_simplification.hpp new file mode 100644 index 000000000..63067c3d8 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/rule/not_constant_or_null_simplification.hpp @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/rule/not_constant_or_null_simplification.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/rule.hpp" + +namespace duckdb { + +// Rewrites NOT(constant_or_null(v, e)) into constant_or_null(!v, e): +// the per-row NULL check on e is preserved, only the constant is negated +class NotConstantOrNullSimplificationRule : public Rule { +public: + explicit NotConstantOrNullSimplificationRule(ExpressionRewriter &rewriter); + + unique_ptr Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, + bool is_root) override; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/rule/or_range_merge.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/or_range_merge.hpp new file mode 100644 index 000000000..ba6380d6d --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/rule/or_range_merge.hpp @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/rule/or_range_merge.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/rule.hpp" + +namespace duckdb { + +//! Merges range predicates on the same expression that are joined by OR into a single range: +//! (x BETWEEN 1 AND 20) OR (x BETWEEN 21 AND 40) => x BETWEEN 1 AND 40 +//! Ranges merge when they overlap or touch, and for integral types also when they are adjacent (20 | 21). +class OrRangeMergeRule : public Rule { +public: + explicit OrRangeMergeRule(ExpressionRewriter &rewriter); + + unique_ptr Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, + bool is_root) override; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp b/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp new file mode 100644 index 000000000..c802177fd --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp @@ -0,0 +1,59 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/scalar_aggregate_merger.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/column_binding_replacer.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +class Optimizer; + +//! The ScalarAggregateMerger computes sibling ungrouped aggregates over the same table(s) in one pass. +//! +//! An uncorrelated scalar subquery that returns exactly one row, and a one-row derived table in a FROM list, are +//! planned as a cross product with the rest of the query, and each of them reads its tables on its own. Siblings of +//! the form [projection ->] ungrouped aggregate -> filters -> plain scan(s) of the same table(s) are rewritten into one +//! scan, filtered by the predicates every sibling shares and the OR of what each has beyond them, feeding one aggregate +//! that holds every sibling's aggregates, each with a FILTER (WHERE ...) of its own predicate. A projection then hands +//! every sibling's columns back under new bindings (TPC-DS q9, q28, q88 and q90). +//! +//! The merge trades scans for FILTERs, which pays off when the scan is the expensive part: siblings over a table +//! function (read_parquet, read_csv, ...) are merged, siblings over a catalog table only when it has at least +//! scalar_aggregate_merge_threshold rows. +class ScalarAggregateMerger { +public: + explicit ScalarAggregateMerger(Optimizer &optimizer); + + //! Rewrites every eligible group of siblings in the plan + void Optimize(unique_ptr &plan); + +public: + struct Branch; + struct MergeTarget; + +private: + void VisitOperator(unique_ptr &op); + //! Merges the eligible leaves of the cross-product tree rooted at `op` + void MergeCrossProduct(unique_ptr &op); + //! Appends `leaf` to `branches` when it has the shape of a branch + static void TryMatchBranch(unique_ptr &leaf, vector &branches); + //! Whether the scans of `branch` cost enough for the merge to pay off: a table function (files, remote sources) + //! or a table of at least scalar_aggregate_merge_threshold rows + bool IsWorthMerging(const Branch &branch); + //! The merged leaf that replaces the branches of `group`, or null when the group cannot be merged + unique_ptr MergeBranches(vector &branches, const vector &group); + +private: + Optimizer &optimizer; + //! The bindings of the branches that were merged away, pointed at the merged projection's columns + vector replacements; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/self_join_aggregate.hpp b/src/duckdb/src/include/duckdb/optimizer/self_join_aggregate.hpp new file mode 100644 index 000000000..1f52f45e1 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/self_join_aggregate.hpp @@ -0,0 +1,28 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/self_join_aggregate.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/optimizer.hpp" + +namespace duckdb { + +//! Rewrites a self-join of one table on equal keys and exactly one inequality, read only through its keys by a +//! parent that ignores duplicates, into GROUP BY keys HAVING min(x) <> max(x) over a single scan. +//! See self_join_aggregate.cpp for the conditions and the argument that the rewrite is exact. +class SelfJoinAggregate { +public: + explicit SelfJoinAggregate(Optimizer &optimizer); + + unique_ptr Optimize(unique_ptr op); + +private: + Optimizer &optimizer; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp index ecef59d2d..2d680c3f6 100644 --- a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp @@ -183,6 +183,8 @@ class StatisticsPropagator { unique_ptr node_stats; //! Whether statistics changed which relations a filter depends on bool filter_bindings_changed = false; + //! Whether propagated statistics are attached to the expressions as verification statistics + bool attach_verification_stats = true; //! The chain of operators from the root down to the operator currently being propagated vector>> propagation_path; }; 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 dbcd59e57..221e3cef4 100644 --- a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp @@ -9,7 +9,6 @@ #pragma once #include "duckdb/optimizer/column_binding_replacer.hpp" -#include "duckdb/optimizer/remove_unused_columns.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/common/enums/order_type.hpp" @@ -35,15 +34,18 @@ struct TopNWindowEliminationParameters { bool row_ids_may_have_duplicates = false; }; -class TopNWindowElimination : public BaseColumnPruner { +class TopNWindowElimination : public LogicalOperatorVisitor { public: explicit TopNWindowElimination(ClientContext &context, Optimizer &optimizer, optional_ptr>> stats_p); unique_ptr Optimize(unique_ptr op); + // 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); + private: - bool CanOptimize(LogicalOperator &op); unique_ptr OptimizeInternal(unique_ptr op, ColumnBindingReplacer &replacer); unique_ptr CreateAggregateOperator(LogicalWindow &window, vector> args, diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp index a12688201..1fb0222dc 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp @@ -15,6 +15,9 @@ #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/common/reference_map.hpp" #include "duckdb/parallel/executor_task.hpp" +// Complete type required: the unique_ptr in ResolveExternalInputs' signature instantiates the +// deleter in sanitizer builds of every includer, which rejects a forward declaration. +#include "duckdb/parallel/pipeline_schedule.hpp" namespace duckdb { @@ -91,9 +94,16 @@ class PipelineBuildState { void AddExternalInputCandidate(Pipeline &pipeline, PhysicalOperator &materialized_source, PhysicalOperator &external_source, shared_ptr cte_dependency, PhysicalCTE &cte, idx_t consumer_idx); + void AddBufferedConsumer(Pipeline &pipeline, PhysicalOperator &materialized_source, + shared_ptr cte_dependency, PhysicalCTE &cte, idx_t consumer_idx); void AddCTEPipelineSelection(PhysicalCTE &cte, Pipeline &pipeline, shared_ptr cte_dependency, bool dependency_added); - void ResolveExternalInputs(const vector> &meta_pipelines); + //! model_runtime_filter_edges must mirror the executor's runtime-filter scheduling condition (initial + //! schedule without recursive CTEs), so the analysis sees the edges the executor will add. + //! Returns the validated schedule (with runtime-filter edges modeled when requested) so the executor can + //! reuse it instead of rebuilding and re-deriving the edges, or nullptr when nothing needed resolution. + unique_ptr ResolveExternalInputs(const vector> &meta_pipelines, + bool model_runtime_filter_edges); private: unique_ptr data; @@ -126,6 +136,7 @@ class Pipeline : public enable_shared_from_this { void AddDependency(shared_ptr &pipeline); void AddDataflowDependency(shared_ptr &pipeline); + void RemoveDataflowDependency(const shared_ptr &pipeline); //! The dependencies of this pipeline on pipelines of other MetaPipelines vector> GetDependencies() const; //! The dependencies of this pipeline on pipelines of the same MetaPipeline diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp index a31d8c3d6..1198a19a6 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp @@ -124,6 +124,8 @@ class PipelineBroadcastExchange { vector> GetProducerPipelines() const; void SelectBufferedConsumer(idx_t consumer_idx, PipelineBroadcastExchangeScanMode scan_mode); void SelectMaterializedConsumer(idx_t consumer_idx); + //! Converts an already registered buffered consumer to a materialized one, before execution starts. + void DemoteBufferedConsumerToMaterialized(idx_t consumer_idx); void ResetConsumerRegistrations(); void Reset(); void SetLogOperator(const PhysicalOperator &op); diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline_schedule.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline_schedule.hpp index 96102679d..87b9919b7 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline_schedule.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline_schedule.hpp @@ -19,6 +19,9 @@ class Pipeline; enum class PipelineScheduleStageType : uint8_t { INITIALIZE, EXECUTE, PREPARE_FINISH, FINISH, COMPLETE }; enum class PipelineScheduleMode : uint8_t { COMPLETE, ACTIVE_SUBSET }; +//! Which dependencies participate in a graph traversal: only the scheduled (event) dependencies, or also the +//! analysis-only dependencies that model runtime completion ordering for cycle detection. +enum class PipelineScheduleGraph : uint8_t { SCHEDULED, WITH_ANALYSIS }; struct PipelineScheduleStage { PipelineScheduleStage(PipelineScheduleStageType type, shared_ptr pipeline); @@ -26,6 +29,10 @@ struct PipelineScheduleStage { PipelineScheduleStageType type; shared_ptr pipeline; vector dependencies; + //! Constraints that hold at runtime but must not gate event scheduling: a dataflow consumer's execute only + //! completes once its producer has finalized, yet the consumer must be able to start and drain the exchange, + //! otherwise producer backpressure deadlocks. Cycle analysis sees these, the event graph does not. + vector analysis_dependencies; }; struct PipelineScheduleExternalInputDependency { @@ -53,8 +60,8 @@ struct PipelineSchedule { vector> initialize_on_schedule_pipelines; vector external_input_dependencies; - bool HasCycle() const; - vector GetCycle() const; + bool HasCycle(PipelineScheduleGraph graph = PipelineScheduleGraph::WITH_ANALYSIS) const; + vector GetCycle(PipelineScheduleGraph graph = PipelineScheduleGraph::WITH_ANALYSIS) const; bool DependsOn(idx_t dependent, idx_t dependency) const; bool TryAddDependency(idx_t dependent, idx_t dependency); }; @@ -62,5 +69,10 @@ struct PipelineSchedule { unique_ptr BuildPipelineSchedule(const vector> &meta_pipelines, PipelineScheduleMode mode = PipelineScheduleMode::COMPLETE); void ScheduleRuntimeFilters(PipelineSchedule &schedule); +//! Clears stale runtime filters without adding edges, for a schedule that already models them. +void ClearRuntimeFilters(PipelineSchedule &schedule); +//! Adds the same ordering edges as ScheduleRuntimeFilters without clearing filters, so consumer selection can +//! analyze the graph the executor will actually run. +void AddRuntimeFilterScheduleDependencies(PipelineSchedule &schedule); } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/task_executor.hpp b/src/duckdb/src/include/duckdb/parallel/task_executor.hpp index f5f0cef70..fbe34febd 100644 --- a/src/duckdb/src/include/duckdb/parallel/task_executor.hpp +++ b/src/duckdb/src/include/duckdb/parallel/task_executor.hpp @@ -17,6 +17,7 @@ namespace duckdb { +class Context; class TaskExecutor; class TaskExecutorTask; @@ -64,6 +65,7 @@ class BaseExecutorTask { class TaskExecutor { public: explicit TaskExecutor(ClientContext &context, TaskSchedulerType type = TaskSchedulerType::REGULAR); + explicit TaskExecutor(Context &context, TaskSchedulerType type = TaskSchedulerType::REGULAR); explicit TaskExecutor(TaskScheduler &scheduler, TaskSchedulerType type = TaskSchedulerType::REGULAR); ~TaskExecutor(); @@ -123,7 +125,7 @@ class TaskExecutor { idx_t completed_tasks DUCKDB_GUARDED_BY(token->producer_lock) = 0; idx_t total_tasks DUCKDB_GUARDED_BY(token->producer_lock) = 0; atomic cancelled {false}; - optional_ptr context; + optional_ptr context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/task_notifier.hpp b/src/duckdb/src/include/duckdb/parallel/task_notifier.hpp index 6bf34b3c0..fa44dab76 100644 --- a/src/duckdb/src/include/duckdb/parallel/task_notifier.hpp +++ b/src/duckdb/src/include/duckdb/parallel/task_notifier.hpp @@ -11,17 +11,17 @@ #include "duckdb/common/optional_ptr.hpp" namespace duckdb { -class ClientContext; +class Context; //! The TaskNotifier notifies ClientContextState listener about started / stopped tasks class TaskNotifier { public: - explicit TaskNotifier(optional_ptr context_p); + explicit TaskNotifier(optional_ptr context_p); ~TaskNotifier(); private: - optional_ptr context; + optional_ptr context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/task_scheduler.hpp b/src/duckdb/src/include/duckdb/parallel/task_scheduler.hpp index 5b767d08b..992f437a6 100644 --- a/src/duckdb/src/include/duckdb/parallel/task_scheduler.hpp +++ b/src/duckdb/src/include/duckdb/parallel/task_scheduler.hpp @@ -106,6 +106,8 @@ class TaskScheduler { DatabaseInstance &db; //! Lock for modifying the thread count mutex thread_lock; + //! Set when the thread count changed + atomic relaunch_requested; //! The thread pools array, TASK_SCHEDULER_TYPE_COUNT> pools; //! The task queues diff --git a/src/duckdb/src/include/duckdb/parser/column_definition.hpp b/src/duckdb/src/include/duckdb/parser/column_definition.hpp index aacd3d85d..e9853d66d 100644 --- a/src/duckdb/src/include/duckdb/parser/column_definition.hpp +++ b/src/duckdb/src/include/duckdb/parser/column_definition.hpp @@ -83,6 +83,8 @@ class ColumnDefinition { ParsedExpression &GeneratedExpressionMutable(); const ParsedExpression &GeneratedExpression() const; + //! Whether the generated expression is set (always the case for valid generated columns) + bool HasGeneratedExpression() const; void SetGeneratedExpression(unique_ptr expression); void ChangeGeneratedExpressionType(const LogicalType &type); void GetListOfDependencies(vector &dependencies) const; diff --git a/src/duckdb/src/include/duckdb/parser/parser.hpp b/src/duckdb/src/include/duckdb/parser/parser.hpp index 58f7015d8..23c361934 100644 --- a/src/duckdb/src/include/duckdb/parser/parser.hpp +++ b/src/duckdb/src/include/duckdb/parser/parser.hpp @@ -68,6 +68,13 @@ class Parser { //! using `stmt->stmt_location` if needed. DUCKDB_API unique_ptr ParseTopLevelStatement(TokenIterator &token_iterator, const string &query); + //! Whether `query` is a complete, semicolon-terminated statement sequence under this parser's + //! grammar. Interactive frontends use this to decide between submitting the buffer and reading + //! more input: an unterminated string or comment, a missing final semicolon, and a statement + //! prefix the grammar can extend are incomplete. Input the grammar rejects mid-way counts as + //! complete, so the error surfaces on execution. + DUCKDB_API bool IsQueryComplete(const string &query); + //! Tokenize a query, returning the raw tokens together with their locations static vector Tokenize(const string &query); diff --git a/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp b/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp index a2054a041..a6b6a4af5 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp @@ -29,6 +29,8 @@ struct ParsedOperator { struct OtherOperatorTail { ParsedOperator op; unique_ptr expression; + //! Whether the right-hand side is a subquery, as in ANY(SELECT ...) + bool is_subquery = false; }; enum class ExpressionTailType : uint8_t { IS_TEST, DISTINCT, COMPARISON, OTHER_OPERATOR, CAST }; @@ -42,6 +44,11 @@ struct IsExpressionTail { unique_ptr cast; }; +struct SimpleCaseCheck { + vector when; + unique_ptr then_expr; +}; + struct BinaryExpressionTail { string op; unique_ptr expression; diff --git a/src/duckdb/src/include/duckdb/parser/peg/compiled_grammar.hpp b/src/duckdb/src/include/duckdb/parser/peg/compiled_grammar.hpp index 57fe65f01..e561ecb19 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/compiled_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/compiled_grammar.hpp @@ -44,6 +44,10 @@ struct CompiledGrammar { static shared_ptr Create(); //! Get the (cached) grammar for the selected extensions without changing the client configuration. static shared_ptr Create(const ClientContext &context, const vector &active_extensions); + //! Get the (cached) grammar for the given extension selection, without changing the client + //! configuration (the base grammar when the selection is empty). + static shared_ptr ComposeSessionGrammar(ClientContext &context, + const vector &extension_names); private: MatcherAllocator allocator; 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 185c2c98b..bcfb1e9b2 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -1405,7 +1405,13 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 84, 97, 114, 103, 101, 116, 79, 112, 116, 65, 108, 105, 97, 115, 32, 60, 45, 32, 66, 97, 115, 101, 84, 97, 98, 108, 101, 78, 97, 109, 101, 32, 84, 97, 114, 103, 101, 116, 65, 108, 105, 97, 115, 63, 10, 84, 97, 114, 103, 101, 116, 65, 108, 105, 97, 115, 32, 60, 45, 32, 39, 65, 83, 39, 63, 32, 67, 111, 108, 73, 100, 10, 68, 101, 108, 101, 116, 101, 85, 115, 105, 110, 103, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 39, 85, 83, 73, 78, 71, 39, 32, 76, 105, 115, 116, 40, 84, 97, 98, 108, 101, 82, 101, 102, 41, 10, - 68, 101, 115, 99, 114, 105, 98, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 83, 104, 111, 119, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 83, 101, 108, 101, 99, 116, 32, 47, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 66, 121, 78, 97, 109, 101, 10, + 68, 101, 115, 99, 114, 105, 98, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 32, 47, 32, 83, 104, 111, 119, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 83, 101, 108, 101, 99, 116, 32, 47, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 66, 121, 78, 97, 109, 101, 10, + 35, 32, 34, 83, 72, 79, 87, 32, 91, 65, 76, 76, 93, 32, 69, 88, 84, 69, 82, 78, 65, 76, 32, 82, 69, 83, 79, 85, 82, 67, 69, 83, 34, 32, 105, 115, 32, 97, 32, 113, 117, 101, 114, 121, 32, 111, 118, 101, 114, 32, 100, 117, 99, 107, 100, 98, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 114, 101, 115, 111, 117, 114, 99, 101, 115, 44, 32, 115, 111, 32, 105, 116, 32, 119, 111, 114, 107, 115, 32, 97, 115, 32, 97, 32, 115, 117, 98, 113, 117, 101, 114, 121, 32, 116, 111, 111, 46, 32, 73, 116, 32, 99, 111, 109, 101, 115, 10, + 35, 32, 102, 105, 114, 115, 116, 58, 32, 34, 83, 72, 79, 87, 32, 65, 76, 76, 34, 32, 97, 108, 111, 110, 101, 32, 105, 115, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 44, 32, 97, 110, 100, 32, 34, 83, 72, 79, 87, 32, 60, 110, 97, 109, 101, 62, 34, 32, 105, 115, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 44, 32, 97, 110, 100, 32, 110, 101, 105, 116, 104, 101, 114, 32, 99, 97, 110, 32, 98, 101, 32, 114, 101, 116, 114, 105, 101, 100, 32, 111, 110, 99, 101, 32, 109, 97, 116, 99, 104, 101, 100, 46, 10, + 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 32, 60, 45, 32, 83, 104, 111, 119, 82, 117, 108, 101, 32, 39, 65, 76, 76, 39, 63, 32, 39, 69, 88, 84, 69, 82, 78, 65, 76, 39, 32, 39, 82, 69, 83, 79, 85, 82, 67, 69, 83, 39, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 84, 121, 112, 101, 63, 10, + 35, 32, 34, 87, 73, 84, 72, 32, 84, 89, 80, 69, 32, 39, 97, 119, 115, 58, 115, 51, 116, 97, 98, 108, 101, 115, 58, 116, 97, 98, 108, 101, 45, 98, 117, 99, 107, 101, 116, 39, 34, 32, 114, 101, 115, 116, 114, 105, 99, 116, 115, 32, 116, 104, 101, 32, 108, 105, 115, 116, 105, 110, 103, 32, 40, 97, 110, 100, 32, 116, 104, 101, 32, 100, 105, 115, 99, 111, 118, 101, 114, 121, 41, 32, 116, 111, 32, 111, 110, 101, 32, 116, 121, 112, 101, 59, 32, 97, 32, 98, 97, 114, 101, 32, 105, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, + 35, 32, 105, 115, 32, 112, 97, 115, 115, 101, 100, 32, 116, 104, 114, 111, 117, 103, 104, 32, 97, 115, 32, 116, 104, 101, 32, 116, 121, 112, 101, 32, 110, 97, 109, 101, 32, 97, 115, 32, 119, 101, 108, 108, 46, 10, + 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 84, 121, 112, 101, 32, 60, 45, 32, 39, 87, 73, 84, 72, 39, 32, 39, 84, 89, 80, 69, 39, 32, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 10, 35, 32, 34, 68, 69, 83, 67, 82, 73, 66, 69, 32, 40, 113, 117, 101, 114, 121, 41, 34, 32, 97, 110, 100, 32, 34, 83, 85, 77, 77, 65, 82, 73, 90, 69, 32, 40, 113, 117, 101, 114, 121, 41, 34, 32, 100, 101, 115, 99, 114, 105, 98, 101, 32, 116, 104, 101, 32, 113, 117, 101, 114, 121, 39, 115, 32, 99, 111, 108, 117, 109, 110, 115, 46, 32, 34, 83, 72, 79, 87, 32, 40, 113, 117, 101, 114, 121, 41, 34, 32, 100, 111, 101, 115, 32, 116, 111, 111, 32, 98, 117, 116, 32, 105, 115, 32, 100, 101, 112, 114, 101, 99, 97, 116, 101, 100, 44, 10, 35, 32, 115, 111, 32, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 105, 115, 32, 112, 97, 114, 115, 101, 100, 32, 121, 101, 116, 32, 115, 117, 112, 112, 114, 101, 115, 115, 101, 100, 32, 102, 114, 111, 109, 32, 97, 117, 116, 111, 99, 111, 109, 112, 108, 101, 116, 101, 32, 40, 109, 97, 116, 99, 104, 101, 114, 95, 102, 97, 99, 116, 111, 114, 121, 46, 99, 112, 112, 41, 32, 45, 32, 83, 72, 79, 87, 32, 119, 111, 110, 39, 116, 32, 111, 102, 102, 101, 114, 32, 116, 111, 32, 99, 111, 109, 112, 108, 101, 116, 101, 32, 97, 32, 113, 117, 101, 114, 121, 46, 10, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 60, 45, 32, 83, 104, 111, 119, 82, 117, 108, 101, 32, 83, 101, 108, 101, 99, 116, 83, 116, 97, 116, 101, 109, 101, 110, 116, 73, 110, 116, 101, 114, 110, 97, 108, 10, @@ -1572,7 +1578,14 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 83, 117, 98, 113, 117, 101, 114, 121, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 83, 117, 98, 113, 117, 101, 114, 121, 78, 111, 116, 63, 32, 83, 117, 98, 113, 117, 101, 114, 121, 69, 120, 105, 115, 116, 115, 63, 32, 83, 117, 98, 113, 117, 101, 114, 121, 82, 101, 102, 101, 114, 101, 110, 99, 101, 10, 83, 117, 98, 113, 117, 101, 114, 121, 78, 111, 116, 32, 60, 45, 32, 39, 78, 79, 84, 39, 10, 83, 117, 98, 113, 117, 101, 114, 121, 69, 120, 105, 115, 116, 115, 32, 60, 45, 32, 39, 69, 88, 73, 83, 84, 83, 39, 10, - 67, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 39, 67, 65, 83, 69, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 63, 32, 67, 97, 115, 101, 87, 104, 101, 110, 84, 104, 101, 110, 43, 32, 67, 97, 115, 101, 69, 108, 115, 101, 63, 32, 39, 69, 78, 68, 39, 10, + 67, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 47, 32, 83, 101, 97, 114, 99, 104, 101, 100, 67, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 39, 67, 65, 83, 69, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 87, 104, 101, 110, 84, 104, 101, 110, 43, 32, 67, 97, 115, 101, 69, 108, 115, 101, 63, 32, 39, 69, 78, 68, 39, 10, + 83, 101, 97, 114, 99, 104, 101, 100, 67, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 39, 67, 65, 83, 69, 39, 32, 67, 97, 115, 101, 87, 104, 101, 110, 84, 104, 101, 110, 43, 32, 67, 97, 115, 101, 69, 108, 115, 101, 63, 32, 39, 69, 78, 68, 39, 10, + 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 87, 104, 101, 110, 84, 104, 101, 110, 32, 60, 45, 32, 39, 87, 72, 69, 78, 39, 32, 76, 105, 115, 116, 40, 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 87, 104, 101, 110, 79, 112, 101, 114, 97, 110, 100, 41, 32, 39, 84, 72, 69, 78, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 35, 32, 87, 72, 69, 78, 32, 60, 32, 48, 32, 99, 111, 109, 112, 97, 114, 101, 115, 32, 116, 104, 101, 32, 67, 65, 83, 69, 32, 111, 112, 101, 114, 97, 110, 100, 32, 119, 105, 116, 104, 32, 60, 44, 32, 97, 32, 87, 72, 69, 78, 32, 111, 112, 101, 114, 97, 110, 100, 32, 119, 105, 116, 104, 111, 117, 116, 32, 97, 110, 32, 111, 112, 101, 114, 97, 116, 111, 114, 32, 99, 111, 109, 112, 97, 114, 101, 115, 32, 119, 105, 116, 104, 32, 61, 10, + 35, 32, 87, 72, 69, 78, 32, 48, 44, 32, 49, 32, 109, 97, 116, 99, 104, 101, 115, 32, 105, 102, 32, 97, 110, 121, 32, 111, 102, 32, 116, 104, 101, 32, 111, 112, 101, 114, 97, 110, 100, 115, 32, 109, 97, 116, 99, 104, 101, 115, 10, + 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 87, 104, 101, 110, 79, 112, 101, 114, 97, 110, 100, 32, 60, 45, 32, 67, 111, 109, 112, 97, 114, 105, 115, 111, 110, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 32, 47, 32, 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 87, 104, 101, 110, 69, 113, 117, 97, 108, 115, 10, + 83, 105, 109, 112, 108, 101, 67, 97, 115, 101, 87, 104, 101, 110, 69, 113, 117, 97, 108, 115, 32, 60, 45, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 67, 97, 115, 101, 87, 104, 101, 110, 84, 104, 101, 110, 32, 60, 45, 32, 39, 87, 72, 69, 78, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 39, 84, 72, 69, 78, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 67, 97, 115, 101, 69, 108, 115, 101, 32, 60, 45, 32, 39, 69, 76, 83, 69, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 84, 121, 112, 101, 76, 105, 116, 101, 114, 97, 108, 32, 60, 45, 32, 84, 121, 112, 101, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 10, @@ -1747,7 +1760,9 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 35, 32, 76, 69, 86, 69, 76, 32, 56, 10, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 73, 110, 102, 105, 120, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 73, 110, 102, 105, 120, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 84, 97, 105, 108, 42, 10, - 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 84, 97, 105, 108, 32, 60, 45, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 84, 97, 105, 108, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 83, 117, 98, 113, 117, 101, 114, 121, 84, 97, 105, 108, 32, 47, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 10, + 65, 110, 121, 65, 108, 108, 83, 117, 98, 113, 117, 101, 114, 121, 84, 97, 105, 108, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 80, 97, 114, 115, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 83, 117, 98, 113, 117, 101, 114, 121, 82, 101, 102, 101, 114, 101, 110, 99, 101, 10, + 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 32, 60, 45, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 10, 32, 32, 32, 32, 65, 110, 121, 65, 108, 108, 80, 97, 114, 115, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 47, 32, 78, 97, 109, 101, 100, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 10, 65, 110, 121, 65, 108, 108, 80, 97, 114, 115, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 79, 112, 101, 114, 97, 116, 111, 114, 10, @@ -1857,14 +1872,12 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 32, 32, 32, 32, 77, 105, 108, 108, 105, 115, 101, 99, 111, 110, 100, 75, 101, 121, 119, 111, 114, 100, 32, 47, 32, 77, 105, 99, 114, 111, 115, 101, 99, 111, 110, 100, 75, 101, 121, 119, 111, 114, 100, 32, 47, 32, 87, 101, 101, 107, 75, 101, 121, 119, 111, 114, 100, 32, 47, 32, 81, 117, 97, 114, 116, 101, 114, 75, 101, 121, 119, 111, 114, 100, 32, 47, 32, 68, 101, 99, 97, 100, 101, 75, 101, 121, 119, 111, 114, 100, 32, 47, 10, 32, 32, 32, 32, 67, 101, 110, 116, 117, 114, 121, 75, 101, 121, 119, 111, 114, 100, 32, 47, 32, 77, 105, 108, 108, 101, 110, 110, 105, 117, 109, 75, 101, 121, 119, 111, 114, 100, 10, 35, 32, 69, 118, 101, 114, 121, 32, 115, 116, 97, 116, 101, 109, 101, 110, 116, 32, 97, 98, 111, 117, 116, 32, 101, 120, 116, 101, 114, 110, 97, 108, 32, 114, 101, 115, 111, 117, 114, 99, 101, 115, 44, 32, 115, 111, 32, 116, 104, 101, 32, 116, 111, 112, 45, 108, 101, 118, 101, 108, 32, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 99, 104, 111, 105, 99, 101, 32, 99, 97, 114, 114, 105, 101, 115, 32, 111, 110, 101, 32, 101, 110, 116, 114, 121, 10, - 35, 32, 114, 97, 116, 104, 101, 114, 32, 116, 104, 97, 110, 32, 111, 110, 101, 32, 112, 101, 114, 32, 102, 111, 114, 109, 46, 10, - 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 82, 101, 103, 105, 115, 116, 101, 114, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 68, 101, 115, 116, 114, 111, 121, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 83, 116, 109, 116, 32, 47, 32, 65, 116, 116, 97, 99, 104, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 32, 47, 32, 67, 111, 110, 110, 101, 99, 116, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 10, + 35, 32, 114, 97, 116, 104, 101, 114, 32, 116, 104, 97, 110, 32, 111, 110, 101, 32, 112, 101, 114, 32, 102, 111, 114, 109, 46, 32, 83, 72, 79, 87, 32, 91, 65, 76, 76, 93, 32, 69, 88, 84, 69, 82, 78, 65, 76, 32, 82, 69, 83, 79, 85, 82, 67, 69, 83, 32, 105, 115, 32, 97, 32, 113, 117, 101, 114, 121, 32, 40, 100, 101, 115, 99, 114, 105, 98, 101, 46, 103, 114, 97, 109, 41, 44, 32, 115, 111, 32, 105, 116, 32, 99, 97, 110, 32, 98, 101, 32, 97, 32, 115, 117, 98, 113, 117, 101, 114, 121, 46, 10, + 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 82, 101, 103, 105, 115, 116, 101, 114, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 68, 101, 115, 116, 114, 111, 121, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 65, 116, 116, 97, 99, 104, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 32, 47, 32, 67, 111, 110, 110, 101, 99, 116, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 10, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 67, 82, 69, 65, 84, 69, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 63, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 105, 111, 110, 79, 112, 116, 105, 111, 110, 115, 63, 10, 82, 101, 103, 105, 115, 116, 101, 114, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 82, 69, 71, 73, 83, 84, 69, 82, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 63, 32, 39, 70, 82, 79, 77, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 68, 101, 115, 116, 114, 111, 121, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 68, 69, 83, 84, 82, 79, 89, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 67, 111, 108, 73, 100, 10, - 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 83, 116, 109, 116, 32, 60, 45, 32, 39, 83, 72, 79, 87, 39, 32, 83, 104, 111, 119, 65, 108, 108, 77, 111, 100, 105, 102, 105, 101, 114, 63, 32, 39, 69, 88, 84, 69, 82, 78, 65, 76, 39, 32, 39, 82, 69, 83, 79, 85, 82, 67, 69, 83, 39, 10, - 83, 104, 111, 119, 65, 108, 108, 77, 111, 100, 105, 102, 105, 101, 114, 32, 60, 45, 32, 39, 65, 76, 76, 39, 10, - 35, 32, 83, 121, 110, 116, 97, 120, 32, 111, 110, 108, 121, 58, 32, 116, 104, 101, 32, 107, 101, 121, 119, 111, 114, 100, 32, 112, 97, 105, 114, 32, 101, 118, 101, 114, 121, 32, 115, 105, 110, 103, 117, 108, 97, 114, 32, 102, 111, 114, 109, 32, 114, 101, 112, 101, 97, 116, 115, 46, 32, 84, 104, 101, 32, 112, 108, 117, 114, 97, 108, 32, 105, 110, 32, 83, 72, 79, 87, 32, 99, 97, 110, 110, 111, 116, 32, 115, 104, 97, 114, 101, 32, 105, 116, 46, 10, + 35, 32, 83, 121, 110, 116, 97, 120, 32, 111, 110, 108, 121, 58, 32, 116, 104, 101, 32, 107, 101, 121, 119, 111, 114, 100, 32, 112, 97, 105, 114, 32, 101, 118, 101, 114, 121, 32, 115, 105, 110, 103, 117, 108, 97, 114, 32, 102, 111, 114, 109, 32, 114, 101, 112, 101, 97, 116, 115, 46, 10, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 60, 45, 32, 39, 69, 88, 84, 69, 82, 78, 65, 76, 39, 32, 39, 82, 69, 83, 79, 85, 82, 67, 69, 39, 10, 35, 32, 84, 104, 101, 32, 114, 101, 99, 105, 112, 101, 39, 115, 32, 99, 114, 101, 97, 116, 101, 32, 112, 97, 114, 97, 109, 115, 46, 32, 73, 116, 115, 32, 111, 119, 110, 32, 114, 117, 108, 101, 32, 114, 97, 116, 104, 101, 114, 32, 116, 104, 97, 110, 32, 65, 116, 116, 97, 99, 104, 79, 112, 116, 105, 111, 110, 115, 58, 32, 116, 104, 101, 32, 116, 119, 111, 32, 111, 112, 116, 105, 111, 110, 32, 98, 97, 103, 115, 32, 97, 114, 101, 10, 35, 32, 100, 105, 115, 116, 105, 110, 99, 116, 44, 32, 97, 110, 100, 32, 97, 32, 115, 116, 97, 116, 101, 109, 101, 110, 116, 32, 99, 97, 110, 32, 99, 97, 114, 114, 121, 32, 98, 111, 116, 104, 46, 10, diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp index a15d95b30..ddbc609a8 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp @@ -176,6 +176,8 @@ struct MatchContext { //! Ignore rule-level suggestion suppression, so the suggestions a rule adds depend only on its //! position and the packrat cache stays valid while collecting them bool memoizable_suggestions = false; + //! With memoizable_suggestions: walk labelled rules instead of summarising them by their label alone + bool expand_labels = false; //! With memoizable_suggestions: suggestion walks already done, keyed by matcher and active label std::map, SuggestionType> walked_suggestions; }; 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 1e3a8f289..95f715f2f 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 @@ -435,6 +435,8 @@ enum class PEGRuleId : uint32_t { TargetAlias, DeleteUsingClause, DescribeStatement, + ShowExternalResources, + ShowExternalResourcesType, ShowDeprecatedSelect, DescribeSelect, ShowAllTables, @@ -554,6 +556,11 @@ enum class PEGRuleId : uint32_t { SubqueryNot, SubqueryExists, CaseExpression, + SimpleCaseExpression, + SearchedCaseExpression, + SimpleCaseWhenThen, + SimpleCaseWhenOperand, + SimpleCaseWhenEquals, CaseWhenThen, CaseElse, TypeLiteral, @@ -690,6 +697,8 @@ enum class PEGRuleId : uint32_t { OtherOperatorExpression, InfixOtherOperatorExpression, OtherOperatorTail, + AnyAllSubqueryTail, + OtherOperatorExpressionTail, OtherOperator, AnyAllParsedOperator, NamedOtherOperator, @@ -788,8 +797,6 @@ enum class PEGRuleId : uint32_t { CreateExternalResourceStmt, RegisterExternalResourceStmt, DestroyExternalResourceStmt, - ShowExternalResourcesStmt, - ShowAllModifier, ExternalResourceKeyword, ExternalResourceCreationOptions, AttachToExternalResource, 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 8e3ddf714..758dfc5c9 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 @@ -11,6 +11,9 @@ class ParserTokenizerBehavior : public TokenizerBehavior { void PushToken(idx_t start, idx_t end, TokenType type, bool unterminated = false) override; void OnStatementEnd(idx_t pos) override; void OnLastToken(const Tokenizer &tokenizer, TokenizeState state, string last_word, idx_t last_pos) override; + + //! A zero-length delimited identifier ("" or ``) - a fatal lexical error at parse time + static bool IsEmptyQuotedIdentifier(const string &sql, idx_t start, idx_t end, TokenType type); }; } // namespace duckdb 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 f37d470b5..97dd55f69 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 @@ -154,6 +154,7 @@ DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.SetOperationType" DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.SetScope", SetScope); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.SettingInfo", SettingInfo); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.ShowType", ShowType); +DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.SimpleCaseCheck", SimpleCaseCheck); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.TableAlias", TableAlias); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.TransactionModifierType", TransactionModifierType); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.TriggerEventInfo", TriggerEventInfo); @@ -269,10 +270,86 @@ using transform_process_initialize_t = void (*)(PEGTransformer &transformer, Gen using transform_process_finalize_t = arena_ptr (*)(PEGTransformer &transformer, GeneratedTransformProcess &process); +//! How a generated sequence rule reaches one child of its ListParseResult +enum class TransformChildKind : uint8_t { + //! A child transformed into one slot + REQUIRED, + //! An optional child, transformed into one slot when present + OPTIONAL, + //! A List(...) child; its items are transformed into consecutive slots + LIST, + //! An optional List(...) child + OPTIONAL_LIST, + //! A (...)+ child; its items are transformed into consecutive slots + REPEAT, + //! A (...)* child + OPTIONAL_REPEAT +}; + +//! Marks a TransformChildPath that ends without descending into a nested sequence +constexpr uint8_t TRANSFORM_PATH_END = 255; + +//! The way from a parse result to the child a rule transforms: strip parens, then optionally descend into one child +//! of a nested sequence and strip its parens +struct TransformChildPath { + uint8_t parens; + uint8_t nested_child; + uint8_t nested_parens; +}; + +struct TransformChildPlan { + PEGRuleId rule; + TransformChildKind kind; + //! Index of the child in the rule's ListParseResult + uint8_t parse_child; + //! Result slot, or the first slot of a dynamic child + uint8_t slot; + //! The slot comes after the dynamic child and shifts with its item count + bool after_dynamic; + //! From the list child to the child itself (the OptionalParseResult for optional kinds) + TransformChildPath path; + //! Optional kinds: from the content of the OptionalParseResult to the child + TransformChildPath content_path; +}; + +constexpr uint16_t ParseResultTypeBit(ParseResultType type) { + return static_cast(1U << static_cast(type)); +} + +//! How a generated choice rule decides whether the chosen alternative gets its own transform frame +struct TransformChoiceDispatch { + //! ParseResultType bits that finish the rule without a child frame + uint16_t early_type_mask; + //! ParseResultType bits that finish the rule without a child frame when the alternative has no transform process + uint16_t fallback_type_mask; + //! An unnamed alternative finishes the rule without a child frame + bool early_empty_name; + //! An alternative without a transform process is an error rather than a syntax-only alternative + bool throw_without_process; + //! Alternatives that finish the rule without a child frame when they have no transform process + uint8_t fallback_name_count; + const char *const *fallback_names; +}; + +//! The data that drives the shared generated trampolines, see InitializePlannedTrampoline +struct TransformFramePlan { + //! Sequence rules: the children in the order they are pushed + const TransformChildPlan *children; + uint8_t child_count; + //! Slots reserved before the dynamic child's item count is added + uint8_t fixed_slots; + bool has_dynamic; + //! Slot whose result FinalizePassthroughTrampoline returns unchanged + uint8_t result_slot; + TransformChoiceDispatch choice; +}; + struct TransformFrameOps { const char *name; transform_process_initialize_t initialize; transform_process_finalize_t finalize; + //! Data for the shared trampolines, nullptr for rules with their own trampolines + const TransformFramePlan *plan; }; template @@ -295,6 +372,9 @@ struct TransformInput { return rule ? rule : parse_result.GetRule(); } + //! Unwrap rule-less wrapper nodes (choice, present optional, unnamed single-child group); throws when none is left + TransformInput Unwrap() const; + optional_ptr rule; ParseResult &parse_result; }; @@ -752,3684 +832,1872 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierOrKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAlterOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAlterTableStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterTableStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterSchemaStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterSchemaStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterSchemaOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAlterSchemaOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAlterTableOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAlterTableOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAddConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAddConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAddColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAddColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAddColumnEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAddColumnEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRenameColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRenameColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNestedColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNestedColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIdentifierDotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierDotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRenameAlterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRenameAlterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetPartitionedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetPartitionedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeResetPartitionedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeResetPartitionedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetSortedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetSortedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeResetSortedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeResetSortedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeResetOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeResetOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterColumnEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAlterColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAddOrDropDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAddOrDropDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAddDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAddDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeChangeNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeChangeNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropOrSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropOrSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUsingExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUsingExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterViewStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterViewStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterSequenceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterSequenceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedSequenceNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQualifiedSequenceNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterSequenceOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeAlterSequenceOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRenameAlterSequenceOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRenameAlterSequenceOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetSequenceOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetSequenceOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAlterDatabaseStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAlterDatabaseStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnalyzeStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnalyzeStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnalyzeTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnalyzeTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnalyzeVerboseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnalyzeVerboseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAttachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAttachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDatabasePathTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDatabasePathTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAttachAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAttachAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAttachOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAttachOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCallStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCallStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCheckpointStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCheckpointStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCheckpointForceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCheckpointForceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCommentTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCommentStringLiteralIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCommentStringLiteralIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentOnTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCommentOnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCommentTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentSequenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentSequenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentMacroTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentMacroTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentMacroTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentMacroTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentViewTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentViewTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentDatabaseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentDatabaseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommentColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommentValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCommentValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeStringLiteralValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStringLiteralValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnalyzeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnalyzeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIndexNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIndexNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeConstraintNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeConstraintNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSequenceNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSequenceNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCollationNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCollationNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNumberLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNumberLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeVariationsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTypeVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSimpleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSimpleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCharacterSimpleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCharacterSimpleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedSimpleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQualifiedSimpleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIntervalTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIntervalIntervalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIntervalIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIntervalWithSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeIntervalWithSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIntervalWithRangeSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIntervalWithRangeSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalWithSimpleSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIntervalWithSimpleSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalWithoutSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIntervalWithoutSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalToIntervalAsTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIntervalToIntervalAsTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeYearKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeYearKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMonthKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMonthKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDayKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDayKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeHourKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeHourKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMinuteKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMinuteKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMillisecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMillisecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMicrosecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMicrosecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWeekKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWeekKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuarterKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuarterKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDecadeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDecadeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCenturyKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCenturyKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMillenniumKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMillenniumKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIntervalToIntervalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIntervalToIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeYearToMonthTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeYearToMonthTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDayToHourTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDayToHourTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDayToMinuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDayToMinuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDayToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDayToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeHourToMinuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeHourToMinuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeHourToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeHourToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMinuteToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMinuteToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBitTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBitTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGeometryTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGeometryTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVariantTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVariantTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNumericTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeNumericTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSimpleNumericTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSimpleNumericTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDecimalNumericTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDecimalNumericTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIntTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIntTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntegerTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIntegerTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSmallintTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSmallintTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBigintTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBigintTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRealTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRealTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBooleanTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBooleanTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDoubleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDoubleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFloatTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFloatTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDecimalTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDecimalTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDecTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDecTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNumericModTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNumericModTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedTypeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQualifiedTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTypeNameAsQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTypeNameAsQualifiedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogReservedSchemaTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogReservedSchemaTypeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSchemaReservedTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaReservedTypeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeModifiersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTypeModifiersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNestedTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNestedTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetofTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetofTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnionTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUnionTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColIdTypeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColIdTypeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMapTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMapTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTupleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTupleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColIdTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColIdTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeArrayBoundsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeArrayBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeArrayKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeArrayKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeArrayKeywordWithBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeArrayKeywordWithBoundsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSquareBracketsArrayTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSquareBracketsArrayTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTimeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTimeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTimeOrTimestampTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTimeOrTimestampTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTimeTypeIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTimeTypeIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTimestampTypeIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTimestampTypeIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithOrWithoutTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeWithOrWithoutTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeWithRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithoutRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithoutRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeConnectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeConnectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDisconnectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDisconnectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeLocalSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLocalSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStringSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeStringSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyVariationsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopyTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFromOrToTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFromOrToTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopyFromTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyFromTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyToTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyToTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopySelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopySelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyFileNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyFileNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopyFileNameExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyFileNameExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopyFileNameStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCopyFileNameStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyFileNameIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCopyFileNameIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyFileNameIdentifierColIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCopyFileNameIdentifierColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIdentifierColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyFileNameSuffixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyFileNameSuffixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopyLegacyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyLegacyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSpecializedOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSpecializedOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSpecializedOptionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSpecializedOptionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSpecializedOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSpecializedOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSingleOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSingleOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeBinaryOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBinaryOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFreezeOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFreezeOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOidsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOidsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCsvOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCsvOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeHeaderOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeHeaderOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDelimiterAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDelimiterAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuoteAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuoteAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEscapeAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEscapeAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEncodingOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEncodingOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForceQuoteOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForceQuoteOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStarSymbolColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeStarSymbolColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForceQuoteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForceQuoteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePartitionByOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePartitionByOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizePartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeStarPartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeStarPartitionByColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeParenthesizedPartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeParenthesizedPartitionByColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSinglePartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSinglePartitionByColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForceNullOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForceNullOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForceNotNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForceNotNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyGenericOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCopyGenericOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyGenericOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyGenericOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOrderByCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOrderByCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePartitionedByCopyOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePartitionedByCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGenericCopyOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeGenericCopyOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGenericCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGenericCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGenericCopyOptionValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeGenericCopyOptionValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeGenericCopyOptionOrderListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeGenericCopyOptionOrderListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGenericCopyOptionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeGenericCopyOptionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGenericCopyOptionParenthesizedExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeGenericCopyOptionParenthesizedExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyFromDatabaseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCopyFromDatabaseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopyFromDatabaseWithFlagTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCopyFromDatabaseWithFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyFromDatabaseWithoutFlagTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCopyFromDatabaseWithoutFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyDatabaseFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyDatabaseFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSchemaOrDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSchemaOrDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCopySchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopySchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCopyDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCopyDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateIndexStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateIndexStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRelOptionOrOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeRelOptionOrOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRelOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRelOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithOrWithoutOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeWithOrWithoutOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeWithOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithoutOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithoutOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIndexElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIndexElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUniqueIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUniqueIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIndexTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIndexTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRelOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRelOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRelOptionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRelOptionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDottedColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDottedColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRelOptionArgumentOptTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRelOptionArgumentOptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefArgTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDefArgTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDefArgNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefArgNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefArgKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefArgKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefArgStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDefArgStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNoneLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNoneLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateMacroStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateMacroStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReturnsTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeReturnsTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMacroOrFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeMacroOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMacroKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMacroKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMacroDefinitionBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeMacroDefinitionBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMacroParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMacroParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMacroParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeMacroParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSimpleParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSimpleParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeScalarMacroDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeScalarMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableMacroDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateSchemaStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateSchemaStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateSecretStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateSecretStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSecretStorageSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSecretStorageSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSecretNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSecretNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateSequenceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateSequenceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSequenceOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSequenceOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSeqSetCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSeqSetCycleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSeqCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqNoCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqNoCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqSetIncrementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqSetIncrementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqSetMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqSetMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqNoMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqNoMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqStartWithTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqStartWithTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqOwnedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqOwnedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSeqMinOrMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSeqMinOrMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMinValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMinValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMaxValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMaxValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateStatementVariationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeCreateStatementVariationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOrReplaceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOrReplaceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTemporaryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTemporaryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTempPersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTempPersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTemporaryPersistentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTemporaryPersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTableStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTableStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTableDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeCreateTableDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCreateTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePartitionSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizePartitionSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePartitionOptSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePartitionOptSortedOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSortedOptPartitionOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSortedOptPartitionOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePartitionOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePartitionOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSortedOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSortedOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeWithDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeWithDataOnlyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithDataOnlyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithNoDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithNoDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIdentifierListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIfNotExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIfNotExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSchemaReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogReservedSchemaIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogReservedSchemaIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSchemaQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReservedSchemaQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeReservedSchemaQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReservedTableQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeReservedTableQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTableColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTableColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTableColumnElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeCreateTableColumnElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTableColumnDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTableColumnDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTableConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTableConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNameableColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNameableColumnConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnConstraintElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeColumnConstraintElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotNullConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotNullConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotNullColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNotNullColumnConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUniqueConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUniqueConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePrimaryKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePrimaryKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeConstraintTimingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeConstraintTimingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeImmediateConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeImmediateConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeferredConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeferredConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefaultValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefaultValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCheckConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCheckConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForeignKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeForeignKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnCollationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnCollationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnCompressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnCompressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeKeyActionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeKeyActionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUpdateFirstKeyActionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateFirstKeyActionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeleteFirstKeyActionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDeleteFirstKeyActionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeleteActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeleteActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNoKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNoKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRestrictKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRestrictKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCascadeKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCascadeKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetNullKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetNullKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetDefaultKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSetDefaultKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTopLevelConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTopLevelConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTopLevelConstraintListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeTopLevelConstraintListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTopCheckConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTopCheckConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTopPrimaryKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTopPrimaryKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTopUniqueConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTopUniqueConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTopForeignKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTopForeignKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnIdListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnIdListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDottedIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDottedIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDotColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDotColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColIdOrStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColIdOrStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeFuncNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTypeFuncNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeFuncKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTypeFuncKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColLabelOrStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColLabelOrStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColLabelIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColLabelIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStringLiteralIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeStringLiteralIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGeneratedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeGeneratedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeGeneratedAlwaysTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGeneratedAlwaysTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGeneratedByDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGeneratedByDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGeneratedColumnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeGeneratedColumnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCommitActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommitActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePreserveOrDeleteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizePreserveOrDeleteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePreserveRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePreserveRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeleteRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeleteRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVirtualGeneratedColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeVirtualGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStoredGeneratedColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeStoredGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTriggerStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTriggerStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTriggerBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTriggerNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReferencingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReferencingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReferencingItemTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeReferencingItemTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeReferencingNewTableAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeReferencingNewTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReferencingOldTableAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeReferencingOldTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerTimingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTriggerTimingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTriggerBeforeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerBeforeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerAfterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerAfterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerInsteadOfTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerInsteadOfTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerEventTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTriggerEventTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTriggerEventInsertTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerEventInsertTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerEventDeleteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerEventDeleteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerEventUpdateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerEventUpdateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerEventUpdateOfTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerEventUpdateOfTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTriggerColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTriggerColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForEachClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeForEachClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeForEachRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForEachRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForEachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForEachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTypeStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTypeStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCreateTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCreateTypeFromTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateTypeFromTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEnumSelectTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEnumSelectTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEnumStringLiteralListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeEnumStringLiteralListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateViewStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateViewStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateRecursiveTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateRecursiveTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateSecureTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCreateSecureTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeallocateStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDeallocateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeallocatePrepareTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeallocatePrepareTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeleteStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeleteStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTruncateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTruncateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTruncateOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTruncateOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTruncateAliasOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTruncateAliasOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTruncateDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTruncateDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTargetOptAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTargetOptAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTargetAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTargetAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeleteUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeleteUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowDeprecatedSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); + static arena_ptr FinalizeShowExternalResourcesTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeShowDeprecatedSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowAllTablesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowAllTablesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowTablesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowTablesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeOrSummarizeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeDescribeOrSummarizeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeShowTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowDeprecatedQualifiedTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeShowDeprecatedQualifiedTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowSettingNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowSettingNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDescribeTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDescribeBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeBaseTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSummarizeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSummarizeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSummarizeRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSummarizeRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowOrDescribeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeShowOrDescribeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeShowRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescribeRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDescribeRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDescribeLongRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeLongRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDetachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDetachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropEntriesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDropEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDropTriggerTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropTriggerTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedIndexNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQualifiedIndexNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeQualifiedIndexNameStringTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQualifiedIndexNameStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSchemaReservedIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaReservedIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogReservedSchemaIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogReservedSchemaIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropSequenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropSequenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropCollationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropCollationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropSecretTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropSecretTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableOrViewTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTableOrViewTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMaterializedViewEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMaterializedViewEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionTypeMacroTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFunctionTypeMacroTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeFunctionTypeMacroKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionTypeMacroKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionTypeFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionTypeFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCascadeDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCascadeDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRestrictDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRestrictDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIfExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIfExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropSecretStorageTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDropSecretStorageTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExecuteStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExecuteStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExplainStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExplainStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExplainOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExplainOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExplainOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExplainOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExplainOptionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExplainOptionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExplainSelectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExplainSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExplainableStatementsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeExplainableStatementsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExportStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExportStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExportSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExportSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExportOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeExportOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeImportStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeImportStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnReferenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnReferenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNestedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNestedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogReservedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogReservedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSchemaReservedTableColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaReservedTableColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableReservedColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableReservedColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionExpressionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionExpressionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionExpressionArgumentListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionExpressionArgumentListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionArgumentListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionArgumentListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFunctionIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeFunctionNameAsQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFunctionNameAsQualifiedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogReservedSchemaFunctionNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogReservedSchemaFunctionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSchemaReservedFunctionNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaReservedFunctionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDistinctOrAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDistinctOrAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDistinctKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDistinctKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAllKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAllKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithinGroupClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithinGroupClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFilterClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFilterClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFilterClauseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFilterClauseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFilterClauseContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFilterClauseContentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIgnoreOrRespectNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeIgnoreOrRespectNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIgnoreNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIgnoreNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRespectNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRespectNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeParenthesisExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeParenthesisExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeConstantLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeConstantLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrueLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrueLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFalseLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFalseLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCastExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCastExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCastArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCastArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCastOrTryCastTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCastOrTryCastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCastKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCastKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTryCastKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTryCastKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColIdDotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColIdDotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStarExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStarExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStarQualifierListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStarQualifierListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeNamesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeExcludeNamesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExcludeNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeNameSingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeNameSingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeExcludeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExcludeDottedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeDottedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReplaceListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReplaceListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReplaceEntriesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeReplaceEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeReplaceEntrySingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReplaceEntrySingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReplaceEntryListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReplaceEntryListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReplaceEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReplaceEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRenameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRenameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRenameEntriesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeRenameEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRenameEntryListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRenameEntryListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSingleRenameEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSingleRenameEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRenameEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRenameEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubqueryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubqueryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubqueryNotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubqueryNotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubqueryExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubqueryExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCaseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCaseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCaseWhenThenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeSimpleCaseExpressionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeSearchedCaseExpressionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeSimpleCaseWhenThenTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeSimpleCaseWhenEqualsTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeCaseWhenThenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCaseElseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCaseElseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTypeLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIntervalLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntervalParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIntervalParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIntervalStringParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIntervalStringParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFrameClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFrameClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowsFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowsFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRangeFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRangeFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupsFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupsFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFrameExtentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSingleFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSingleFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBetweenFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBetweenFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFrameBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFrameBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeFrameUnboundedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFrameUnboundedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFrameExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFrameExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFrameCurrentRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFrameCurrentRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePrecedingOrFollowingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizePrecedingOrFollowingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePrecedingFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePrecedingFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFollowingFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFollowingFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowExcludeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeWindowExcludeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowExcludeElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeWindowExcludeElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExcludeCurrentRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeCurrentRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeGroupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeGroupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeTiesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeTiesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeNoOthersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeNoOthersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeWindowFrameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIdentifierWindowFrameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIdentifierWindowFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeParensIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeParensIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowFrameDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeWindowFrameDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeWindowFrameNameContentsParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeWindowFrameNameContentsParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowFrameNameContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeWindowFrameNameContentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowFrameContentsParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeWindowFrameContentsParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowFrameContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeWindowFrameContentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBaseWindowNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBaseWindowNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowPartitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWindowPartitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeListExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeArrayBoundedListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeArrayBoundedListExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeArrayParensSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeArrayParensSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBoundedListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeBoundedListExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStructExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStructExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStructFieldTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStructFieldTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMapExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMapExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMapStructExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMapStructExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMapStructFieldTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMapStructFieldTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupingExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupingExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupingOrGroupingIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeGroupingOrGroupingIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeGroupingKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupingKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupingIdKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupingIdKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeQuestionMarkNumberedParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQuestionMarkNumberedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnonymousParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnonymousParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNumberedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNumberedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColLabelParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColLabelParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePositionalExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePositionalExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefaultExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefaultExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeListComprehensionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeListComprehensionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeListComprehensionFilterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeListComprehensionFilterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeParensExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeParensExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMeasureSemanticsExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMeasureSemanticsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSingleExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSingleExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeColumnDefaultExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnDefaultExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSingleArrowPairTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSingleArrowPairTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLogicalOrExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalOrExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLogicalOrExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalOrExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColDefOrExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColDefOrExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColDefOrExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeColDefOrExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLogicalAndExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalAndExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLogicalAndExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalAndExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColDefAndExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColDefAndExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColDefAndExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeColDefAndExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLogicalNotExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalNotExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsExpressionContinuationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIsExpressionContinuationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIsExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIsTestTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsTestTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsDistinctTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsDistinctTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsComparisonTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsComparisonTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsOtherOperatorTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIsOtherOperatorTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsCastTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsCastTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsTestTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIsTestTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIsLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsLiteralValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIsLiteralValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUnknownLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUnknownLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeNotNullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNotNullKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotNullKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotNullOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotNullOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsNullOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsNullOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsDistinctFromExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeIsDistinctFromExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsDistinctFromTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsDistinctFromTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIsDistinctFromOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIsDistinctFromOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeComparisonExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeComparisonExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeComparisonExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeComparisonExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeComparisonOperandTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeComparisonOperandTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNotComparisonOperandTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNotComparisonOperandTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeComparisonOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeComparisonOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOperatorEqualTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorEqualTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOperatorNotEqualTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorNotEqualTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOperatorLessThanTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorLessThanTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOperatorGreaterThanTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorGreaterThanTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOperatorLessThanEqualsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorLessThanEqualsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOperatorGreaterThanEqualsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorGreaterThanEqualsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBetweenInLikeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeBetweenInLikeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInPredicateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInPredicateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBetweenLikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBetweenLikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBetweenLikeOpExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeBetweenLikeOpExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLikeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLikeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEscapeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEscapeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLikeVariationsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLikeVariationsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLikeTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLikeTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeILikeTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeILikeTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGlobTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGlobTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSimilarToTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSimilarToTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRegexMatchTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRegexMatchTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRegexInsensitiveMatchTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRegexInsensitiveMatchTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotILikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotILikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotLikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotLikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotRegexInsensitiveMatchOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNotRegexInsensitiveMatchOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotSimilarToOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotSimilarToOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeInExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeInContainsExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeInContainsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBetweenClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBetweenClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOtherOperatorExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeOtherOperatorExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInfixOtherOperatorExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeInfixOtherOperatorExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOtherOperatorTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOtherOperatorTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOtherOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAnyAllParsedOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); + static arena_ptr FinalizeAnyAllSubqueryTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr + FinalizeOtherOperatorExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnyAllParsedOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNamedOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNamedOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOperatorLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOperatorLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnyOperatorLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnyOperatorLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnyAllOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAnyAllOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAnyOrAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAnyOrAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSubqueryAnyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubqueryAnyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubqueryAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubqueryAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQualifiedOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedOperatorContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQualifiedOperatorContentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBitwiseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBitwiseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBitwiseExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeBitwiseExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBitOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBitOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTildeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTildeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAdditiveExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAdditiveExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAdditiveExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeAdditiveExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMultiplicativeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMultiplicativeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMultiplicativeExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMultiplicativeExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFactorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFactorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExponentiationExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExponentiationExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExponentiationExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExponentiationExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExponentOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExponentOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCollateExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCollateExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCollateExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCollateExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAtTimeZoneExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeAtTimeZoneExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAtTimeZoneExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeAtTimeZoneExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnaryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeUnaryExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCustomPrefixExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCustomPrefixExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMinusPrefixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMinusPrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePlusPrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePlusPrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTildePrefixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTildePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBaseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBaseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIndirectionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIndirectionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIndirectionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeIndirectionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCastOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCastOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDotOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDotOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDotMethodOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDotMethodOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDotColumnOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDotColumnOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMethodExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMethodExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMethodExpressionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMethodExpressionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMethodExpressionArgumentListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMethodExpressionArgumentListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMethodFunctionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMethodFunctionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSliceExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSliceExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSliceUpperBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSliceUpperBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMinusStepSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMinusStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEndStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEndStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEndSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEndSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePostfixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePostfixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSpecialFunctionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeSpecialFunctionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCoalesceExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCoalesceExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnpackExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUnpackExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtractExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExtractExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtractArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExtractArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLambdaExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLambdaExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullIfExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullIfExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullIfArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullIfArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePositionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePositionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePositionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePositionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubstringExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSubstringExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubstringArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSubstringArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSubstringExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSubstringExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubstringParametersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSubstringParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubstringFromForTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSubstringFromForTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSubstringFromOptionalForTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSubstringFromOptionalForTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubstringForTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubstringForTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimDirectionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimDirectionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimBothTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimBothTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimLeadingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimLeadingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimTrailingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimTrailingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTrimSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTrimSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOverlayExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOverlayExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOverlayArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOverlayArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOverlayParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOverlayParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFromExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFromExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeForExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeForExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOverlayExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOverlayExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtractArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeExtractArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExtractDatePartArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExtractDatePartArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtractIdentifierArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExtractIdentifierArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtractStringArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExtractStringArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtractDatePartTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeExtractDatePartTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExternalResourceStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeExternalResourceStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateExternalResourceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCreateExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRegisterExternalResourceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRegisterExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDestroyExternalResourceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDestroyExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowExternalResourcesStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeShowExternalResourcesStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeShowAllModifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeShowAllModifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExternalResourceCreationOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeExternalResourceCreationOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAttachToExternalResourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeAttachToExternalResourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeConnectToExternalResourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeConnectToExternalResourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExternalResourceSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeExternalResourceSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeExternalResourceCreateClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExternalResourceCreateClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExternalResourceReferenceClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExternalResourceReferenceClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOrActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOrActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeInsertOrReplaceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertOrReplaceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertOrIgnoreTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertOrIgnoreTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeByNameOrPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeInsertByNameOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeInsertByNameOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeInsertByPositionOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeInsertByPositionOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeInsertByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertByPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertByPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeInsertValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSelectInsertValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectInsertValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefaultValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefaultValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOnConflictClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOnConflictClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOnConflictTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOnConflictTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOnConflictExpressionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOnConflictExpressionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOnConflictIndexTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOnConflictIndexTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOnConflictActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOnConflictActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOnConflictUpdateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOnConflictUpdateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOnConflictNothingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOnConflictNothingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReturningClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReturningClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLoadStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLoadStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtensionAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExtensionAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInstallStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInstallStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInstallAndLoadTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInstallAndLoadTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateExtensionsStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateExtensionsStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFromSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFromSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeFromSourceIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFromSourceIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFromSourceStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFromSourceStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVersionNumberTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVersionNumberTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExtensionRepositoryStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeExtensionRepositoryStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCreateExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCreateExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRepositoryPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRepositoryPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRepositoryPublicKeyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRepositoryPublicKeyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDropExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDropExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableMatchRecognizeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableMatchRecognizeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMatchRecognizeBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMatchRecognizeBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMatchRecognizeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeMatchRecognizeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMRPartitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRPartitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMROrderByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMROrderByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRMeasuresTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRMeasuresTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRSkipTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRSkipTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRPatternTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRPatternTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRSubsetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRSubsetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRDefineAutoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRDefineAutoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMRDefineTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMRDefineTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMeasuresClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMeasuresClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMeasuresElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMeasuresElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMeasureSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeMeasureSemanticsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRunningSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRunningSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFinalSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFinalSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowsPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeRowsPerMatchTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOneRowPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOneRowPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAllRowsPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAllRowsPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAllRowsEmptyMatchesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeAllRowsEmptyMatchesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeShowEmptyMatchesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowEmptyMatchesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOmitEmptyMatchesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOmitEmptyMatchesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithUnmatchedRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithUnmatchedRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAfterMatchSkipTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAfterMatchSkipTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeAfterMatchSkipTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeAfterMatchSkipTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSkipToNextRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSkipToNextRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSkipPastLastRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSkipPastLastRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSkipToFirstVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSkipToFirstVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSkipToLastVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSkipToLastVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSkipToVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSkipToVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePatternClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizePatternClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRowPatternTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternAlternativeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeRowPatternAlternativeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRowPatternTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternFactorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternFactorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternPrimaryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeRowPatternPrimaryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRowPatternPermuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternPermuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternAnchorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeRowPatternAnchorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePatternStartTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePatternStartTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePatternEndTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePatternEndTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternGroupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeRowPatternGroupTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeRowPatternEmptyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternEmptyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternExclusionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternExclusionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternQuantifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRowPatternQuantifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRowPatternQuantifierKindTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeRowPatternQuantifierKindTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierReluctantTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierReluctantTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierStarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierStarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierPlusTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierPlusTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierOptionalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierOptionalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierRangeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQuantifierRangeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeQuantifierBoundsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQuantifierBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeQuantifierMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierMinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierMinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQuantifierExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQuantifierExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubsetElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubsetElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefineClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefineClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDefineElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDefineElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMergeIntoStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMergeIntoStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMergeIntoUsingClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeMergeIntoUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMergeMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeMergeMatchTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeMatchedClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMatchedClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMatchedClauseActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeMatchedClauseActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUpdateMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateMatchInfoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeUpdateMatchInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUpdateMatchSetActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateMatchSetActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateByNameOrPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDeleteMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDeleteMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertMatchInfoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeInsertMatchInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeInsertDefaultValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeInsertDefaultValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeInsertByNameOrPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInsertValuesListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInsertValuesListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDoNothingMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeDoNothingMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeErrorMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeErrorMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateMatchSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeUpdateMatchSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUpdateMatchSetInfoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateMatchSetInfoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAndExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAndExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNotMatchedClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNotMatchedClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBySourceOrTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeBySourceOrTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeBySourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBySourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeByTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeByTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotOnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotOnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotUsingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotUsingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotColumnEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizePivotColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePivotColumnExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePivotColumnExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotColumnSubqueryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePivotColumnSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntoNameValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIntoNameValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOptionalParensNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeOptionalParensNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeParenthesizedNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeParenthesizedNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBareNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBareNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIncludeOrExcludeNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeIncludeOrExcludeNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeIncludeNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIncludeNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExcludeNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeExcludeNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnpivotHeaderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeUnpivotHeaderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUnpivotHeaderSingleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUnpivotHeaderSingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnpivotHeaderListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUnpivotHeaderListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePragmaStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePragmaStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePragmaAssignOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizePragmaAssignOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePragmaAssignTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePragmaAssignTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePragmaFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePragmaFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePragmaParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePragmaParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePrepareStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePrepareStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTypeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTypeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectSetOpChainTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectSetOpChainTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectSetOpChainTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSelectSetOpChainTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntersectChainTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIntersectChainTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeIntersectChainTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeIntersectChainTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetIntersectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetIntersectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectAtomTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSelectAtomTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSelectParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetopClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetopClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetopTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSetopTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSetopUnionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetopUnionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetopExceptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetopExceptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectStatementTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeSelectStatementTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeResultModifiersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeResultModifiersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLimitOffsetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeLimitOffsetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeLimitOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLimitOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOffsetLimitClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOffsetLimitClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOffsetFetchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOffsetFetchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFetchOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFetchOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFetchOnlyClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFetchOnlyClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOptionalParensSimpleSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeOptionalParensSimpleSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSimpleSelectParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSimpleSelectParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectFromTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSelectFromTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSelectFromClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectFromClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFromSelectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFromSelectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCTEBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeCTEBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCTESelectBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCTESelectBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCTEDMLBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCTEDMLBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUsingKeyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUsingKeyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeMaterializedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMaterializedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeColumnAliasesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnAliasesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDistinctClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDistinctClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDistinctAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDistinctAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDistinctOnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDistinctOnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDistinctOnTargetsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDistinctOnTargetsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInnerTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeInnerTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTableSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBaseTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBaseTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableAliasColonTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableAliasColonTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeValuesRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeValuesRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeJoinOrPivotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeJoinOrPivotTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTablePivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTablePivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTablePivotClauseBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTablePivotClauseBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotGroupByListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotGroupByListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableUnpivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableUnpivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableUnpivotClauseBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableUnpivotClauseBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotHeaderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotHeaderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotValueListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotValueListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotValueTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizePivotValueTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializePivotEnumTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotEnumTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotListTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotListTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnpivotValueListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUnpivotValueListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePivotTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePivotTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUnpivotTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUnpivotTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLateralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLateralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBaseTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUnqualifiedBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUnqualifiedBaseTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQualifiedTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSchemaReservedTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaReservedTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogReservedSchemaTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogReservedSchemaTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTableFunctionLateralOptTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableFunctionLateralOptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableFunctionAliasColonTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableFunctionAliasColonTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWithOrdinalityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithOrdinalityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifiedTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeQualifiedTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableFunctionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableFunctionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFunctionArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNamedFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNamedFunctionArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePositionalFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePositionalFunctionArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNamedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNamedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTableAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeTableAliasAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableAliasAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTableAliasWithoutAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeTableAliasWithoutAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAtClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAtClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAtSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAtSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVersionAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVersionAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTimestampAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTimestampAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeJoinClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeJoinClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNearestJoinClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeNearestJoinClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNearestJoinAliasedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestJoinAliasedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestJoinBareTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestJoinBareTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestBareTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeNearestBareTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNearestValuesRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestValuesRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNearestTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestTableSubqueryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNearestTableSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestBaseTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNearestBaseTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestParensTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeNearestParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeApproxOrExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeApproxOrExactTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNearestApproxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestApproxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDistanceOrSimilarityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeDistanceOrSimilarityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNearestDistanceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestDistanceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNearestSimilarityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNearestSimilarityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRegularJoinClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRegularJoinClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeJoinByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeJoinByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAsofTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAsofTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeJoinWithoutOnClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeJoinWithoutOnClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeJoinQualifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeJoinQualifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOnClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOnClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUsingColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUsingColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeJoinTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeJoinTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeJoinPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeCrossJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCrossJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNaturalJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNaturalJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializePositionalJoinPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizePositionalJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFullJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFullJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLeftJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLeftJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRightJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRightJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSemiJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSemiJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAntiJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAntiJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeInnerJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeInnerJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFromClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFromClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWhereClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWhereClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeHavingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeHavingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeQualifyClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeQualifyClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSampleClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSelectSampleClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSelectSampleClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeWindowClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWindowClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSampleEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSampleEntryCountTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSampleEntryCountTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleEntryFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSampleEntryFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSampleFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSamplePropertiesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSamplePropertiesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRepeatableSampleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRepeatableSampleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleSeedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSampleSeedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleCountTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSampleCountTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSampleValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSampleUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSampleUnitTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSamplePercentageTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSamplePercentageTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSampleRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSampleRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupByExpressionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeGroupByExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeGroupByAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupByAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupByListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupByListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupByExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeGroupByExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeGroupByBaseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeGroupByBaseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeEmptyGroupingItemTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeEmptyGroupingItemTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCubeOrRollupClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCubeOrRollupClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCubeOrRollupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCubeOrRollupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCubeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCubeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRollupKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeRollupKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGroupingSetsClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGroupingSetsClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSubqueryReferenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSubqueryReferenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOrderByExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOrderByExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDescOrAscTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeDescOrAscTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeDescendingOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescendingOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAscendingOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeAscendingOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullsFirstOrLastTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeNullsFirstOrLastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeNullsFirstTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullsFirstTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNullsLastTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNullsLastTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOrderByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOrderByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOrderByExpressionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeOrderByExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeOrderByExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeOrderByExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOrderByAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOrderByAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLimitClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLimitClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOffsetValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOffsetValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLimitValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeLimitValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeLimitAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLimitAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLimitLiteralPercentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLimitLiteralPercentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLimitExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLimitExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFetchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeFetchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeFetchClauseWithoutValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeFetchClauseWithoutValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeFetchClauseWithValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeFetchClauseWithValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeFetchValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeFetchValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeAliasedExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeAliasedExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeColIdExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColIdExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExpressionAsCollabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExpressionAsCollabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeExpressionOptIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeExpressionOptIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeValuesClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeValuesClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeValuesExpressionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeValuesExpressionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSetStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSetKeywordStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSetKeywordStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVariableAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVariableAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetAssignmentOrTimeZoneTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr - FinalizeSetAssignmentOrTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeResetStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeResetStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeResetTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeResetTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeResetTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeResetTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeResetVariableOrSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeResetVariableOrSettingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeStandardAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeStandardAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetVariableOrSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeSetVariableOrSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSetTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeZoneValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeZoneValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeZoneLocalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeZoneLocalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeZoneDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeZoneDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeZoneStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeZoneStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeZoneIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeZoneIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeZoneIntervalWithIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeZoneIntervalWithIntervalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeZoneIntervalWithPrecisionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeZoneIntervalWithPrecisionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetSettingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetSettingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetVariableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetVariableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVariableScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVariableScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSettingScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSettingScopeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeLocalScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLocalScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSessionScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSessionScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeGlobalScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeGlobalScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeSetAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeSetAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVariableListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVariableListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeTransactionStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeTransactionStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeBeginTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBeginTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeRollbackTransactionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeRollbackTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCommitTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCommitTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReadOrWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReadOrWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReadOnlyOrReadWriteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeReadOnlyOrReadWriteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeReadOnlyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReadOnlyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeReadWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReadWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeUpdateTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeBaseTableSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBaseTableSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeBaseTableAliasSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeBaseTableAliasSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateSetClauseListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateSetClauseListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateSetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeUpdateSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeUpdateSetTupleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateSetTupleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateSetElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateSetElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUpdateSetColumnTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUpdateSetColumnTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUseStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeUseStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUseTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSchemaNameAsUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeSchemaNameAsUseTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeCatalogNameAsUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeCatalogNameAsUseTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeUseTargetCatalogSchemaTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeUseTargetCatalogSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeDotIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDotIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVacuumStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVacuumStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVacuumOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeVacuumOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeVacuumParensOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeVacuumParensOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVacuumLegacyOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeVacuumLegacyOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeVacuumOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeVacuumOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOptAnalyzeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOptAnalyzeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOptFullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOptFullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOptFreezeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOptFreezeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeOptVerboseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOptVerboseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static unique_ptr TransformAlterStatement(PEGTransformer &transformer, @@ -5047,6 +3315,9 @@ class PEGTransformerFactory { vector> table_ref); static unique_ptr TransformDescribeStatement(PEGTransformer &transformer, unique_ptr child); + static unique_ptr TransformShowExternalResources(PEGTransformer &transformer, const ShowType &show_rule, + const bool &has_result, + optional show_external_resources_type); static unique_ptr TransformShowDeprecatedSelect(PEGTransformer &transformer, const ShowType &show_rule, unique_ptr select_statement_internal); static unique_ptr TransformDescribeSelect(PEGTransformer &transformer, @@ -5255,10 +3526,18 @@ class PEGTransformerFactory { unique_ptr subquery_reference); static bool TransformSubqueryNot(PEGTransformer &transformer); static bool TransformSubqueryExists(PEGTransformer &transformer); - static unique_ptr TransformCaseExpression(PEGTransformer &transformer, - optional> expression, - vector case_when_then, - optional> case_else); + static unique_ptr TransformSimpleCaseExpression(PEGTransformer &transformer, + unique_ptr expression, + vector simple_case_when_then, + optional> case_else); + static unique_ptr + TransformSearchedCaseExpression(PEGTransformer &transformer, vector case_when_then, + optional> case_else); + static SimpleCaseCheck TransformSimpleCaseWhenThen(PEGTransformer &transformer, + vector simple_case_when_operand, + unique_ptr expression); + static ComparisonExpressionTail TransformSimpleCaseWhenEquals(PEGTransformer &transformer, + unique_ptr expression); static CaseCheck TransformCaseWhenThen(PEGTransformer &transformer, unique_ptr expression, unique_ptr expression_1); static unique_ptr TransformCaseElse(PEGTransformer &transformer, @@ -5477,8 +3756,12 @@ class PEGTransformerFactory { static unique_ptr TransformInfixOtherOperatorExpression(PEGTransformer &transformer, unique_ptr bitwise_expression, optional> other_operator_tail); - static OtherOperatorTail TransformOtherOperatorTail(PEGTransformer &transformer, ParsedOperator other_operator, - unique_ptr bitwise_expression); + static OtherOperatorTail TransformAnyAllSubqueryTail(PEGTransformer &transformer, + ParsedOperator any_all_parsed_operator, + unique_ptr subquery_reference); + static OtherOperatorTail TransformOtherOperatorExpressionTail(PEGTransformer &transformer, + ParsedOperator other_operator, + unique_ptr bitwise_expression); static ParsedOperator TransformAnyAllParsedOperator(PEGTransformer &transformer, const pair &any_all_operator); static ParsedOperator TransformNamedOtherOperator(PEGTransformer &transformer, const string &child); @@ -5644,9 +3927,6 @@ class PEGTransformerFactory { unique_ptr expression); static unique_ptr TransformDestroyExternalResourceStmt(PEGTransformer &transformer, const Identifier &col_id); - static unique_ptr TransformShowExternalResourcesStmt(PEGTransformer &transformer, - const optional &show_all_modifier); - static bool TransformShowAllModifier(PEGTransformer &transformer); static unique_ptr TransformAttachToExternalResource( PEGTransformer &transformer, unique_ptr external_resource_source, const Identifier &attach_alias, const optional> &attach_options); @@ -6284,6 +4564,12 @@ class PEGTransformerFactory { static const case_insensitive_map_t &GeneratedTransformFrameOps(); + //! Shared trampolines for generated rules, driven by TransformFrameOps::plan + static void InitializePlannedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static void InitializePlannedChoiceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizePassthroughTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static string ExtractFormat(const string &file_path); static string TransformIdentifierOrKeyword(PEGTransformer &transformer, ParseResult &parse_result); diff --git a/src/duckdb/src/include/duckdb/parser/statement/external_resource_statement.hpp b/src/duckdb/src/include/duckdb/parser/statement/external_resource_statement.hpp index c90b90ac8..2b5c62070 100644 --- a/src/duckdb/src/include/duckdb/parser/statement/external_resource_statement.hpp +++ b/src/duckdb/src/include/duckdb/parser/statement/external_resource_statement.hpp @@ -18,7 +18,7 @@ namespace duckdb { //! The durable external-resource verbs. CREATE provisions and registers a resource under a local name; //! REGISTER registers an already-provisioned resource from a handle value; DESTROY tears one down and //! deregisters it; SHOW lists the registered resources. -enum class ExternalResourceOperation : uint8_t { CREATE, REGISTER, DESTROY, SHOW }; +enum class ExternalResourceOperation : uint8_t { CREATE, REGISTER, DESTROY }; class ExternalResourceStatement : public SQLStatement { public: @@ -36,8 +36,6 @@ class ExternalResourceStatement : public SQLStatement { case_insensitive_map_t> options; //! The `FROM ` handle expression. Set for REGISTER. unique_ptr handle; - //! Whether `SHOW ALL` was used (include discovered resources, not just locally registered). - bool all = false; protected: ExternalResourceStatement(const ExternalResourceStatement &other); diff --git a/src/duckdb/src/include/duckdb/planner/binder.hpp b/src/duckdb/src/include/duckdb/planner/binder.hpp index 30d16328b..00b716e5c 100644 --- a/src/duckdb/src/include/duckdb/planner/binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/binder.hpp @@ -61,6 +61,7 @@ class LogicalVacuum; class ColumnList; class ExternalDependency; +class FunctionArgument; class FunctionSignature; class TableFunction; class BoundTableFunction; @@ -217,6 +218,8 @@ struct GlobalBinderState { vector> using_column_sets; //! The set of parameter expressions bound by this binder optional_ptr parameters; + //! The parameters declared by the statement text, as found by the parser + identifier_map_t statement_parameters; //! Tables whose triggers have already been expanded in this query (recursion detection) reference_set_t trigger_expanded_tables; //! Generated base-UPDATE nodes that must capture the pre-update (OLD) row image (the capture request), @@ -417,6 +420,9 @@ class Binder : public enable_shared_from_this { } optional_ptr GetParameters(); void SetParameters(BoundParameterMap ¶meters); + void SetStatementParameters(const identifier_map_t &statement_parameters); + //! Whether the statement text declares a parameter with this identifier + bool StatementHasParameter(const Identifier &identifier) const; //! Returns a ColumnRefExpression after it was resolved (i.e. past the STAR expression/USING clauses) static optional_ptr GetResolvedColumnExpression(ParsedExpression &root_expr); @@ -425,6 +431,9 @@ class Binder : public enable_shared_from_this { void SetAlwaysRequireRebind(); void SetInsideSubquery(); bool IsInsideSubquery() const; + //! Set while binding the key expressions of an index + void SetBindingIndexKey(bool binding_index_key); + bool IsBindingIndexKey() const; void SetBindingTrySubquery(); bool IsBindingTrySubquery() const; const TrySubqueryPlanIndexes &GetTrySubqueryPlanIndexes() const; @@ -461,6 +470,8 @@ class Binder : public enable_shared_from_this { bool legacy_can_contain_nulls = false; //! Whether this binder is inside a subquery boundary bool inside_subquery = false; + //! Whether the key expressions of an index are being bound + bool binding_index_key = false; //! Whether this binder binds a TRY subquery, which lowers TRY onto the bound plan after binding bool binding_try_subquery = false; //! The plan indexes of the TRY subquery's top select node, recorded while planning it @@ -630,8 +641,7 @@ class Binder : public enable_shared_from_this { unique_ptr BindAtClause(optional_ptr at_clause); - bool BindTableFunctionParameters(TableFunctionCatalogEntry &table_function, - vector> &expressions, + bool BindTableFunctionParameters(TableFunctionCatalogEntry &table_function, vector &arguments, vector> &positional_arguments, vector>> &named_arguments, BoundStatement &subquery, bool &table_in_out, ErrorData &error); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp index 96f1d34b3..95c9e1e3b 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp @@ -32,13 +32,17 @@ struct BoundBetweenExpression { static unique_ptr &LowerBoundMutable(BoundFunctionExpression &between_expr); static unique_ptr &UpperBoundMutable(BoundFunctionExpression &between_expr); + static ExpressionType LowerComparisonType(bool lower_inclusive) { + return lower_inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; + } + static ExpressionType UpperComparisonType(bool upper_inclusive) { + return upper_inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN; + } static ExpressionType LowerComparisonType(const BoundFunctionExpression &between_expr) { - return LowerInclusive(between_expr) ? ExpressionType::COMPARE_GREATERTHANOREQUALTO - : ExpressionType::COMPARE_GREATERTHAN; + return LowerComparisonType(LowerInclusive(between_expr)); } static ExpressionType UpperComparisonType(const BoundFunctionExpression &between_expr) { - return UpperInclusive(between_expr) ? ExpressionType::COMPARE_LESSTHANOREQUALTO - : ExpressionType::COMPARE_LESSTHAN; + return UpperComparisonType(UpperInclusive(between_expr)); } }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/extension_callback.hpp b/src/duckdb/src/include/duckdb/planner/extension_callback.hpp index d457019bf..6ae91a567 100644 --- a/src/duckdb/src/include/duckdb/planner/extension_callback.hpp +++ b/src/duckdb/src/include/duckdb/planner/extension_callback.hpp @@ -37,6 +37,11 @@ class ExtensionCallback { //! Called after an extension fails to load loading virtual void OnExtensionLoadFail(DatabaseInstance &db, const string &name, const ErrorData &error) { } + //! Called after removal from the connection manager, without holding its lock. + //! Destruction waits for this callback. The context and database are still alive. + //! Must not throw. Calls for different connections can overlap. + virtual void OnConnectionUnregistered(ClientContext &context) { + } static void Register(DBConfig &config, shared_ptr extension); static ExtensionCallbackIteratorHelper> Iterate(ClientContext &context) { diff --git a/src/duckdb/src/include/duckdb/planner/sql_export/logical_plan_sql_exporter_internal.hpp b/src/duckdb/src/include/duckdb/planner/sql_export/logical_plan_sql_exporter_internal.hpp index 2549d14a4..84b6f061b 100644 --- a/src/duckdb/src/include/duckdb/planner/sql_export/logical_plan_sql_exporter_internal.hpp +++ b/src/duckdb/src/include/duckdb/planner/sql_export/logical_plan_sql_exporter_internal.hpp @@ -143,18 +143,5 @@ struct SQLExportDMLHelpers { const LogicalPlanVerificationPath &path); //! Whether this exported query is a data-modifying statement node. static bool IsDMLNode(const QueryNode &query); - //! The row-id column that keys an exported data-modifying statement, with its position among the - //! row-id columns the binder appends to the bound source. - struct SelectedRowId { - //! The selected column, pointing into the given map, or null when no key exists - optional_ptr column; - //! Index of the selected column within the row-id set - idx_t ordinal = 0; - //! Number of row-id columns the binder appends to the source - idx_t count = 0; - }; - //! Selects the single row-id column, or the logical row identifier among several. - static SelectedRowId SelectRowIdColumn(const vector &row_id_columns, - const virtual_column_map_t &virtual_columns); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp b/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp index aaa865c3b..8e74f37ea 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp @@ -21,6 +21,7 @@ namespace duckdb { class LogicalAggregate; class LogicalComparisonJoin; class LogicalCTERef; +class LogicalDependentJoin; class LogicalExpressionGet; class LogicalJoin; @@ -115,6 +116,7 @@ class FlattenDependentJoins { vector state, bool rewrite_parent = true, idx_t child_idx = 0); UnnestingState FinalizeDependentJoin(unique_ptr &plan, UnnestingState outer_state, const UnnestingState &right_state, DependentJoinOutput output); + void MaterializeCorrelatedAggregateRewrites(LogicalDependentJoin &op, UnnestingState &outer_state); UnnestingState AttachDelimToIndependentJoinLeft(unique_ptr &plan); UnnestingState PushDownSingleCorrelatedChild(unique_ptr &plan, bool propagate_null_values, vector state, bool correlated_left); diff --git a/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp b/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp index 97e108a6e..f87512451 100644 --- a/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp @@ -118,13 +118,24 @@ class DynamicTableFilterSet { void ClearFilters(const PhysicalOperator &op); void PushFilter(const PhysicalOperator &op, ProjectionIndex column_index, unique_ptr filter); + vector> AddDisjunction(ProjectionIndex column, idx_t alternative_count); + vector> GetDisjunctionFilters() const; + bool HasFilters() const; unique_ptr GetFinalTableFilters(const PhysicalTableScan &scan, optional_ptr existing_filters) const; private: + unique_ptr CopyColumnFilter(ProjectionIndex column) const; + + struct FilterDisjunction { + ProjectionIndex column; + vector> alternatives; + }; + mutable mutex lock; reference_map_t> filters; + vector disjunctions; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp b/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp index 80bea9939..4981f3a47 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/checkpoint/pending_publication.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint/pending_publication.hpp new file mode 100644 index 000000000..f0b04ce84 --- /dev/null +++ b/src/duckdb/src/include/duckdb/storage/checkpoint/pending_publication.hpp @@ -0,0 +1,21 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/storage/checkpoint/pending_publication.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +namespace duckdb { + +class PendingPublication { +public: + virtual ~PendingPublication() = default; + + //! Publish prepared state after its backing blocks have been flushed. + virtual void Publish() = 0; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint/table_data_writer.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint/table_data_writer.hpp index c7c8ac85b..357781609 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint/table_data_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint/table_data_writer.hpp @@ -20,6 +20,7 @@ class DuckTableEntry; class TableStatistics; class SingleFileCheckpointWriter; class RowGroupCollection; +class PendingPublication; struct RowGroupPointer; //! The table data writer is responsible for writing the data of a table to storage. @@ -30,7 +31,7 @@ struct RowGroupPointer; //! Abstraction will support, for example: tiering, versioning, or splitting into multiple block managers. class TableDataWriter { public: - explicit TableDataWriter(TableCatalogEntry &table, QueryContext context); + explicit TableDataWriter(TableCatalogEntry &table, Context &context); virtual ~TableDataWriter(); public: @@ -43,11 +44,17 @@ class TableDataWriter { const vector> &index_infos, Serializer &serializer) = 0; - virtual unique_ptr GetRowGroupWriter(RowGroup &row_group) = 0; + virtual unique_ptr GetRowGroupWriter() = 0; virtual unique_ptr GetTableIndexWriter(StorageVersion version) = 0; virtual void AddRowGroup(RowGroupPointer &&row_group_pointer, unique_ptr writer); virtual CheckpointOptions GetCheckpointOptions() const = 0; + //! Whether publication can be deferred, evaluated after the collection's rebuild requirements are known. + virtual bool CanDeferPublication() const { + return false; + } + //! Transfer prepared state to the enclosing checkpoint; only valid when publication can be deferred. + virtual void AddPendingPublication(unique_ptr publication); virtual void FlushPartialBlocks() = 0; virtual MetadataManager &GetMetadataManager() = 0; //! Whether this is a SingleFileTableDataWriter @@ -82,11 +89,11 @@ class TableDataWriter { AttachedDatabase &GetAttached(); DatabaseInstance &GetDatabase(); unique_ptr CreateTaskExecutor(); - optional_ptr TryGetClientContext() const; + Context &GetContext() const; protected: DuckTableEntry &table; - optional_ptr context; + Context &context; //! Pointers to the start of each row group. vector row_group_pointers; @@ -108,10 +115,12 @@ class SingleFileTableDataWriter : public TableDataWriter { void FinalizeTable(const TableStatistics &global_stats, DataTableInfo &info, RowGroupCollection &collection, const vector> &index_infos, Serializer &serializer) override; - unique_ptr GetRowGroupWriter(RowGroup &row_group) override; + unique_ptr GetRowGroupWriter() override; unique_ptr GetTableIndexWriter(StorageVersion version) override; CheckpointOptions GetCheckpointOptions() const override; + bool CanDeferPublication() const override; + void AddPendingPublication(unique_ptr publication) override; void FlushPartialBlocks() override; MetadataManager &GetMetadataManager() override; bool IsSingleFileWriter() const override { diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp index 6faa1a573..4fc89c101 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp @@ -14,6 +14,7 @@ namespace duckdb { class PartialBlockManager; +class PendingPublication; class SingleFileCheckpointWriter; class BoundIndex; @@ -38,8 +39,8 @@ class TableIndexWriter { } //! Segments managed by this block manager will be packer on a per-index basis. virtual PartialBlockManager CreatePerIndexPartialBlockManager() = 0; - //! Writes the index buffers to disk - virtual void Flush() = 0; + //! Transfer prepared state to the enclosing checkpoint. + virtual void AddPendingPublication(unique_ptr publication) = 0; //! Get the targeted storage version for the current writer StorageVersion GetStorageVersion() const; @@ -55,7 +56,7 @@ class SingleFileTableIndexWriter : public TableIndexWriter { private: PartialBlockManager CreatePerIndexPartialBlockManager() override; - void Flush() override; + void AddPendingPublication(unique_ptr publication) override; private: SingleFileCheckpointWriter &checkpoint_manager; diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp index 8a60e47ba..e5b62dc53 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp @@ -42,6 +42,7 @@ class TriggerCatalogEntry; class ViewCatalogEntry; class TableDataWriter; class TypeCatalogEntry; +class PendingPublication; struct BoundCreateTableInfo; struct CheckpointOptions; @@ -50,8 +51,7 @@ 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(optional_ptr context, AttachedDatabase &db, - DuckTransactionManager &transaction_manager); + ActiveCheckpointWrapper(Context &context, AttachedDatabase &db, DuckTransactionManager &transaction_manager); ~ActiveCheckpointWrapper(); @@ -73,19 +73,32 @@ class ActiveCheckpointWrapper { class CheckpointWriter { public: - explicit CheckpointWriter(AttachedDatabase &db) : db(db) { - } - virtual ~CheckpointWriter() { - } + //! 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); + virtual ~CheckpointWriter(); //! The database AttachedDatabase &db; + //! The services of the query that triggered the checkpoint, or database-wide services if there is none + 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; virtual MetadataWriter &GetMetadataWriter() = 0; virtual unique_ptr GetTableDataWriter(TableCatalogEntry &table) = 0; +private: + shared_ptr owned_context; + Context &context; + optional_ptr client_context; + protected: virtual void WriteEntry(CatalogEntry &entry, Serializer &serializer); virtual void WriteSchema(SchemaCatalogEntry &schema, Serializer &serializer); @@ -146,7 +159,8 @@ class SingleFileCheckpointWriter final : public CheckpointWriter { public: SingleFileCheckpointWriter(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, - CheckpointOptions options); + CheckpointOptions options, optional_ptr client_context = nullptr); + ~SingleFileCheckpointWriter() override; void CreateCheckpoint() override; @@ -160,15 +174,15 @@ class SingleFileCheckpointWriter final : public CheckpointWriter { CheckpointOptions GetCheckpointOptions() const { return options; } - optional_ptr GetClientContext() const { - return context; - } public: void WriteTable(TableCatalogEntry &table, Serializer &serializer) override; private: - optional_ptr context; + //! Retain prepared state until the shared blocks are flushed and publication can run. + 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; @@ -179,12 +193,12 @@ class SingleFileCheckpointWriter final : public CheckpointWriter { //! Because this is single-file storage, we can share partial blocks across //! an entire checkpoint. PartialBlockManager partial_block_manager; - //! Need to have a separate partial block manager for indexes due to different block shapes. - PartialBlockManager index_partial_block_manager; //! Checkpoint type CheckpointOptions options; //! Block usage count for verification purposes unordered_map verify_block_usage_count; + //! Owns prepared state in publication order. + vector> pending_publications; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/chimp128.hpp b/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/chimp128.hpp index 6985a86e7..60146eeee 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/chimp128.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/chimp128.hpp @@ -223,10 +223,6 @@ struct Chimp128Decompression { static constexpr uint8_t INDEX_BITS_SIZE = 7; static constexpr uint8_t BIT_SIZE = sizeof(CHIMP_TYPE) * 8; - static inline void UnpackPackedData(uint16_t packed_data, UnpackedData &dest) { - return PackedDataUtils::Unpack(packed_data, dest); - } - static inline CHIMP_TYPE Load(ChimpConstants::Flags flag, uint8_t leading_zeros[], uint32_t &leading_zero_index, UnpackedData unpacked_data[], uint32_t &unpacked_index, DecompressState &state, BitReader &input) { diff --git a/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/packed_data.hpp b/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/packed_data.hpp index eaa896852..d58a78f2d 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/packed_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/chimp/algorithm/packed_data.hpp @@ -47,13 +47,6 @@ struct PackedDataUtils { return result; } - // FIXME: remove once chimp has been moved over to the above. - static inline void Unpack(uint16_t packed_data, UnpackedData &dest) { - dest = Unpack(packed_data); - // Verify that combined, this is not bigger than the full size of the type - D_ASSERT(dest.significant_bits + dest.leading_zero <= (sizeof(CHIMP_TYPE) * 8)); - } - static inline uint16_t Pack(uint8_t index, uint8_t leading_zero, uint8_t significant_bits) { static constexpr uint8_t BIT_SIZE = (sizeof(CHIMP_TYPE) * 8); diff --git a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/analyze.hpp b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/analyze.hpp index ab57b235a..fe21f5b92 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/analyze.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/analyze.hpp @@ -1,6 +1,10 @@ #pragma once +#include "duckdb/common/bitpacking.hpp" +#include "duckdb/common/primitive_dictionary.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/function/compression_function.hpp" +#include "duckdb/storage/compression/dict_fsst/common.hpp" namespace duckdb { @@ -10,6 +14,19 @@ namespace dict_fsst { // Analyze //===--------------------------------------------------------------------===// struct DictFSSTAnalyzeState : public AnalyzeState { +public: + //! Distinct values the set of a simulated block starts out with, and the factor it grows by when it fills up + static constexpr idx_t INITIAL_SET_SIZE = 1024; + static constexpr idx_t SET_GROWTH_FACTOR = 4; + //! Fixed point scale of 'fsst_ratio' + static constexpr idx_t FSST_RATIO_SCALE = 1024; + //! Bytes beyond twice the input length that FSST needs in its output buffer, as specified in fsst.h + static constexpr idx_t FSST_OUTPUT_SLACK = 7; + //! Amount of the dictionary of a block that is encoded to measure the ratio, which is what FSST trains on + static constexpr idx_t FSST_MEASURE_SIZE = 16384; + //! Number of times a full block considers encoding its dictionary between two measurements + static constexpr idx_t FSST_MEASURE_INTERVAL = 4; + public: explicit DictFSSTAnalyzeState(BlockManager &block_manager); @@ -17,8 +34,42 @@ struct DictFSSTAnalyzeState : public AnalyzeState { bool Analyze(const Vector &input); idx_t FinalAnalyze(); + //! Space one block with an unencoded dictionary needs to hold the given amount of tuples and dictionary entries + static idx_t RequiredSpace(idx_t tuple_count, idx_t unique_count, idx_t dict_size, idx_t max_string_length); + //! Same for the layout of the given mode, where an encoded dictionary also stores the symbol table + static idx_t RequiredSpace(DictionaryAppendState mode, idx_t tuple_count, idx_t unique_count, idx_t dict_size, + idx_t max_string_length, idx_t symbol_table_size); + +private: + //! Account for a tuple that reuses a dictionary index (NULL or a repeated value); false if the block is full, or + //! if it decided to store every value, in which case the tuple has to be stored like a new value + bool TryAddIndexOnlyTuple(); + //! Account for a value the current block has not seen, flushing the block first if it does not fit. The hash is + //! only passed when the caller had to compute it, a block that stores every value does not need one. + void AddNewString(const string_t &str, optional_idx hash); + void FlushSimulatedBlock(); + //! Space a flushed segment of the given size takes on disk: the partial block manager packs small segments + //! together, but a segment above its limit gets a block of its own + idx_t SegmentCharge(idx_t required_space) const; + unique_ptr> MakeSet(idx_t size) const; + void GrowSet(); + + //! Space the current block can use: it reserves room for a symbol table until it is known to not need one + idx_t AvailableSpace() const; + //! Space the current block needs for the given contents, in the mode and with the symbol table it has + idx_t BlockRequiredSpace(idx_t tuple_count, idx_t unique_count, idx_t dict_size, idx_t max_string_length) const; + //! Length of a value of the given length once FSST encoded, according to the measured ratio + idx_t EncodedLength(idx_t length) const; + //! Length a value takes in the dictionary of the current block + idx_t StoredLength(idx_t length) const; + //! The block is full for an unencoded dictionary: decide how to continue, the way the writer does when it is + //! full (DictFSSTCompressionState::TryEncode) + void SwitchFromRegular(); + DictionaryAppendState ChooseEncoding(); + //! FSST encode the dictionary of the current block, to learn how well values compress and how big the table is + void MeasureFSST(); + public: - idx_t max_string_length = 0; bool contains_nulls = false; //! Effective exclusive size limit for plain dictionary encoding. idx_t string_size_limit = 0; @@ -26,8 +77,44 @@ struct DictFSSTAnalyzeState : public AnalyzeState { idx_t fsst_string_size_limit = 0; //! Flag which disables the usage of FSST if worst-case encoding blowup does not fit the block size. bool disable_fsst = false; - idx_t total_string_length = 0; idx_t total_count = 0; + + //! The dictionary is block-local, so the size estimate has to simulate how values pack into blocks: + //! duplicates that end up in different blocks are stored once per block, not once in total. + //! Space charged for the simulated blocks flushed so far, see SegmentCharge + idx_t simulated_space = 0; + //! How the current simulated block stores its values, which changes when it fills up (see SwitchFromRegular) + DictionaryAppendState current_mode = DictionaryAppendState::REGULAR; + idx_t current_tuple_count = 0; + idx_t current_unique_count = 0; + //! Size of the dictionary and of its longest entry, as stored in the mode of the block + idx_t current_dict_size = 0; + idx_t current_max_string_length = 0; + //! Size of the symbol table of the block, 0 as long as its dictionary is not encoded + idx_t current_symbol_table_size = 0; + //! Bit width of the dictionary indices and the space the block needs in its current state, cached so a tuple + //! that reuses an index only has to add a packing group now and then instead of recomputing the layout + bitpacking_width_t current_indices_width = 0; + idx_t current_required_space = 0; + //! Set of the distinct values in the current simulated block, grown when it fills up + unique_ptr> current_set; + //! Number of values 'current_set' was created for + idx_t current_set_size = 0; + //! Most distinct strings a block can hold, where 'current_set' stops growing + idx_t max_set_size = 0; + //! Owns the memory of the strings in 'current_set'; reset per simulated block to bound memory usage + StringHeap heap; + //! The first values the current block stored, to measure how well they compress if the block fills up + vector measure_sample; + idx_t measure_sample_size = 0; + + //! What encoding a dictionary with FSST achieves, measured on the dictionary of a block that filled up + //! Encoded over unencoded size, in FSST_RATIO_SCALE + idx_t fsst_ratio = FSST_RATIO_SCALE; + idx_t fsst_symbol_table_size = 0; + //! Number of times a full block considered encoding its dictionary, and the number at which to measure next + idx_t encode_decisions = 0; + idx_t next_measurement = 1; }; } // namespace dict_fsst diff --git a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/common.hpp b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/common.hpp index 24608e5be..fd36f8bab 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/common.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/common.hpp @@ -37,8 +37,14 @@ struct DictFSSTCompression { //! Dictionary header size at the beginning of the string segment (offset + length) static constexpr uint16_t DICTIONARY_HEADER_SIZE = sizeof(dict_fsst_compression_header_t); static constexpr idx_t STRING_SIZE_LIMIT = 16384; + //! Dictionary size from which the writer considers FSST encoding it, and the saving it has to achieve + static constexpr idx_t DICTIONARY_ENCODE_THRESHOLD = 4096; }; +static inline bool IsEncoded(DictionaryAppendState state) { + return state == DictionaryAppendState::ENCODED || state == DictionaryAppendState::ENCODED_ALL_UNIQUE; +} + } // namespace dict_fsst } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/compression.hpp b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/compression.hpp index 7cab5f116..5b666ac48 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/compression.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/compression.hpp @@ -47,14 +47,12 @@ struct DictFSSTCompressionState : public StandardCompressionState { bool AllUnique() const; void FlushEncodingBuffer(); - idx_t CalculateRequiredSpace() const; DictionaryAppendState TryEncode(); DictFSSTCompressResult CompressInternal(UnifiedVectorFormat &vector_format, const string_t &str, bool is_null, EncodedInput &encoded_input, const idx_t i, idx_t count, bool fail_on_no_space); void Compress(const Vector &scan_vector); - void FinalizeCompress(); void Flush(bool final); public: diff --git a/src/duckdb/src/include/duckdb/storage/data_table.hpp b/src/duckdb/src/include/duckdb/storage/data_table.hpp index ccaf066f4..c4fbe1658 100644 --- a/src/duckdb/src/include/duckdb/storage/data_table.hpp +++ b/src/duckdb/src/include/duckdb/storage/data_table.hpp @@ -41,8 +41,10 @@ class Vector; class Transaction; class WriteAheadLog; class TableDataWriter; +class TableStatistics; class ConflictManager; class TableScanState; +struct CollectionCheckpointResult; struct TableDeleteState; struct ConstraintState; struct TableUpdateState; @@ -233,6 +235,8 @@ class DataTable : public enable_shared_from_this { //! Checkpoint the table to the specified table data writer void Checkpoint(TableDataWriter &writer, Serializer &serializer); + //! Install checkpointed row groups. + void PublishCheckpoint(CollectionCheckpointResult result, TableStatistics &checkpoint_stats); //! Accumulates the table's on-disk blocks for reclamation into the drop state. void CommitDropTable(CommitDropState &drop_state); //! Accumulates the column's on-disk blocks for reclamation into the drop state. diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp index c89514b63..1b860cc69 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp @@ -122,6 +122,7 @@ class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_th bool write) override; DUCKDB_API void SetDisabledFileSystems(const vector &names) override; + DUCKDB_API vector GetDisabledFileSystems() override; DUCKDB_API bool SubSystemIsDisabled(const string &name) override; DUCKDB_API bool IsDisabledForPath(const string &path) override; diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache_util.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache_util.hpp index e64c9f3b8..ce1b1af05 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache_util.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache_util.hpp @@ -15,13 +15,13 @@ namespace duckdb { struct OpenFileInfo; class DatabaseInstance; -class ClientContext; +class Context; struct ExternalFileCacheUtil { - //! Get the cache validation mode in order of file open info, client context (for client-local settings), or + //! Get the cache validation mode in order of file open info, execution context (for client-local settings), or //! database config. - DUCKDB_API static CacheValidationMode - GetCacheValidationMode(const OpenFileInfo &info, optional_ptr client_context, DatabaseInstance &db); + DUCKDB_API static CacheValidationMode GetCacheValidationMode(const OpenFileInfo &info, + optional_ptr context, DatabaseInstance &db); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/object_cache.hpp b/src/duckdb/src/include/duckdb/storage/object_cache.hpp index 4c4ed3a05..b133749ed 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/optimistic_data_writer.hpp b/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp index abaae1f13..3104bb393 100644 --- a/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp @@ -35,6 +35,7 @@ enum class OptimisticWritePartialManagers { PER_COLUMN, GLOBAL }; class OptimisticDataWriter { public: OptimisticDataWriter(ClientContext &context, DataTable &table); + OptimisticDataWriter(Context &context, DataTable &table); OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent); ~OptimisticDataWriter(); @@ -57,8 +58,8 @@ class OptimisticDataWriter { //! Whether this writer can write to disk at all (not temporary / in-memory / read-only) bool CanWriteToDisk() const; - //! Return the client context. - ClientContext &GetClientContext() { + //! Return the runtime services. + Context &GetContext() { return context; } @@ -70,8 +71,8 @@ class OptimisticDataWriter { const vector &segment_indexes); private: - //! The client context in which we're writing the data. - ClientContext &context; + //! The services in which we're writing the data. + Context &context; //! The table. DataTable &table; //! The partial block manager, if any. diff --git a/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp index b08cfb188..de15f83ea 100644 --- a/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp @@ -36,7 +36,7 @@ class PartialBlockManager { public: //! Use the default packing threshold unless supplied; it must not exceed the block size. - PartialBlockManager(QueryContext context, BlockManager &block_manager, PartialBlockType partial_block_type, + PartialBlockManager(Context &context, BlockManager &block_manager, PartialBlockType partial_block_type, optional_idx max_partial_block_size = optional_idx(), uint32_t max_use_count = DEFAULT_MAX_USE_COUNT); //! Discard pending blocks without flushing or finalizing their packables. @@ -68,8 +68,8 @@ class PartialBlockManager { //! Returns a reference to the underlying block manager. BlockManager &GetBlockManager() const; - //! Returns the optional client context. - optional_ptr GetClientContext() const; + //! Returns the query context to attribute IO to. + QueryContext GetQueryContext() const; private: //! Remove the smallest fitting block from the map, or return nullptr if none fits. @@ -84,11 +84,8 @@ class PartialBlockManager { void RetainOrFlush(unique_ptr partial_block); private: - //! The optional client context in which we use the partial block manager. - //! The SingleFileCheckpointWriter contains a partial block manager, and the destructor of - //! AttachedDatabase invokes CreateCheckpoint with that checkpoint writer. - //! Thus, we're using the optional client context instead of a reference. - optional_ptr context; + //! The context in which we use the partial block manager (owned by the checkpoint writer) + Context &context; BlockManager &block_manager; PartialBlockType partial_block_type; mutex partial_block_lock; diff --git a/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp b/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp index 01f14eb77..140672394 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp @@ -15,6 +15,7 @@ #include "duckdb/storage/statistics/numeric_stats.hpp" #include "duckdb/storage/statistics/string_stats.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/storage/statistics/geometry_stats.hpp" #include "duckdb/storage/statistics/variant_stats.hpp" #include "duckdb/storage/statistics/stats_merge_type.hpp" @@ -177,6 +178,8 @@ class BaseStatistics { NumericStatsData numeric_data; //! String stats data, for string stats StringStatsData string_data; + //! List stats data, for list stats + ListStatsData list_data; //! Geometry stats data, for geometry stats GeometryStatsData geometry_data; //! Variant stats data, for variant stats diff --git a/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp index bc56a4c9a..b870f59f2 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp @@ -195,12 +195,14 @@ class GeometryTypeSet { return result_found; } - void AddWKBType(int32_t wkb_type) { - const auto vert_idx = static_cast((wkb_type / 1000) % 10); - const auto geom_idx = static_cast(wkb_type % 1000); - D_ASSERT(vert_idx < VERT_TYPES); - D_ASSERT(geom_idx < PART_TYPES); + bool TryAddWKBType(int32_t wkb_type) { + const auto vert_idx = wkb_type / 1000; + const auto geom_idx = wkb_type % 1000; + if (vert_idx < 0 || vert_idx >= VERT_TYPES || geom_idx < 1 || geom_idx >= PART_TYPES) { + return false; + } sets[vert_idx] |= (1 << geom_idx); + return true; } vector ToWKBList() const { diff --git a/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp index ce23a2703..66021f686 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp @@ -11,6 +11,7 @@ #include "duckdb/common/common.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/types.hpp" +#include "duckdb/common/optional_idx.hpp" #include "duckdb/storage/statistics/stats_merge_type.hpp" namespace duckdb { @@ -19,6 +20,28 @@ struct SelectionVector; class Vector; class Value; +struct ListStatsData { + //! Whether or not the minimum list length is known + bool has_min_list_length; + //! Whether or not the maximum list length is known + bool has_max_list_length; + //! Whether or not the total list length is known + bool has_total_list_length; + //! The minimum length of any non-NULL list + uint64_t min_list_length; + //! The maximum length of any non-NULL list + uint64_t max_list_length; + //! The total (summed) length of all non-NULL lists + uint64_t total_list_length; + +public: + bool HasMinListLength() const; + //! The minimum, maximum and total list length, which are invalid if they are unknown + optional_idx MinLength() const; + optional_idx MaxLength() const; + optional_idx TotalLength() const; +}; + struct ListStats { DUCKDB_API static void Construct(BaseStatistics &stats); DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type); @@ -28,6 +51,26 @@ struct ListStats { DUCKDB_API static BaseStatistics &GetChildStats(BaseStatistics &stats); DUCKDB_API static void SetChildStats(BaseStatistics &stats, unique_ptr new_stats); + //! Returns the minimum list length of the non-NULL lists, if known + DUCKDB_API static optional_idx MinListLength(const BaseStatistics &stats); + //! Returns the maximum list length of the non-NULL lists, if known + DUCKDB_API static optional_idx MaxListLength(const BaseStatistics &stats); + //! Returns the total list length of the non-NULL lists, if known + DUCKDB_API static optional_idx TotalListLength(const BaseStatistics &stats); + //! Sets the list length bounds, which are unknown if not set, and makes the total list length unknown + DUCKDB_API static void SetLengthBounds(BaseStatistics &stats, optional_idx min_length, optional_idx max_length); + //! Merges in the length stats of a set of lists + DUCKDB_API static void MergeInLengths(BaseStatistics &stats, idx_t min_length, idx_t max_length, + idx_t total_length); + //! Returns a copy of the list length stats + DUCKDB_API static ListStatsData GetLengthData(const BaseStatistics &stats); + //! Overwrites the list length stats + DUCKDB_API static void SetLengthData(BaseStatistics &stats, const ListStatsData &data); + //! Resets the list length stats to the stats of an empty set of lists + DUCKDB_API static void ResetLengthData(BaseStatistics &stats); + //! Marks the total list length as unknown + DUCKDB_API static void ResetTotalListLength(BaseStatistics &stats); + DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); @@ -38,6 +81,10 @@ struct ListStats { DUCKDB_API static void Copy(BaseStatistics &stats, const BaseStatistics &other); DUCKDB_API static void Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count); + +private: + static ListStatsData &GetDataUnsafe(BaseStatistics &stats); + static const ListStatsData &GetDataUnsafe(const BaseStatistics &stats); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/storage_info.hpp b/src/duckdb/src/include/duckdb/storage/storage_info.hpp index be2d19ff5..98cadbac6 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_info.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_info.hpp @@ -142,6 +142,7 @@ enum class StorageVersion : uint64_t { V1_5_5 = 68, V1_5_6 = 68, V2_0_0 = 69, + V2_0_1 = 69, V2_1_0 = 70, LATEST = 70, DEPRECATED = 999, @@ -180,6 +181,7 @@ enum class SerializationVersionDeprecated : uint64_t { V1_5_5 = 7, V1_5_6 = 7, V2_0_0 = 8, + V2_0_1 = 8, V2_1_0 = 9, LATEST = 9, INVALID = UINT64_MAX diff --git a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp index 1c693224c..30e129d47 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp @@ -112,7 +112,9 @@ class StorageManager { virtual bool AutomaticCheckpoint(idx_t estimated_wal_bytes) = 0; virtual unique_ptr GenStorageCommitState(WriteAheadLog &wal) = 0; virtual bool IsCheckpointClean(MetaBlockPointer checkpoint_id) = 0; - virtual void CreateCheckpoint(QueryContext context, CheckpointOptions options = CheckpointOptions()) = 0; + //! The client context is only passed for explicit checkpoints + virtual void CreateCheckpoint(QueryContext context, CheckpointOptions options = CheckpointOptions(), + optional_ptr client_context = nullptr) = 0; virtual DatabaseSize GetDatabaseSize() = 0; virtual vector GetMetadataInfo() = 0; virtual shared_ptr GetTableIOManager(BoundCreateTableInfo *info) = 0; @@ -220,7 +222,8 @@ class SingleFileStorageManager : public StorageManager { bool AutomaticCheckpoint(idx_t estimated_wal_bytes) override; unique_ptr GenStorageCommitState(WriteAheadLog &wal) override; bool IsCheckpointClean(MetaBlockPointer checkpoint_id) override; - void CreateCheckpoint(QueryContext context, CheckpointOptions options) override; + void CreateCheckpoint(QueryContext context, CheckpointOptions options, + optional_ptr client_context) override; DatabaseSize GetDatabaseSize() override; vector GetMetadataInfo() override; shared_ptr GetTableIOManager(BoundCreateTableInfo *info) override; @@ -230,6 +233,7 @@ class SingleFileStorageManager : public StorageManager { protected: void LoadDatabase(QueryContext context) override; - unique_ptr CreateCheckpointWriter(QueryContext context, CheckpointOptions options); + unique_ptr CreateCheckpointWriter(QueryContext context, CheckpointOptions options, + optional_ptr client_context); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp b/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp index 11f12087d..a4eaf050d 100644 --- a/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp +++ b/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp @@ -104,8 +104,6 @@ struct UncompressedStringStorage { public: //! Dictionary header size at the beginning of the string segment (offset + length) static constexpr uint16_t DICTIONARY_HEADER_SIZE = sizeof(uint32_t) + sizeof(uint32_t); - //! Marker used in length field to indicate the presence of a big string - static constexpr uint16_t BIG_STRING_MARKER = (uint16_t)-1; //! Base size of big string marker (block id + offset) static constexpr idx_t BIG_STRING_MARKER_BASE_SIZE = sizeof(block_id_t) + sizeof(int32_t); //! The marker size of the big string @@ -137,13 +135,6 @@ struct UncompressedStringStorage { return StringAppendBase(append_state.handle, segment, stats, data, offset, count); } - static idx_t StringAppendBase(ColumnSegment &segment, BaseStatistics &stats, UnifiedVectorFormat &data, - idx_t offset, idx_t count) { - auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); - auto handle = buffer_manager.Pin(segment.GetBlockHandle()); - return StringAppendBase(handle, segment, stats, data, offset, count); - } - static idx_t StringAppendBase(BufferHandle &handle, ColumnSegment &segment, BaseStatistics &stats, UnifiedVectorFormat &data, idx_t offset, idx_t count) { auto handle_ptr = handle.GetDataMutable() + segment.GetBlockOffset(); @@ -284,36 +275,6 @@ struct UncompressedStringStorage { static string_t ReadStringWithLength(CompressionSegmentReader reader, int32_t offset); static void WriteStringMarker(data_ptr_t target, block_id_t block_id, int32_t offset); - // FIXME: Remove this raw pointer helper once FSST no longer needs it. - inline static string_t FetchStringFromDict(const QueryContext &context, ColumnSegment &segment, - uint32_t dict_end_offset, Vector &result, data_ptr_t base_ptr, - int32_t dict_offset, uint32_t string_length) { - D_ASSERT(dict_offset <= NumericCast(segment.GetBlockSize())); - if (DUCKDB_LIKELY(dict_offset >= 0)) { - // regular string - fetch from dictionary - auto dict_end = base_ptr + dict_end_offset; - auto dict_pos = dict_end - dict_offset; - auto str_ptr = char_ptr_cast(dict_pos); - return string_t(str_ptr, string_length); - } else if (string_length == 0) { - // NULL values are stored as a copy of the previous entry's dictionary offset (see - // StringAppendBase). When the previous entry is a big (overflow) string, its offset is - // negative, so the NULL inherits that negative offset even though it references no - // overflow data (its computed length is 0). Return an empty string here instead of - // following the marker into ReadOverflowString - otherwise every NULL that trails a big - // string re-reads and re-allocates the entire overflow string (O(num_nulls * big_size) - // memory, tagged OVERFLOW_STRINGS). The value is masked NULL by the caller regardless. - return string_t(char_ptr_cast(base_ptr), 0); - } else { - // read overflow string - auto marker = base_ptr + dict_end_offset - AbsValue(dict_offset); - block_id_t block_id = Load(marker); - int32_t offset = Load(marker + sizeof(block_id_t)); - - return ReadOverflowString(context, segment, result, block_id, offset); - } - } - inline static string_t FetchStringFromEntry(const QueryContext &context, ColumnSegment &segment, Vector &result, const StringDictionaryEntry &entry) { if (DUCKDB_LIKELY(!entry.is_overflow)) { diff --git a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp index f99df3b48..d81d8f7dd 100644 --- a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp @@ -21,10 +21,11 @@ class ArrayColumnData : public ColumnData { public: void SetDataType(ColumnDataType data_type) override; - FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) override; + FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) override; - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -40,7 +41,6 @@ class ArrayColumnData : public ColumnData { void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; void FinalizeAppend(ColumnDataFinalizeAppendState &finalize_state, ColumnAppendState &state) override; void RevertAppend(row_t new_count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/chunk_info.hpp b/src/duckdb/src/include/duckdb/storage/table/chunk_info.hpp index 967607d20..adb653420 100644 --- a/src/duckdb/src/include/duckdb/storage/table/chunk_info.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/chunk_info.hpp @@ -82,8 +82,9 @@ class ChunkVectorInfo { void RollbackWrite(const uint16_t rows[], idx_t count, const transaction_t previous_ids[], idx_t previous_id_count); //! Attempts to compress the per-row insert/delete ids into constants. Ids that precede - //! lowest_visibility_bound look the same to every active and future transaction, so they can collapse - VersionCompressionResult CompressVersionIds(VisibilityBound lowest_visibility_bound); + //! lowest_visibility_bound look the same to every active and future transaction, so they can collapse. + //! Only the first row_count rows hold rows - the insert ids past them are not considered + VersionCompressionResult CompressVersionIds(VisibilityBound lowest_visibility_bound, idx_t row_count); //! Whether a compression pass could achieve anything for this vector (see recheck_compression) bool RecheckCompression() const { return recheck_compression; @@ -92,7 +93,8 @@ class ChunkVectorInfo { //! compressible now or in the future without a modification that re-arms the check void VerifyCachedCompressionState() const; - bool HasDeletes(VisibilityBound visibility_bound = VisibilityBound::IncludingUncommitted()) const; + //! Whether any of the first row_count rows are deleted (or not yet committed) as of visibility_bound + bool HasDeletes(VisibilityBound visibility_bound, idx_t row_count) const; bool HasUncommittedChanges() const; bool AnyDeleted() const; bool HasConstantInsertionId() const; @@ -100,7 +102,8 @@ class ChunkVectorInfo { bool HasConstantDeleteId() const; transaction_t ConstantDeleteId() const; - void Write(WriteStream &writer, VisibilityBound visibility_bound) const; + //! Writes which of the first row_count rows are deleted - the slots past them are written as not deleted + void Write(WriteStream &writer, VisibilityBound visibility_bound, idx_t row_count) const; static unique_ptr Read(FixedSizeAllocator &allocator, ReadStream &reader); private: diff --git a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp index bc8225ced..9b0e05d96 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp @@ -40,6 +40,7 @@ class UpdateSegment; struct DataTableInfo; struct PrefetchState; struct RowGroupWriteInfo; +struct ScanFilter; struct TransactionData; struct PersistentColumnData; class ValidityColumnData; @@ -83,8 +84,14 @@ class ColumnData : public enable_shared_from_this { LogicalType type; public: - virtual FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment); + //! Checks the filter against the zonemap from the scan position, and sets checked_end to the row of the row group + //! up to which the result holds, so that the scan can skip ahead to it when the filter is rejected + virtual FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end); + //! Checks the filter against the zonemap from any row of the row group, reporting checked_end as CheckZonemap + //! does, so that the prefetch of a scan can leave out the vectors the filter rejects + virtual FilterPropagateResult CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, + optional_idx &checked_end); BlockManager &GetBlockManager() const { return block_manager; @@ -139,8 +146,9 @@ class ColumnData : public enable_shared_from_this { //! Whether or not we can scan an entire vector virtual ScanVectorType GetVectorScanType(ColumnScanState &state, idx_t scan_count, Vector &result); - //! Initialize prefetch state with required I/O data for the next N rows - virtual void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows); + //! Initialize prefetch state with the I/O data required to scan the rows in [start_row, end_row) + virtual void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row); //! Initialize a scan of the column virtual void InitializeScan(ColumnScanState &state); //! Initialize a scan starting at the specified offset @@ -175,8 +183,6 @@ class ColumnData : public enable_shared_from_this { //! Revert a set of appends to the ColumnData virtual void RevertAppend(row_t new_count); - //! Fetch the vector from the column data that belongs to this specific row - virtual idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result); //! Fetch a batch of row offsets and append them to the vector virtual void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, @@ -187,6 +193,8 @@ class ColumnData : public enable_shared_from_this { //! Fetches the base data of a batch of row offsets, without updates void FetchBaseRows(const QueryContext &context, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset); + //! Fetches base values of row_ids into result, densely and in the same order, without updates + void FetchBaseRows(const row_t *row_ids, idx_t count, Vector &result, idx_t row_group_start); //! Reads the selected rows of a scan through FetchBaseRows (debug_force_fetch_row) void FetchScannedRows(ColumnScanState &state, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset); @@ -225,8 +233,6 @@ class ColumnData : public enable_shared_from_this { FilterPropagateResult CheckZonemap(optional_ptr context, const StorageIndex &index, TableFilter &filter); - //! End of the last vector in [start_row, end_row) that the segment zonemaps do not reject for the filter - idx_t ZonemapScanEnd(optional_ptr context, idx_t start_row, idx_t end_row, TableFilter &filter); static shared_ptr CreateColumn(BlockManager &block_manager, DataTableInfo &info, idx_t column_index, const LogicalType &type, @@ -262,19 +268,16 @@ class ColumnData : public enable_shared_from_this { UpdateScanType update_type); void FetchUpdateRow(TransactionData transaction, row_t row_id, Vector &result, idx_t result_idx); void UpdateInternal(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, - Vector &update_vector, row_t *row_ids, idx_t update_count, Vector &base_vector, + Vector &update_vector, row_t *row_ids, idx_t update_count, const Vector &base_vector, idx_t row_group_start); - idx_t FetchUpdateData(ColumnScanState &state, row_t *row_ids, Vector &base_vector, idx_t row_group_start); - idx_t GetVectorCount(idx_t vector_index) const; static bool IsDirectNullCheckFilter(const TableFilter &filter); - //! Checks the filter against the statistics of one segment + //! Checks the filter against the statistics of one segment and of the updates of the column FilterPropagateResult CheckSegmentStatistics(optional_ptr context, SegmentNode &segment, ExpressionFilter &expr_filter); - FilterPropagateResult CheckValidityZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment, - ColumnData &validity_column); + FilterPropagateResult CheckValidityZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end, ColumnData &validity_column); private: void UpdateCompressionFunction(SegmentLock &l, const CompressionFunction &function); @@ -319,6 +322,7 @@ enum class ExtraPersistentColumnDataType : uint8_t { INVALID = 0, VARIANT = 1, GEOMETRY = 2, + LIST = 3, }; class ExtraPersistentColumnData { @@ -344,6 +348,10 @@ class ExtraPersistentColumnData { void Serialize(Serializer &serializer) const; static unique_ptr Deserialize(Deserializer &deserializer); + //! Whether the extra data can be written for the storage version of the serializer + virtual bool IsSupported(const Serializer &serializer) const { + return true; + } protected: explicit ExtraPersistentColumnData(ExtraPersistentColumnDataType type_p) : type(type_p) { diff --git a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp index 8d7ef912d..ce39663d0 100644 --- a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp @@ -30,7 +30,8 @@ class GeoColumnData final : public ColumnData { void InitializeChildScanStates(ColumnScanState &state); - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -45,7 +46,6 @@ class GeoColumnData final : public ColumnData { void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; void FinalizeAppend(ColumnDataFinalizeAppendState &finalize_state, ColumnAppendState &state) override; void RevertAppend(row_t new_count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp b/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp index 1b108d9c7..4ee40b19c 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 @@ -18,16 +18,14 @@ namespace duckdb { class InMemoryCheckpointer final : public CheckpointWriter { public: InMemoryCheckpointer(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, - StorageManager &storage_manager, CheckpointOptions options); + StorageManager &storage_manager, CheckpointOptions options, + optional_ptr client_context = nullptr); void CreateCheckpoint() override; MetadataWriter &GetMetadataWriter() override; MetadataManager &GetMetadataManager() override; unique_ptr GetTableDataWriter(TableCatalogEntry &table) override; - optional_ptr GetClientContext() const { - return context; - } CheckpointOptions GetCheckpointOptions() const { return options; } @@ -39,7 +37,6 @@ class InMemoryCheckpointer final : public CheckpointWriter { void WriteTable(TableCatalogEntry &table, Serializer &serializer) override; private: - optional_ptr context; PartialBlockManager partial_block_manager; StorageManager &storage_manager; CheckpointOptions options; @@ -54,7 +51,7 @@ class InMemoryTableDataWriter : public TableDataWriter { idx_t total_rows, idx_t next_row_id) override; void FinalizeTable(const TableStatistics &global_stats, DataTableInfo &info, RowGroupCollection &collection, const vector> &index_infos, Serializer &serializer) override; - unique_ptr GetRowGroupWriter(RowGroup &row_group) override; + unique_ptr GetRowGroupWriter() override; unique_ptr GetTableIndexWriter(StorageVersion version) override; void FlushPartialBlocks() override; CheckpointOptions GetCheckpointOptions() const override; diff --git a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp index b1478db90..d7736bd0c 100644 --- a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp @@ -10,9 +10,27 @@ #include "duckdb/storage/table/column_data.hpp" #include "duckdb/storage/table/validity_column_data.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" namespace duckdb { +//! The list length statistics that are persisted with a list column +class ListPersistentColumnData final : public ExtraPersistentColumnData { +public: + static constexpr auto TYPE = ExtraPersistentColumnDataType::LIST; + ListPersistentColumnData() : ExtraPersistentColumnData(TYPE) { + } + explicit ListPersistentColumnData(const ListStatsData &length_data_p) + : ExtraPersistentColumnData(TYPE), length_data(length_data_p) { + } + + bool IsSupported(const Serializer &serializer) const override; + void SerializeFields(Serializer &serializer) const; + static unique_ptr Deserialize(Deserializer &deserializer); + + ListStatsData length_data = ListStatsData {false, false, false, 0, 0, 0}; +}; + //! List column data represents a list class ListColumnData : public ColumnData { public: @@ -21,10 +39,11 @@ class ListColumnData : public ColumnData { public: void SetDataType(ColumnDataType data_type) override; - FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) override; + FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) override; - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -38,7 +57,6 @@ class ListColumnData : public ColumnData { void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; void FinalizeAppend(ColumnDataFinalizeAppendState &finalize_state, ColumnAppendState &state) override; void RevertAppend(row_t new_count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; @@ -66,6 +84,8 @@ class ListColumnData : public ColumnData { const ColumnSegmentInfoScanOptions &options) override; void SetValidityData(shared_ptr validity_p); + //! The statistics of this column, if they can be resolved + optional_ptr GetColumnStatistics() const; void SetChildData(shared_ptr child_column_p); const BaseStatistics &GetChildStats(const ColumnData &child) const override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp index 164e1eef7..3814bbb46 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp @@ -194,7 +194,7 @@ class RowGroup : public SegmentBase { //! Checks the given set of table filters against the row-group statistics. Returns false if the entire row group //! can be skipped. bool CheckZonemap(optional_ptr context, ScanFilterInfo &filters, idx_t row_start); - //! Checks the given set of table filters against the per-segment statistics. Returns false if any segments were + //! Checks the given set of table filters against the zonemaps of their columns. Returns false if any vectors were //! skipped. bool CheckZonemapSegments(CollectionScanState &state); void Scan(ScanOptions options, CollectionScanState &state, DataChunk &result); @@ -203,8 +203,8 @@ class RowGroup : public SegmentBase { void PrefetchScanIO(CollectionScanState &state, idx_t row_count) const; //! Collects the async I/O tasks required to scan the next row_count rows, without performing any I/O vector> CollectScanIOTasks(CollectionScanState &state, idx_t row_count) const; - //! Rows of the remaining assignment worth prefetching, trailing vectors the zonemaps reject are left out - idx_t PrefetchRowCount(CollectionScanState &state); + //! Collects the async I/O tasks of the remaining assignment, leaving out the vectors the zonemaps reject + vector> CollectAssignmentIOTasks(CollectionScanState &state) const; //! Prepares the next eligible vector in the assigned range, idempotent, returns false when none remain bool PrepareScan(ScanOptions options, CollectionScanState &state); //! Processes the vector prepared by PrepareScan, clearing the prepared state when the vector is finished @@ -309,8 +309,10 @@ class RowGroup : public SegmentBase { ColumnData &GetRawColumnData(storage_t c) const; private: - //! Registers prefetch candidates for the next row_count rows, returns false when prefetching is not supported - bool RegisterScanIO(CollectionScanState &state, idx_t row_count, PrefetchState &prefetch_state) const; + //! Registers prefetch candidates for the rows in [start_row, end_row), returns false when prefetching is not + //! supported + bool RegisterScanIO(CollectionScanState &state, idx_t start_row, idx_t end_row, + PrefetchState &prefetch_state) const; //! Shared scan-state setup for InitializeScan and InitializeScanWithOffset bool InitializeScanInternal(CollectionScanState &state, SegmentNode &node, idx_t vector_offset); //! Advances the scan past the current vector, clearing the prepared state diff --git a/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp index 8119d9b95..63e61dbda 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp @@ -17,7 +17,8 @@ class RowIdColumnData : public ColumnData { RowIdColumnData(BlockManager &block_manager, DataTableInfo &info); public: - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -31,15 +32,16 @@ class RowIdColumnData : public ColumnData { void Select(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result, SelectionVector &sel, idx_t count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; void Skip(ColumnScanState &state, idx_t count = STANDARD_VECTOR_SIZE) override; - FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) override; + FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) override; + FilterPropagateResult CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, + optional_idx &checked_end) override; void InitializeAppend(ColumnAppendState &state) override; void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp index 7b7daf8e0..e56525cca 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp @@ -17,7 +17,8 @@ class RowNumberColumnData : public ColumnData { RowNumberColumnData(BlockManager &block_manager, DataTableInfo &info); public: - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -29,15 +30,14 @@ class RowNumberColumnData : public ColumnData { void Select(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result, SelectionVector &sel, idx_t count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; void Skip(ColumnScanState &state, idx_t count = STANDARD_VECTOR_SIZE) override; - FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) override; + FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) override; void InitializeAppend(ColumnAppendState &state) override; void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_version_manager.hpp b/src/duckdb/src/include/duckdb/storage/table/row_version_manager.hpp index 3a5020f0f..ff1a588e2 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_version_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_version_manager.hpp @@ -51,9 +51,10 @@ class RowVersionManager { //! lowest_visibility_bound look the same to every active and future transaction, so they can collapse. //! Cheap when nothing can have changed: the pass only runs when version ids were modified since the //! last pass, or when a previous pass left ids that can still compress once older transactions finish - void CompressVersionIds(VisibilityBound lowest_visibility_bound); + void CompressVersionIds(VisibilityBound lowest_visibility_bound, idx_t row_count); - vector Checkpoint(RowGroupWriter &writer); + //! Writes the deletes of the first row_count rows of the row group + vector Checkpoint(RowGroupWriter &writer, idx_t row_count); static shared_ptr Deserialize(MetaBlockPointer delete_pointer, MetadataManager &manager); bool HasUnserializedChanges(VisibilityBound bound); diff --git a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp index 337bf8b5c..c44ca73f3 100644 --- a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp @@ -23,7 +23,8 @@ class StandardColumnData : public ColumnData { void SetDataType(ColumnDataType data_type) override; ScanVectorType GetVectorScanType(ColumnScanState &state, idx_t scan_count, Vector &result) override; - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -40,7 +41,6 @@ class StandardColumnData : public ColumnData { void AppendData(ColumnAppendState &state, UnifiedVectorFormat &vdata, idx_t count) override; void FinalizeAppend(ColumnDataFinalizeAppendState &finalize_state, ColumnAppendState &state) override; void RevertAppend(row_t new_count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp index 30941fc2b..118b77c72 100644 --- a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp @@ -36,10 +36,13 @@ class StructColumnData : public ColumnData { public: void SetDataType(ColumnDataType data_type) override; idx_t GetMaxEntry() override; - FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) override; + FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) override; + FilterPropagateResult CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, + optional_idx &checked_end) override; - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -55,7 +58,6 @@ class StructColumnData : public ColumnData { void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; void FinalizeAppend(ColumnDataFinalizeAppendState &finalize_state, ColumnAppendState &state) override; void RevertAppend(row_t new_count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/update_segment.hpp b/src/duckdb/src/include/duckdb/storage/table/update_segment.hpp index b4c07a07b..dc1cd794b 100644 --- a/src/duckdb/src/include/duckdb/storage/table/update_segment.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/update_segment.hpp @@ -10,7 +10,7 @@ #include "duckdb/storage/storage_lock.hpp" #include "duckdb/storage/statistics/segment_statistics.hpp" -#include "duckdb/common/types/string_heap.hpp" +#include "duckdb/storage/arena_allocator.hpp" #include "duckdb/transaction/undo_buffer_allocator.hpp" #include "duckdb/transaction/transaction_data.hpp" @@ -22,6 +22,7 @@ struct SelectionVector; class Vector; struct UpdateInfo; struct UpdateNode; +struct UpdateStringHeap; struct UndoBufferAllocator; class UpdateSegment { @@ -41,7 +42,7 @@ class UpdateSegment { void FetchCommitted(idx_t vector_index, Vector &result); void FetchCommittedRange(idx_t start_row, idx_t count, Vector &result); void Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update, - row_t *ids, idx_t count, Vector &base_data, idx_t row_group_start); + row_t *ids, idx_t count, const Vector &base_data, idx_t row_group_start); void FetchRows(TransactionData transaction, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset); @@ -50,11 +51,11 @@ class UpdateSegment { void CleanupUpdate(UpdateInfo &info); unique_ptr GetStatistics(); - StringHeap &GetStringHeap() { - return heap; - } private: + //! Merge the statistics of an update into those of the segment + void MergeStatistics(const SegmentStatistics &update_stats); + //! The lock for the update segment mutable StorageLock lock; //! The root node (if any) @@ -65,8 +66,6 @@ class UpdateSegment { mutex stats_lock; //! Internal type size idx_t type_size; - //! String heap, only used for strings - StringHeap heap; public: typedef void (*merge_update_function_t)(UpdateInfo &info, UnifiedVectorFormat &update, row_t *ids, idx_t count, @@ -83,8 +82,8 @@ class UpdateSegment { idx_t vector_offset, Vector &result, idx_t result_offset); typedef idx_t (*statistics_update_function_t)(UpdateSegment *segment, SegmentStatistics &stats, UnifiedVectorFormat &update, idx_t count, SelectionVector &sel); - typedef idx_t (*get_effective_updates_t)(UnifiedVectorFormat &update_format, row_t *ids, idx_t count, - SelectionVector &sel, Vector &base_data, idx_t id_offset); + typedef idx_t (*get_effective_updates_t)(UnifiedVectorFormat &update_format, idx_t count, SelectionVector &sel, + const Vector &base_data); private: merge_update_function_t merge_update_function; @@ -101,6 +100,23 @@ class UpdateSegment { UndoBufferPointer GetUpdateNode(StorageLockKey &lock, idx_t vector_idx) const; void InitializeUpdateInfo(idx_t vector_idx); void ReallocateRootInfoIfNeeded(UpdateInfo ¤t_info, idx_t update_count, idx_t vector_index); + void CompactStringHeapIfNeeded(UpdateInfo &root_info, idx_t vector_index, idx_t new_size); + void AddStringHeapReference(const StorageLockKey &lock, idx_t vector_index, Vector &result) const; +}; + +//! Holds the non-inlined strings of the update infos of a single vector +struct UpdateStringHeap { + explicit UpdateStringHeap(Allocator &allocator, + idx_t initial_capacity = ArenaAllocator::ARENA_ALLOCATOR_INITIAL_CAPACITY); + + ArenaAllocator allocator; + //! The total size of the strings added to the heap + idx_t size = 0; + //! The size of the strings in the heap when it was created, or last compacted + idx_t compacted_size = 0; + +public: + string_t AddString(const string_t &str); }; struct UpdateNode { @@ -109,6 +125,8 @@ struct UpdateNode { UndoBufferAllocator allocator; vector info; + //! For strings - the heap of each vector. Scans hold a reference, so a heap can be replaced when compacting it + vector> string_heaps; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp index d4890fa7a..9a97ae0b5 100644 --- a/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp @@ -34,7 +34,8 @@ class VariantColumnData : public ColumnData { return sub_columns.size() == 2; } - void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) override; + void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; @@ -48,7 +49,6 @@ class VariantColumnData : public ColumnData { void Append(ColumnAppendState &state, const Vector &vector, idx_t count) override; void FinalizeAppend(ColumnDataFinalizeAppendState &finalize_state, ColumnAppendState &state) override; void RevertAppend(row_t new_count) override; - idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override; void FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset) override; diff --git a/src/duckdb/src/include/duckdb/storage/temporary_memory_manager.hpp b/src/duckdb/src/include/duckdb/storage/temporary_memory_manager.hpp index 111ef1a56..357137d3f 100644 --- a/src/duckdb/src/include/duckdb/storage/temporary_memory_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/temporary_memory_manager.hpp @@ -16,7 +16,7 @@ namespace duckdb { -class ClientContext; +class Context; class TemporaryMemoryManager; //! State of the temporary memory to be managed concurrently with other states @@ -34,7 +34,7 @@ class TemporaryMemoryState { //! Set the remaining size needed for this state (NOTE: does not update the reservation!) void SetRemainingSize(idx_t new_remaining_size); //! Set the remaining size needed for this state and update the reservation - void SetRemainingSizeAndUpdateReservation(ClientContext &context, idx_t new_remaining_size); + void SetRemainingSizeAndUpdateReservation(Context &context, idx_t new_remaining_size); //! Set the remaining size to 0 (NOTE: updates the reservation to 0 as well) void SetZero(); //! Get the remaining size that was set for this state @@ -44,7 +44,7 @@ class TemporaryMemoryState { //! Get the minimum reservation for this state idx_t GetMinimumReservation() const; //! Updates the reservation based on current remaining size - void UpdateReservation(ClientContext &context); + void UpdateReservation(Context &context); //! Get the reservation of this state idx_t GetReservation() const; //! Set the materialization penalty for this state @@ -95,9 +95,9 @@ class TemporaryMemoryManager { public: //! Get the TemporaryMemoryManager - static TemporaryMemoryManager &Get(ClientContext &context); + static TemporaryMemoryManager &Get(Context &context); //! Register a TemporaryMemoryState - unique_ptr Register(ClientContext &context); + unique_ptr Register(Context &context); private: //! Get the default minimum reservation @@ -105,9 +105,9 @@ class TemporaryMemoryManager { //! Unregister a TemporaryMemoryState (called by the destructor of TemporaryMemoryState) void Unregister(TemporaryMemoryState &temporary_memory_state); //! Update memory_limit, has_temporary_directory, and num_threads (must hold the lock) - void UpdateConfiguration(ClientContext &context) DUCKDB_REQUIRES(lock); + void UpdateConfiguration(Context &context) DUCKDB_REQUIRES(lock); //! Update the TemporaryMemoryState to the new remaining size, and updates the reservation (must hold the lock) - void UpdateState(ClientContext &context, TemporaryMemoryState &temporary_memory_state) DUCKDB_REQUIRES(lock); + void UpdateState(Context &context, TemporaryMemoryState &temporary_memory_state) DUCKDB_REQUIRES(lock); //! Set the remaining size of a TemporaryMemoryState (must hold the lock) void SetRemainingSize(TemporaryMemoryState &temporary_memory_state, idx_t new_remaining_size) DUCKDB_REQUIRES(lock); //! Set the reservation of a TemporaryMemoryState (must hold the lock) diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp index b30fed196..51382548e 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp @@ -67,6 +67,8 @@ class DuckTransaction : public Transaction { void PushCatalogEntry(CatalogEntry &entry, data_ptr_t extra_data, idx_t extra_data_size); void PushAttach(AttachedDatabase &db); + //! Acquire a shared checkpoint lock for a statement, or return null if this transaction already holds one. + unique_ptr GetCheckpointLockForStatement(); void SetModifications(DatabaseModificationType type) override; bool ShouldWriteToWAL(AttachedDatabase &db); diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 7d18acbe6..3014ab186 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -11,6 +11,7 @@ #include "duckdb/storage/table/table_index_list.hpp" #include "duckdb/storage/optimistic_data_writer.hpp" #include "duckdb/common/error_data.hpp" +#include "duckdb/common/query_context.hpp" #include "duckdb/common/reference_map.hpp" namespace duckdb { @@ -40,7 +41,7 @@ struct TransactionData; class LocalTableStorage : public enable_shared_from_this { public: // Create a new LocalTableStorage - explicit LocalTableStorage(ClientContext &context, DataTable &table); + explicit LocalTableStorage(Context &context, DataTable &table); //! Create a LocalTableStorage from an ALTER TYPE. LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent, const idx_t alter_column_index, const LogicalType &target_type, @@ -52,7 +53,7 @@ class LocalTableStorage : public enable_shared_from_this { ExpressionExecutor &default_executor); ~LocalTableStorage(); - QueryContext context; + Context &context; reference table_ref; //! The DuckTableEntry visible to this transaction that references table_ref. @@ -81,7 +82,9 @@ class LocalTableStorage : public enable_shared_from_this { bool is_dropped = false; public: - void InitializeScan(CollectionScanState &state, optional_ptr table_filters = nullptr); + //! Initialize a scan; the context of the scanning query is used for pushed down casts and zonemap checks + void InitializeScan(const QueryContext &context, CollectionScanState &state, + optional_ptr table_filters = nullptr); //! Write a new row group to disk (if possible) void WriteNewRowGroup(idx_t flushed_row_group_idx); void FlushBlocks(); @@ -127,7 +130,7 @@ class LocalTableManager { reference_map_t> MoveEntries(); vector> GetEntries() const; optional_ptr GetStorage(const DataTable &table) const; - LocalTableStorage &GetOrCreateStorage(ClientContext &context, DataTable &table); + LocalTableStorage &GetOrCreateStorage(Context &context, DataTable &table); idx_t EstimatedSize() const; bool IsEmpty() const; void InsertEntry(DataTable &table, shared_ptr entry); @@ -148,14 +151,15 @@ class LocalStorage { }; public: - explicit LocalStorage(ClientContext &context, DuckTransaction &transaction); + explicit LocalStorage(Context &context, DuckTransaction &transaction); static LocalStorage &Get(DuckTransaction &transaction); static LocalStorage &Get(ClientContext &context, AttachedDatabase &db); static LocalStorage &Get(ClientContext &context, Catalog &catalog); //! Initialize a scan of the local storage - void InitializeScan(DataTable &table, CollectionScanState &state, optional_ptr table_filters); + void InitializeScan(const QueryContext &context, DataTable &table, CollectionScanState &state, + optional_ptr table_filters); //! Scan void Scan(CollectionScanState &state, const vector &column_ids, DataChunk &result); @@ -204,23 +208,23 @@ class LocalStorage { idx_t AddedRows(DataTable &table); vector GetPartitionStats(DataTable &table, TransactionData transaction) const; - void AddColumn(DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, + void AddColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, ExpressionExecutor &default_executor); void DropColumn(DataTable &old_dt, DataTable &new_dt, const idx_t drop_column_index); - void ChangeType(DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, const LogicalType &target_type, - const vector &bound_columns, Expression &cast_expr); + void ChangeType(ClientContext &context, DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, + const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr); void MoveStorage(DataTable &old_dt, DataTable &new_dt); void FetchChunk(DataTable &table, const Vector &row_ids, idx_t count, const vector &col_ids, DataChunk &chunk, ColumnFetchState &fetch_state); //! Returns true, if the local storage contains the row id. bool CanFetch(DataTable &table, const row_t row_id); - TableIndexList &GetIndexes(ClientContext &context, DataTable &table); + TableIndexList &GetIndexes(DataTable &table); optional_ptr GetStorage(const DataTable &table); void VerifyNewConstraint(DataTable &parent, const BoundConstraint &constraint); - ClientContext &GetClientContext() const { + Context &GetContext() const { return context; } DuckTransaction &GetTransaction() const { @@ -233,7 +237,7 @@ class LocalStorage { } private: - ClientContext &context; + Context &context; DuckTransaction &transaction; LocalTableManager table_manager; bool synced_flushed_blocks = false; diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 3bac1100d..e55b081a2 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -23,6 +23,8 @@ #include "duckdb_v2.h" +#include + //===--------------------------------------------------------------------===// // Util Macros //===--------------------------------------------------------------------===// @@ -125,7 +127,7 @@ typedef struct { (duckdb_v2_config_handle config, idx_t index, duckdb_v2_option_handle *out_option, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_get_option_by_name) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, duckdb_v2_option_handle *out_option, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_option_handle *out_option, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_get_option_count) (duckdb_v2_config_handle config, idx_t *out_count, duckdb_v2_error_info_handle *err); @@ -158,46 +160,51 @@ typedef struct { (duckdb_v2_environment_handle env, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_error_info_destroy)(duckdb_v2_error_info_handle *info); DUCKDB_V2_ERROR (*duckdb_v2_error_info_get_code)(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR *out_code); - DUCKDB_V2_ERROR (*duckdb_v2_error_info_get_raw_text)(duckdb_v2_error_info_handle info, duckdb_v2_str *out_raw_text); - DUCKDB_V2_ERROR (*duckdb_v2_error_info_get_text)(duckdb_v2_error_info_handle info, duckdb_v2_str *out_text); + DUCKDB_V2_ERROR(*duckdb_v2_error_info_get_raw_text) + (duckdb_v2_error_info_handle info, const char **out_raw_text, idx_t *out_raw_text_length); + DUCKDB_V2_ERROR(*duckdb_v2_error_info_get_text) + (duckdb_v2_error_info_handle info, const char **out_text, idx_t *out_text_length); DUCKDB_V2_ERROR (*duckdb_v2_error_info_set_code)(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR code); - DUCKDB_V2_ERROR (*duckdb_v2_error_info_set_text)(duckdb_v2_error_info_handle info, const duckdb_v2_str *text); + DUCKDB_V2_ERROR(*duckdb_v2_error_info_set_text) + (duckdb_v2_error_info_handle info, const char *text, idx_t text_length); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_id) - (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_name) - (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_text) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *text, duckdb_v2_logical_type_handle *out_type, + (duckdb_v2_factory_handle factory, const char *text, idx_t text_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_with_alias) - (duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle base_type, - const duckdb_v2_identifier_t *alias_name, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle base_type, const char *alias_name, + idx_t alias_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_attach) - (duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, const duckdb_v2_str *path, + (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, const char *path, idx_t path_length, duckdb_v2_attach_options_handle options, bool make_default, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_create) (duckdb_v2_environment_handle env, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_create_with_options) - (duckdb_v2_environment_handle env, const duckdb_v2_str *option_names, const duckdb_v2_str *option_values, - idx_t option_count, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); + (duckdb_v2_environment_handle env, const char **option_names, const idx_t *option_names_lengths, + const char **option_values, const idx_t *option_values_lengths, idx_t option_count, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_instance_destroy)(duckdb_v2_instance_handle *instance); DUCKDB_V2_ERROR(*duckdb_v2_instance_detach) - (duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR (*duckdb_v2_library_version)(duckdb_v2_str *out_version, duckdb_v2_error_info_handle *err); + (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_library_version) + (const char **out_version, idx_t *out_version_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_copy) (duckdb_v2_logical_type_handle type, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_logical_type_destroy)(duckdb_v2_logical_type_handle *type); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_id) (duckdb_v2_logical_type_handle type, DUCKDB_V2_LOGICAL_TYPE_ID *out_id, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_name) - (duckdb_v2_logical_type_handle type, duckdb_v2_identifier_t *out_name, duckdb_v2_error_info_handle *err); + (duckdb_v2_logical_type_handle type, const char **out_name, idx_t *out_name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_param) - (duckdb_v2_logical_type_handle type, idx_t index, duckdb_v2_identifier_t *out_name, + (duckdb_v2_logical_type_handle type, idx_t index, const char **out_name, idx_t *out_name_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_logical_type_get_param_count) (duckdb_v2_logical_type_handle type, idx_t *out_count, duckdb_v2_error_info_handle *err); @@ -209,17 +216,19 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_option_destroy)(duckdb_v2_option_handle *option); DUCKDB_V2_ERROR(*duckdb_v2_option_get_alias) - (duckdb_v2_option_handle option, idx_t index, duckdb_v2_identifier_t *out_alias, duckdb_v2_error_info_handle *err); + (duckdb_v2_option_handle option, idx_t index, const char **out_alias, idx_t *out_alias_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_alias_count) (duckdb_v2_option_handle option, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_default_value) (duckdb_v2_option_handle option, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_description) - (duckdb_v2_option_handle option, duckdb_v2_str *out_description, duckdb_v2_error_info_handle *err); + (duckdb_v2_option_handle option, const char **out_description, idx_t *out_description_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_name) - (duckdb_v2_option_handle option, duckdb_v2_identifier_t *out_name, duckdb_v2_error_info_handle *err); + (duckdb_v2_option_handle option, const char **out_name, idx_t *out_name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_parse_sql) - (duckdb_v2_connection_handle conn, const char *sql, bool apply_invalidation_policy, + (duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, bool apply_invalidation_policy, duckdb_v2_statement_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_result_destroy)(duckdb_v2_result_handle *result); DUCKDB_V2_ERROR(*duckdb_v2_result_drain) @@ -233,8 +242,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_result_get_statement_type) (duckdb_v2_result_handle result, DUCKDB_V2_STATEMENT_TYPE *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_result_render_box) - (duckdb_v2_result_handle *result, idx_t max_rows, idx_t max_width, idx_t max_col_width, - const duckdb_v2_str *null_value, idx_t render_mode, idx_t limit, duckdb_v2_text_sink_fn sink, void *user_data, + (duckdb_v2_result_handle *result, idx_t max_rows, idx_t max_width, idx_t max_col_width, const char *null_value, + idx_t null_value_length, idx_t render_mode, idx_t limit, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_result_step) (duckdb_v2_result_handle result, duckdb_v2_data_chunk_handle *out_chunk, DUCKDB_V2_RESULT_STEP_STATUS *out_status, @@ -244,16 +253,16 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_schema_get_count) (duckdb_v2_schema_handle schema, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_schema_get_field) - (duckdb_v2_schema_handle schema, idx_t index, duckdb_v2_identifier_t *out_name, + (duckdb_v2_schema_handle schema, idx_t index, const char **out_name, idx_t *out_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_sql_statement_destroy)(duckdb_v2_sql_statement_handle *statement); DUCKDB_V2_ERROR(*duckdb_v2_statement_bind) (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, duckdb_v2_schema_handle *out_schema, duckdb_v2_schema_handle *out_parameters, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_statement_iterator_destroy)(duckdb_v2_statement_iterator_handle *iterator); DUCKDB_V2_ERROR(*duckdb_v2_statement_iterator_next) (duckdb_v2_statement_iterator_handle iterator, duckdb_v2_sql_statement_handle *out_statement, @@ -268,13 +277,13 @@ typedef struct { (duckdb_v2_factory_handle factory, int64_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_bignum) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_bit) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_blob) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_bool) (duckdb_v2_factory_handle factory, bool in_value, duckdb_v2_value_handle *out_value, @@ -314,8 +323,9 @@ typedef struct { (duckdb_v2_factory_handle factory, int16_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_struct) - (duckdb_v2_factory_handle factory, const duckdb_v2_identifier_t *names, const duckdb_v2_value_handle *children, - idx_t field_count, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); + (duckdb_v2_factory_handle factory, const char **names, const idx_t *names_lengths, + const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_time) (duckdb_v2_factory_handle factory, int64_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); @@ -371,13 +381,13 @@ typedef struct { (duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_varchar) - (duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, duckdb_v2_value_handle *out_value, + (duckdb_v2_factory_handle factory, const char *in_value, idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_value_destroy)(duckdb_v2_value_handle *value); DUCKDB_V2_ERROR(*duckdb_v2_value_get_bigint) (duckdb_v2_value_handle value, int64_t *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_blob) - (duckdb_v2_value_handle value, duckdb_v2_str *out, duckdb_v2_error_info_handle *err); + (duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_bool) (duckdb_v2_value_handle value, bool *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_child) @@ -438,7 +448,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_value_get_uuid) (duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_varchar) - (duckdb_v2_value_handle value, duckdb_v2_str *out, duckdb_v2_error_info_handle *err); + (duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_is_null) (duckdb_v2_value_handle value, bool *out_is_null, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_to_string) @@ -482,12 +492,12 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_register_scalar_function) (duckdb_v2_connection_handle conn, duckdb_v2_scalar_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_log) - (duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + (duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, const char *log_type, idx_t log_type_length, + const char *message, idx_t message_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_scalar_function) (duckdb_v2_extension_handle extension, duckdb_v2_scalar_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_signature_add_parameter) - (duckdb_v2_function_signature_handle sig, const duckdb_v2_identifier_t *name, duckdb_v2_logical_type_handle type, + (duckdb_v2_function_signature_handle sig, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_value_handle value, DUCKDB_V2_FUNCTION_PARAMETER_KIND kind, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_signature_set_return_type) (duckdb_v2_function_signature_handle sig, duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); @@ -530,7 +540,7 @@ typedef struct { (duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_init_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_name) - (duckdb_v2_scalar_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_user_data) (duckdb_v2_scalar_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_bind_set_return_type) @@ -597,7 +607,7 @@ typedef struct { (duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_init_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_name) - (duckdb_v2_aggregate_function_handle function, const duckdb_v2_identifier_t *name, + (duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_size_callback) (duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_size_callback_fn callback, @@ -643,7 +653,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_extension_register_table_function) (duckdb_v2_extension_handle extension, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_add_result_column) - (duckdb_v2_table_function_bind_info_handle info, const duckdb_v2_identifier_t *name, + (duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_set_cardinality) (duckdb_v2_table_function_bind_info_handle info, idx_t cardinality, bool is_exact, @@ -702,7 +712,7 @@ typedef struct { (duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_local_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_name) - (duckdb_v2_table_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_table_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_progress_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_progress_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -750,7 +760,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_custom_type_set_base_type) (duckdb_v2_custom_type_handle type, duckdb_v2_logical_type_handle base_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_type_set_name) - (duckdb_v2_custom_type_handle type, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_custom_type_handle type, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_cast_function) (duckdb_v2_extension_handle extension, duckdb_v2_cast_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_custom_type) @@ -766,7 +776,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_file_open_options_set_flag) (duckdb_v2_file_open_options_handle options, DUCKDB_V2_FILE_FLAG flag, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_open_options_set_value) - (duckdb_v2_file_open_options_handle options, const duckdb_v2_str *name, duckdb_v2_value_handle value, + (duckdb_v2_file_open_options_handle options, const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_read) (duckdb_v2_file_handle file, void *buffer, idx_t buffer_size, idx_t *bytes_read, duckdb_v2_error_info_handle *err); @@ -777,7 +787,7 @@ typedef struct { DUCKDB_V2_ERROR (*duckdb_v2_file_size)(duckdb_v2_file_handle file, idx_t *size, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_file_sync)(duckdb_v2_file_handle file, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_open) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *file_path, + (duckdb_v2_file_system_handle file_system, const char *file_path, idx_t file_path_length, duckdb_v2_file_open_options_handle options, duckdb_v2_file_handle *file, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_tell) (duckdb_v2_file_handle file, idx_t *position, duckdb_v2_error_info_handle *err); @@ -790,26 +800,26 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_register_replacement_scan) (duckdb_v2_instance_handle instance, duckdb_v2_replacement_scan_handle scan, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_create) - (const duckdb_v2_identifier_t *parts, idx_t part_count, duckdb_v2_qname_handle *name, + (const char **parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_qname_destroy)(duckdb_v2_qname_handle *name); DUCKDB_V2_ERROR(*duckdb_v2_qname_equals) (duckdb_v2_qname_handle left, duckdb_v2_qname_handle right, bool *result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_get_part) - (duckdb_v2_qname_handle name, idx_t index, duckdb_v2_identifier_t *part, duckdb_v2_error_info_handle *err); + (duckdb_v2_qname_handle name, idx_t index, const char **part, idx_t *part_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_get_part_count) (duckdb_v2_qname_handle name, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_hash) (duckdb_v2_qname_handle name, uint64_t *hash, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_parse) - (const duckdb_v2_str *text, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); + (const char *text, idx_t text_length, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_render) (duckdb_v2_qname_handle name, char *out_text, idx_t out_capacity, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_add_argument) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_add_named_argument) - (duckdb_v2_replacement_scan_info_handle info, const duckdb_v2_identifier_t *name, duckdb_v2_value_handle value, + (duckdb_v2_replacement_scan_info_handle info, const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_create) (duckdb_v2_factory_handle factory, duckdb_v2_replacement_scan_handle *scan, duckdb_v2_error_info_handle *err); @@ -819,26 +829,28 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_get_user_data) (duckdb_v2_replacement_scan_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_alias) - (duckdb_v2_replacement_scan_info_handle info, const duckdb_v2_identifier_t *alias, + (duckdb_v2_replacement_scan_info_handle info, const char *alias, idx_t alias_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_callback) (duckdb_v2_replacement_scan_handle scan, duckdb_v2_replacement_scan_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_collection) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const duckdb_v2_identifier_t *column_names, idx_t column_count, duckdb_v2_error_info_handle *err); + 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_replacement_scan_set_function_name) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_qname_handle name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_subquery) - (duckdb_v2_replacement_scan_info_handle info, const duckdb_v2_str *sql, duckdb_v2_error_info_handle *err); + (duckdb_v2_replacement_scan_info_handle info, const char *sql, idx_t sql_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_user_data) (duckdb_v2_replacement_scan_handle scan, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_append) (duckdb_v2_arrow_exporter_handle exporter, duckdb_v2_data_chunk_handle *chunk, bool consume, bool flush, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_create) - (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const duckdb_v2_str *names, - idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err); + (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const char **names, + const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_arrow_exporter_destroy)(duckdb_v2_arrow_exporter_handle *exporter); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_get_schema) (duckdb_v2_arrow_exporter_handle exporter, struct ArrowSchema *out_schema, duckdb_v2_error_info_handle *err); @@ -858,7 +870,8 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_column_description_destroy)(duckdb_v2_column_description_handle *column); DUCKDB_V2_ERROR(*duckdb_v2_column_description_get_name) - (duckdb_v2_column_description_handle column, duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_column_description_handle column, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_column_description_get_type) (duckdb_v2_column_description_handle column, duckdb_v2_logical_type_handle *type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_column_description_has_default) @@ -873,17 +886,18 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_column_count) (duckdb_v2_copy_from_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_column_name) - (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_from_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_column_type) (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_file_path) - (duckdb_v2_copy_from_bind_info_handle info, duckdb_v2_str *path, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_from_bind_info_handle info, const char **path, idx_t *path_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_option_count) (duckdb_v2_copy_from_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_option_name) - (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_from_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_get_option_value) (duckdb_v2_copy_from_bind_info_handle info, idx_t index, duckdb_v2_value_handle *value, @@ -947,7 +961,7 @@ typedef struct { (duckdb_v2_factory_handle factory, duckdb_v2_copy_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_copy_function_destroy)(duckdb_v2_copy_function_handle *function); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_set_name) - (duckdb_v2_copy_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_set_user_data) (duckdb_v2_copy_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_batch_get_bind_data) @@ -970,17 +984,17 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_column_count) (duckdb_v2_copy_to_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_column_name) - (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_to_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_column_type) (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_file_path) - (duckdb_v2_copy_to_bind_info_handle info, duckdb_v2_str *path, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_to_bind_info_handle info, const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_option_count) (duckdb_v2_copy_to_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_option_name) - (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_copy_to_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_bind_get_option_value) (duckdb_v2_copy_to_bind_info_handle info, idx_t index, duckdb_v2_value_handle *value, @@ -1006,7 +1020,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_get_bind_data) (duckdb_v2_copy_to_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_get_file_path) - (duckdb_v2_copy_to_init_info_handle info, duckdb_v2_str *path, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_to_init_info_handle info, const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_get_user_data) (duckdb_v2_copy_to_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_init_set_init_data) @@ -1036,7 +1050,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_expression_constant_get_value) (duckdb_v2_expression_handle expression, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_function_get_name) - (duckdb_v2_expression_handle expression, duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_expression_handle expression, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_function_get_qname) (duckdb_v2_expression_handle expression, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_get_child) @@ -1051,14 +1065,14 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_extension_register_copy_function) (duckdb_v2_extension_handle extension, duckdb_v2_copy_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_identifier_render_quoted) - (const duckdb_v2_identifier_t *name, char *out_text, idx_t out_capacity, idx_t *out_length, + (const char *name, idx_t name_length, char *out_text, idx_t out_capacity, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_create) (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, bool require_cacheable, duckdb_v2_prepared_statement_handle *out_prepared, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_prepared_statement_destroy)(duckdb_v2_prepared_statement_handle *prepared); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute) - (duckdb_v2_prepared_statement_handle prepared, const duckdb_v2_identifier_t *parameter_names, + (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_reuses_plan) @@ -1112,10 +1126,11 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_parameter_count) (duckdb_v2_sql_statement_handle statement, idx_t *out_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_parameter_name) - (duckdb_v2_sql_statement_handle statement, idx_t index, duckdb_v2_identifier_t *out_name, + (duckdb_v2_sql_statement_handle statement, idx_t index, const char **out_name, idx_t *out_name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_text) - (duckdb_v2_sql_statement_handle statement, duckdb_v2_str *out_text, duckdb_v2_error_info_handle *err); + (duckdb_v2_sql_statement_handle statement, const char **out_text, idx_t *out_text_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_sql_statement_get_type) (duckdb_v2_sql_statement_handle statement, DUCKDB_V2_STATEMENT_TYPE *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_token_iterator_destroy)(duckdb_v2_token_iterator_handle *iterator); @@ -1125,17 +1140,17 @@ typedef struct { (duckdb_v2_token_iterator_handle iterator, DUCKDB_V2_TOKEN_TYPE *out_type, idx_t *out_start, idx_t *out_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_tokenize_sql) - (duckdb_v2_connection_handle conn, const duckdb_v2_str *sql, duckdb_v2_token_iterator_handle *out_iterator, + (duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, duckdb_v2_token_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_attach_options_create) (duckdb_v2_instance_handle instance, duckdb_v2_attach_options_handle *out_options, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_attach_options_destroy)(duckdb_v2_attach_options_handle *options); DUCKDB_V2_ERROR(*duckdb_v2_attach_options_set) - (duckdb_v2_attach_options_handle options, const duckdb_v2_identifier_t *key, const duckdb_v2_str *setting, - duckdb_v2_error_info_handle *err); + (duckdb_v2_attach_options_handle options, const char *key, idx_t key_length, const char *setting, + idx_t setting_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_set_default) - (duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_bind_data) (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_global_state) @@ -1176,7 +1191,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_partitioning_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR (*duckdb_v2_validate_utf8)(const duckdb_v2_str *text, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_validate_utf8)(const char *text, idx_t text_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_multi_file_function) (duckdb_v2_connection_handle conn, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_to_set_statistics_callback) @@ -1202,13 +1217,17 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_multi_file_function_destroy)(duckdb_v2_multi_file_function_handle *function); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_file_extension) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *extension, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *extension, idx_t extension_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_name) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_reader_type) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *reader_type, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *reader_type, idx_t reader_type_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_single_file_function) - (duckdb_v2_multi_file_function_handle function, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_multi_file_function_handle function, const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_bind_data) (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_global_state) @@ -1226,10 +1245,10 @@ typedef struct { (duckdb_v2_function_bind_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_index) - (duckdb_v2_function_bind_info_handle info, const duckdb_v2_identifier_t *name, idx_t *index, bool *found, + (duckdb_v2_function_bind_info_handle info, const char *name, idx_t name_length, idx_t *index, bool *found, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_name) - (duckdb_v2_function_bind_info_handle info, idx_t index, duckdb_v2_identifier_t *name, + (duckdb_v2_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_type) (duckdb_v2_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, @@ -1263,14 +1282,13 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_arrow_result_wait) (duckdb_v2_arrow_result_handle result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute_arrow) - (duckdb_v2_prepared_statement_handle prepared, const duckdb_v2_identifier_t *parameter_names, + (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute_arrow) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, - duckdb_v2_error_info_handle *err); + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_stats_callback) (duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_stats_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1335,8 +1353,8 @@ typedef struct { (duckdb_v2_table_function_get_bind_info_info_handle info, idx_t column_index, const idx_t *child_path, idx_t child_path_length, duckdb_v2_value_handle identifier, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_get_bind_info_set_option) - (duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_str *key, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); + (duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_get_bind_info_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_get_bind_info_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1349,21 +1367,21 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_set_bind_data) (duckdb_v2_scalar_function_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_get_option_value) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, duckdb_v2_value_handle *out_value, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_value_handle *out_value, DUCKDB_V2_SETTING_SCOPE *out_scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_set_option_text) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, const duckdb_v2_str *setting, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, const char *setting, idx_t setting_length, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_config_set_option_value) - (duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, duckdb_v2_value_handle value, + (duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_value_handle value, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_get_config) (duckdb_v2_connection_handle conn, duckdb_v2_config_handle *out_config, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_get_file_system) (duckdb_v2_connection_handle conn, duckdb_v2_file_system_handle *file_system, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_log) - (duckdb_v2_connection_handle conn, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + (duckdb_v2_connection_handle conn, DUCKDB_V2_LOG_LEVEL level, const char *log_type, idx_t log_type_length, + const char *message, idx_t message_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_get_config) (duckdb_v2_context_handle ctx, duckdb_v2_config_handle *out_config, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_get_config) @@ -1371,8 +1389,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_get_file_system) (duckdb_v2_instance_handle instance, duckdb_v2_file_system_handle *file_system, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_log) - (duckdb_v2_instance_handle instance, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + (duckdb_v2_instance_handle instance, DUCKDB_V2_LOG_LEVEL level, const char *log_type, idx_t log_type_length, + const char *message, idx_t message_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_get_default_scope) (duckdb_v2_option_handle option, DUCKDB_V2_SETTING_SCOPE *out_scope, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_option_supports_scope) @@ -1389,12 +1407,14 @@ typedef struct { (duckdb_v2_factory_handle factory, const duckdb_v2_logical_type_handle *types, idx_t type_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_docs_add_category) - (duckdb_v2_function_docs_handle docs, const duckdb_v2_str *category, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_function_docs_add_example) - (duckdb_v2_function_docs_handle docs, const duckdb_v2_str *title, const duckdb_v2_str *example, + (duckdb_v2_function_docs_handle docs, const char *category, idx_t category_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_function_docs_add_example) + (duckdb_v2_function_docs_handle docs, const char *title, idx_t title_length, const char *example, + idx_t example_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_docs_set_description) - (duckdb_v2_function_docs_handle docs, const duckdb_v2_str *description, duckdb_v2_error_info_handle *err); + (duckdb_v2_function_docs_handle docs, const char *description, idx_t description_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_pragma_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_pragma_function_destroy)(duckdb_v2_pragma_function_handle *function); @@ -1404,12 +1424,13 @@ typedef struct { (duckdb_v2_pragma_function_handle function, duckdb_v2_function_signature_handle *sig, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_query_set_query) - (duckdb_v2_pragma_function_query_info_handle info, const duckdb_v2_str *query, duckdb_v2_error_info_handle *err); + (duckdb_v2_pragma_function_query_info_handle info, const char *query, idx_t query_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_set_exec_callback) (duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_exec_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_set_name) - (duckdb_v2_pragma_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_pragma_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_pragma_function_set_query_callback) (duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_query_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1429,9 +1450,10 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_default_value) (duckdb_v2_custom_option_handle option, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_description) - (duckdb_v2_custom_option_handle option, const duckdb_v2_str *description, duckdb_v2_error_info_handle *err); + (duckdb_v2_custom_option_handle option, const char *description, idx_t description_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_name) - (duckdb_v2_custom_option_handle option, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_custom_option_handle option, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_custom_option_set_supports_scope) (duckdb_v2_custom_option_handle option, DUCKDB_V2_SETTING_SCOPE scope, bool supported, duckdb_v2_error_info_handle *err); @@ -1459,13 +1481,13 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_extension_register_macro_function) (duckdb_v2_extension_handle extension, duckdb_v2_macro_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_exists) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, bool *out_exists, + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, bool *out_exists, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_expand) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, duckdb_v2_text_sink_fn sink, void *user_data, - duckdb_v2_error_info_handle *err); + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, duckdb_v2_text_sink_fn sink, + void *user_data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_is_remote) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, bool *out_is_remote, + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, bool *out_is_remote, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_register_log_sink) (duckdb_v2_instance_handle instance, duckdb_v2_log_sink_handle sink, duckdb_v2_error_info_handle *err); @@ -1475,7 +1497,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_flush_callback) (duckdb_v2_log_sink_handle sink, duckdb_v2_log_sink_flush_callback_fn callback, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_name) - (duckdb_v2_log_sink_handle sink, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_log_sink_handle sink, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_user_data) (duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_log_sink_set_write_callback) @@ -1498,9 +1520,9 @@ typedef struct { (duckdb_v2_macro_function_handle function, duckdb_v2_function_signature_handle *sig, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_macro_function_set_body) - (duckdb_v2_macro_function_handle function, const duckdb_v2_str *body, duckdb_v2_error_info_handle *err); + (duckdb_v2_macro_function_handle function, const char *body, idx_t body_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_macro_function_set_name) - (duckdb_v2_macro_function_handle function, const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_macro_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_vector_cast) (duckdb_v2_factory_handle factory, duckdb_v2_vector_handle source, duckdb_v2_vector_handle target, DUCKDB_V2_CAST_MODE mode, bool *out_converted, duckdb_v2_error_info_handle *cast_err, @@ -1510,16 +1532,17 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_get_query_metrics) (duckdb_v2_connection_handle conn, duckdb_v2_query_metrics_handle *metrics, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_set_file_extension) - (duckdb_v2_copy_function_handle function, const duckdb_v2_str *extension, duckdb_v2_error_info_handle *err); + (duckdb_v2_copy_function_handle function, const char *extension, idx_t extension_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_data_chunk_clear)(duckdb_v2_data_chunk_handle chunk, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_glob) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *pattern, + (duckdb_v2_file_system_handle file_system, const char *pattern, idx_t pattern_length, duckdb_v2_file_system_path_glob_callback_fn callback, void *user_data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_move) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *source, const duckdb_v2_str *target, - duckdb_v2_error_info_handle *err); + (duckdb_v2_file_system_handle file_system, const char *source, idx_t source_length, const char *target, + idx_t target_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_file_system_path_remove) - (duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, bool *out_removed, + (duckdb_v2_file_system_handle file_system, const char *path, idx_t path_length, bool *out_removed, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_query_metrics_destroy)(duckdb_v2_query_metrics_handle *metrics); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_get_root) @@ -1531,21 +1554,22 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_child_count) (duckdb_v2_query_metrics_node_handle node, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric) - (duckdb_v2_query_metrics_node_handle node, const duckdb_v2_str *name, duckdb_v2_value_handle *value, bool *present, - duckdb_v2_error_info_handle *err); + (duckdb_v2_query_metrics_node_handle node, const char *name, idx_t name_length, duckdb_v2_value_handle *value, + bool *present, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric_count) (duckdb_v2_query_metrics_node_handle node, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric_name) - (duckdb_v2_query_metrics_node_handle node, idx_t index, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_query_metrics_node_handle node, idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_metric_value) (duckdb_v2_query_metrics_node_handle node, idx_t index, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_query_metrics_node_get_name) - (duckdb_v2_query_metrics_node_handle node, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); + (duckdb_v2_query_metrics_node_handle node, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_add_collection) - (duckdb_v2_sql_statement_handle statement, const duckdb_v2_identifier_t *name, - duckdb_v2_column_data_collection_handle collection, const duckdb_v2_identifier_t *column_names, idx_t column_count, - duckdb_v2_error_info_handle *err); + (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); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -3576,7 +3600,8 @@ typedef struct { // called before it succeeds, so a failure returns without touching the error slot: the library has already recorded // why get_api refused, and reports that. #define DUCKDB_EXTENSION_API_INIT(input, minimum_api_version) \ - duckdb_ext_api_v2 *res = (duckdb_ext_api_v2 *)(input)->get_api((input)->extension, minimum_api_version); \ + duckdb_ext_api_v2 *res = \ + (duckdb_ext_api_v2 *)(input)->get_api((input)->extension, minimum_api_version, strlen(minimum_api_version)); \ if (!res) { \ return; \ }; \ diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index dba8df656..2ae65767b 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -212,8 +212,6 @@ typedef enum DUCKDB_V2_ORDER_PRESERVATION { /* --- Struct forward declarations for common --- */ -typedef struct duckdb_v2_str duckdb_v2_str; - typedef struct duckdb_v2_bytes duckdb_v2_bytes; typedef struct duckdb_v2_opaque duckdb_v2_opaque; @@ -384,16 +382,6 @@ typedef duckdb_v2_bytes duckdb_v2_bit_t; //! BIGNUM storage. Decode via `duckdb_v2_bignum_decode()`. typedef duckdb_v2_bytes duckdb_v2_bignum_t; -/*! - * A borrowed name view with the same layout as str, marking a string DuckDB treats as a SQL identifier: one matched - * case-insensitively. Compare two identifiers case-insensitively rather than byte for byte, and render one into SQL - * through the identifier-quoting entry point rather than embedding it raw. The catalog preserves casing; some - * registries (config settings) canonicalize to lowercase. - * - * An identifier passed into the API must be valid UTF-8; otherwise the call fails with `ERROR_INPUT_INVALID`. - */ -typedef duckdb_v2_str duckdb_v2_identifier_t; - /* --- Constants for common --- */ //! Inline cutoff for `bytes` storage: a value of at most this many bytes is stored inline. @@ -404,10 +392,10 @@ typedef duckdb_v2_str duckdb_v2_identifier_t; /*! * Receives text produced by DuckDB * - * Invoked exactly once per producing call, with the complete text in a single view. + * Invoked exactly once per producing call, with the complete text in a single call. * - * The view is borrowed for the duration of the call only. Copy what you need before returning, and do not retain `text` - * or `text->ptr`. The bytes are NOT guaranteed to be null-terminated. + * The text is borrowed for the duration of the call only. Copy what you need before returning, and do not retain + * `text`. The bytes are NOT guaranteed to be null-terminated. * * `err` is a live error slot, never NULL. Populate it with `duckdb_v2_error_info_set_code()` / * `duckdb_v2_error_info_set_text()` to signal failure to DuckDB. Do not destroy it yourself. @@ -415,7 +403,8 @@ typedef duckdb_v2_str duckdb_v2_identifier_t; * The sink runs inside DuckDB's call frame: it must not throw or unwind across the boundary, and it must not re-enter * the API on the handle being operated on. */ -typedef void (*duckdb_v2_text_sink_fn)(const duckdb_v2_str *text, void *user_data, duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_text_sink_fn)(const char *text, idx_t text_length, void *user_data, + duckdb_v2_error_info_handle *err); /*! * Compares two caller-defined resources for equality. @@ -443,25 +432,6 @@ typedef void (*duckdb_v2_opaque_destroy_fn)(void *data); /* --- Struct definitions for common --- */ -/*! - * A borrowed, length-delimited string view: `ptr` points at `len` bytes of character data. The bytes are NOT guaranteed - * to be null-terminated and may contain interior null bytes, so always honor `len` rather than scanning for a - * terminator. The view never owns its bytes; the function that produced it documents how long they live (typically - * "valid until the owning handle is destroyed"). `{NULL, 0}` is the canonical empty view, and `ptr` must not be - * dereferenced when `len` is 0. Not to be confused with `bytes`, the transparent 16-byte *storage* format for a - * variable-size value in a vector. - * - * Functions take an input view as a `const str *`, which must not be NULL; a NULL pointer, or a view whose `ptr` is - * NULL while `len` is nonzero, fails with ERROR_INPUT_INVALID. Point at a `{NULL, 0}` view to pass an empty string. - * - * Text inputs, such as VARCHAR values and names, must contain valid UTF-8. The caller is responsible for ensuring this; - * API functions do not necessarily validate the input. Binary inputs, such as BLOB values, do not require valid UTF-8. - */ -struct duckdb_v2_str { - const char *ptr; - idx_t len; -}; - /*! * 16-byte storage for a variable-size, byte-backed value: VARCHAR, BLOB, BIT, or BIGNUM. The bytes are inlined when the * length is at most BYTES_INLINE_LENGTH, in value.inlined.inlined; otherwise value.pointer.ptr holds them and @@ -1649,15 +1619,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_config(duckdb_v2_context_hand * * @param config The config to read from. * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param out_value Receives the value, typed as the option. Owned by the caller. * @param out_scope Receives the scope the value came from. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_handle config, - const duckdb_v2_identifier_t *name, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_handle config, const char *name, + idx_t name_length, duckdb_v2_value_handle *out_value, DUCKDB_V2_SETTING_SCOPE *out_scope, duckdb_v2_error_info_handle *err); #endif @@ -1680,15 +1651,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_ * * @param config The config to write to. * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param value The value, cast to the option's type as SQL `SET` does. Borrowed. * @param scope Target scope: DEFAULT, GLOBAL, or SESSION. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_handle config, - const duckdb_v2_identifier_t *name, - duckdb_v2_value_handle value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_handle config, const char *name, + idx_t name_length, duckdb_v2_value_handle value, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err); #endif @@ -1706,16 +1678,19 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_ * * @param config The config to write to. * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param setting The setting, in the textual form SQL `SET` accepts. + * @param setting_length The length of `setting` in bytes. `setting` need not be null-terminated and may be NULL only + * when this is 0. * @param scope Target scope: DEFAULT, GLOBAL, or SESSION. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_handle config, - const duckdb_v2_identifier_t *name, - const duckdb_v2_str *setting, - DUCKDB_V2_SETTING_SCOPE scope, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_handle config, const char *name, + idx_t name_length, const char *setting, + idx_t setting_length, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err); #endif @@ -1733,14 +1708,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_h * * @param config The config whose instance registered the options. * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param out_option Receives the option descriptor. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_name(duckdb_v2_config_handle config, - const duckdb_v2_identifier_t *name, - duckdb_v2_option_handle *out_option, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_name(duckdb_v2_config_handle config, const char *name, + idx_t name_length, duckdb_v2_option_handle *out_option, duckdb_v2_error_info_handle *err); #endif @@ -1814,13 +1790,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_destroy(duckdb_v2_option_handle *o * - unstable: v2.0.0 * * @param option The option. - * @param out_name Receives a borrowed view of the option name. Valid until the option is destroyed. + * @param out_name Receives a borrowed pointer to the option name. Valid until the option is destroyed. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_name(duckdb_v2_option_handle option, duckdb_v2_identifier_t *out_name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_name(duckdb_v2_option_handle option, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -1851,13 +1829,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_default_value(duckdb_v2_option * - unstable: v2.0.0 * * @param option The option. - * @param out_description Receives a borrowed view of the description. Valid until the option is destroyed. + * @param out_description Receives a borrowed pointer to the description. Valid until the option is destroyed. + * @param out_description_length Receives the length of `*out_description` in bytes. `*out_description` is not + * guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_description(duckdb_v2_option_handle option, - duckdb_v2_str *out_description, + const char **out_description, + idx_t *out_description_length, duckdb_v2_error_info_handle *err); #endif @@ -1931,13 +1912,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_alias_count(duckdb_v2_option_h * * @param option The option. * @param index The alias index, in [0, alias_count). - * @param out_alias Receives a borrowed view of the alias. Valid until the option is destroyed. + * @param out_alias Receives a borrowed pointer to the alias. Valid until the option is destroyed. + * @param out_alias_length Receives the length of `*out_alias` in bytes. `*out_alias` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_alias(duckdb_v2_option_handle option, idx_t index, - duckdb_v2_identifier_t *out_alias, + const char **out_alias, idx_t *out_alias_length, duckdb_v2_error_info_handle *err); #endif @@ -2113,13 +2096,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_create(duckdb_v2_factory_hand * * @param type The type to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_set_name(duckdb_v2_custom_type_handle type, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_set_name(duckdb_v2_custom_type_handle type, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -2493,18 +2477,20 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_code(duckdb_v2_error_info_ /*! * Retrieves the error text associated with an error info handle. * - * Returns a borrowed pointer to the info's null-terminated error text. The pointer is owned by DuckDB and is valid - * until the info is destroyed or a new text is set; callers must not free it, and must not read it once the info has - * been destroyed. + * Returns a borrowed view of the info's error text. The text is owned by DuckDB and is valid until the info is + * destroyed or a new text is set; callers must not free it, and must not read it once the info has been destroyed. * * history: * - unstable: v2.0.0 * * @param info The error info handle to query. - * @param out_text Receives a borrowed view of the text. Owned by DuckDB; valid until the info handle is destroyed. + * @param out_text Receives a borrowed pointer to the text. Owned by DuckDB; valid until the info handle is destroyed. + * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be + * null-terminated. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_handle info, duckdb_v2_str *out_text); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_handle info, const char **out_text, + idx_t *out_text_length); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -2514,19 +2500,21 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_ * Returns a borrowed view of the same text error_info_get_text reports, minus the leading " Error: " prefix. This * is the authoritative unprefixed body: the API exposes no type name, so the prefix cannot be reconstructed and the * body cannot be derived from error_info_get_text. Unprefixed does not mean plain — the body keeps whatever form it was - * rendered in (a LINE/caret block by default, JSON under errors_as_json). `{NULL, 0}` when there is no text. The - * pointer is owned by DuckDB and valid until the info handle is destroyed. + * rendered in (a LINE/caret block by default, JSON under errors_as_json). NULL with a zero length when there is no + * text. The text is owned by DuckDB and valid until the info handle is destroyed. * * history: * - unstable: v2.0.0 * * @param info The error info handle to query. - * @param out_raw_text Receives a borrowed view of the raw text. Owned by DuckDB; valid until the info handle is + * @param out_raw_text Receives a borrowed pointer to the raw text. Owned by DuckDB; valid until the info handle is * destroyed. + * @param out_raw_text_length Receives the length of `*out_raw_text` in bytes. `*out_raw_text` is not guaranteed to be + * null-terminated. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_raw_text(duckdb_v2_error_info_handle info, - duckdb_v2_str *out_raw_text); + const char **out_raw_text, idx_t *out_raw_text_length); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -2558,9 +2546,12 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_code(duckdb_v2_error_info_ * * @param info The error info handle to set. On success, updated with the provided text. * @param text The error text to set in the info. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_text(duckdb_v2_error_info_handle info, const duckdb_v2_str *text); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_text(duckdb_v2_error_info_handle info, const char *text, + idx_t text_length); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -2606,7 +2597,8 @@ typedef struct duckdb_v2_extension_input duckdb_v2_extension_input; * must return without touching the error slot. Statically linked extensions resolve DuckDB's symbols at link time and * never call it, so for those the field is NULL. */ -typedef const void *(*duckdb_v2_extension_get_api_fn)(duckdb_v2_extension_handle extension, const char *version); +typedef const void *(*duckdb_v2_extension_get_api_fn)(duckdb_v2_extension_handle extension, const char *version, + idx_t version_length); /* --- Functions for extension --- */ @@ -2818,7 +2810,7 @@ typedef struct _duckdb_v2_file { * through `err`, a live slot that must not be destroyed, to stop the glob: `duckdb_v2_file_system_path_glob()` then * fails with that error. The callback must not throw or unwind across the boundary. */ -typedef void (*duckdb_v2_file_system_path_glob_callback_fn)(const duckdb_v2_str *path, void *user_data, +typedef void (*duckdb_v2_file_system_path_glob_callback_fn)(const char *path, idx_t path_length, void *user_data, duckdb_v2_error_info_handle *err); /* --- Functions for file system --- */ @@ -2956,13 +2948,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_flag(duckdb_v2_file * * @param options The options to set the value on. * @param name The name of the value. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. * @param value The value. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_value(duckdb_v2_file_open_options_handle options, - const duckdb_v2_str *name, + const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif @@ -3006,14 +3000,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_destroy(duckdb_v2_file_ * * @param file_system The file system to open the file through. * @param file_path The path of the file to open. Borrowed for the call only. + * @param file_path_length The length of `file_path` in bytes. `file_path` need not be null-terminated and may be NULL + * only when this is 0. * @param options How to open the file. Borrowed for the call only, and reusable across opens. * @param file On success, receives the open file. Owned by the caller; destroy via `duckdb_v2_file_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *file_path, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_system, const char *file_path, + idx_t file_path_length, duckdb_v2_file_open_options_handle options, duckdb_v2_file_handle *file, duckdb_v2_error_info_handle *err); #endif @@ -3030,13 +3026,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_ha * * @param file_system The file system to ask. * @param path The path to check. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. * @param out_exists Receives whether a file exists at the path. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_exists(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *path, bool *out_exists, + const char *path, idx_t path_length, bool *out_exists, duckdb_v2_error_info_handle *err); #endif @@ -3052,13 +3050,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_exists(duckdb_v2_file_sy * * @param file_system The file system the path is meant for. * @param path The path to check. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. * @param out_is_remote Receives whether the path names a remote file. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *path, bool *out_is_remote, + const char *path, idx_t path_length, + bool *out_is_remote, duckdb_v2_error_info_handle *err); #endif @@ -3074,6 +3075,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file * * @param file_system The file system whose settings expand the path. * @param path The path to expand. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. * @param sink Receives the expanded path in a single call. Borrowed for the duration of that call; see text_sink for * the full contract. * @param user_data Opaque pointer passed through to sink untouched. May be NULL. @@ -3082,8 +3085,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *path, duckdb_v2_text_sink_fn sink, - void *user_data, duckdb_v2_error_info_handle *err); + const char *path, idx_t path_length, + duckdb_v2_text_sink_fn sink, void *user_data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3101,6 +3105,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_sy * * @param file_system The file system to glob in. * @param pattern The glob pattern. Borrowed for the call only. + * @param pattern_length The length of `pattern` in bytes. `pattern` need not be null-terminated and may be NULL only + * when this is 0. * @param callback Invoked once per matched path. * @param user_data Opaque pointer passed through to `callback` untouched. May be NULL. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via @@ -3108,7 +3114,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_sy * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *pattern, + const char *pattern, idx_t pattern_length, duckdb_v2_file_system_path_glob_callback_fn callback, void *user_data, duckdb_v2_error_info_handle *err); #endif @@ -3126,13 +3132,18 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_syst * * @param file_system The file system to move the file in. * @param source The path of the file to move. Borrowed for the call only. + * @param source_length The length of `source` in bytes. `source` need not be null-terminated and may be NULL only when + * this is 0. * @param target The path to move the file to. Borrowed for the call only. + * @param target_length The length of `target` in bytes. `target` need not be null-terminated and may be NULL only when + * this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_move(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *source, const duckdb_v2_str *target, + const char *source, idx_t source_length, + const char *target, idx_t target_length, duckdb_v2_error_info_handle *err); #endif @@ -3148,13 +3159,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_move(duckdb_v2_file_syst * * @param file_system The file system to remove the file from. * @param path The path of the file to remove. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. * @param out_removed Optional. Receives whether a file was removed. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_remove(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *path, bool *out_removed, + const char *path, idx_t path_length, bool *out_removed, duckdb_v2_error_info_handle *err); #endif @@ -3531,13 +3544,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_value(duckdb_v2_fun * * @param info The bind info handle. * @param index The index of the argument. - * @param name Receives a borrowed view of the argument name. Valid only for the duration of the callback. + * @param name Receives a borrowed pointer to the argument name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_name(duckdb_v2_function_bind_info_handle info, idx_t index, - duckdb_v2_identifier_t *name, + const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -3556,6 +3570,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_name(duckdb_v2_func * * @param info The bind info handle. * @param name The name to look up. Borrowed for the call only. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param index Receives the index of the argument, if found. * @param found Receives whether the call has an argument of that name. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via @@ -3563,7 +3579,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_name(duckdb_v2_func * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_index(duckdb_v2_function_bind_info_handle info, - const duckdb_v2_identifier_t *name, idx_t *index, + const char *name, idx_t name_length, idx_t *index, bool *found, duckdb_v2_error_info_handle *err); #endif @@ -3607,12 +3623,14 @@ typedef struct _duckdb_v2_function_docs { * * @param docs The documentation to set the description of. * @param description The description to set. Borrowed and copied. + * @param description_length The length of `description` in bytes. `description` need not be null-terminated and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_docs_set_description(duckdb_v2_function_docs_handle docs, - const duckdb_v2_str *description, + const char *description, idx_t description_length, duckdb_v2_error_info_handle *err); #endif @@ -3626,15 +3644,19 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_docs_set_description(duckdb_v2_f * - unstable: v2.0.0 * * @param docs The documentation to add the example to. - * @param title Optional. The title of the example; NULL or an empty view for none. Borrowed and copied. + * @param title Optional. The title of the example; NULL or empty for none. Borrowed and copied. + * @param title_length The length of `title` in bytes. `title` need not be null-terminated and may be NULL only when + * this is 0. * @param example The example, e.g. a SQL expression calling the function. Borrowed and copied. + * @param example_length The length of `example` in bytes. `example` need not be null-terminated and may be NULL only + * when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_docs_add_example(duckdb_v2_function_docs_handle docs, - const duckdb_v2_str *title, - const duckdb_v2_str *example, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_docs_add_example(duckdb_v2_function_docs_handle docs, const char *title, + idx_t title_length, const char *example, + idx_t example_length, duckdb_v2_error_info_handle *err); #endif @@ -3649,12 +3671,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_docs_add_example(duckdb_v2_funct * * @param docs The documentation to add the category to. * @param category The category. Borrowed and copied. + * @param category_length The length of `category` in bytes. `category` need not be null-terminated and may be NULL only + * when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_docs_add_category(duckdb_v2_function_docs_handle docs, - const duckdb_v2_str *category, + const char *category, idx_t category_length, duckdb_v2_error_info_handle *err); #endif @@ -3730,6 +3754,8 @@ typedef struct _duckdb_v2_function_signature { * * @param sig The signature to configure. * @param name The parameter name. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param type The parameter type. ANY accepts an argument of any type without casting it. Borrowed and copied. * @param value Optional default value, borrowed and copied. Will be cast to the parameter type. * @param kind How a caller passes the argument for the parameter. @@ -3738,7 +3764,7 @@ typedef struct _duckdb_v2_function_signature { * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_signature_add_parameter( - duckdb_v2_function_signature_handle sig, const duckdb_v2_identifier_t *name, duckdb_v2_logical_type_handle type, + duckdb_v2_function_signature_handle sig, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_value_handle value, DUCKDB_V2_FUNCTION_PARAMETER_KIND kind, duckdb_v2_error_info_handle *err); #endif @@ -3797,10 +3823,18 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_signature_set_return_type(duckdb * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C * string. * + * DuckDB treats names such as catalog entries, columns and parameters as SQL identifiers, matched case-insensitively: + * compare two identifiers case-insensitively rather than byte for byte, and render one into SQL through this function + * rather than embedding it raw. The catalog preserves casing; some registries (config settings) canonicalize to + * lowercase. An identifier passed into the API must be valid UTF-8; otherwise the call fails with + * `ERROR_INPUT_INVALID`. + * * history: * - unstable: v2.0.0 * * @param name The name to render. Borrowed for the call only. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param out_text Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required * length in out_length. * @param out_capacity Bytes available in out_text, terminator included. Ignored when out_text is NULL. @@ -3810,7 +3844,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_function_signature_set_return_type(duckdb * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_identifier_render_quoted(const duckdb_v2_identifier_t *name, char *out_text, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_identifier_render_quoted(const char *name, idx_t name_length, char *out_text, idx_t out_capacity, idx_t *out_length, duckdb_v2_error_info_handle *err); #endif @@ -3886,8 +3920,12 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_create(duckdb_v2_environment_han * @param env The environment. * @param option_names Optional. An array of option_count option names (canonical or alias). Pass NULL when option_count * is 0. + * @param option_names_lengths Byte lengths of the entries in `option_names`; element i is the length of + * `option_names[i]`. May be NULL only when `option_names` is NULL. * @param option_values Optional. An array of option_count values, parallel to option_names, in the textual form SQL * `SET` accepts. Pass NULL when option_count is 0. + * @param option_values_lengths Byte lengths of the entries in `option_values`; element i is the length of + * `option_values[i]`. May be NULL only when `option_values` is NULL. * @param option_count The number of startup options. * @param out_instance Receives the new instance handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via @@ -3895,8 +3933,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_create(duckdb_v2_environment_han * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options( - duckdb_v2_environment_handle env, const duckdb_v2_str *option_names, const duckdb_v2_str *option_values, - idx_t option_count, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); + duckdb_v2_environment_handle env, const char **option_names, const idx_t *option_names_lengths, + const char **option_values, const idx_t *option_values_lengths, idx_t option_count, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3943,7 +3982,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_destroy(duckdb_v2_instance_handl * @param instance The instance handle. * @param name Optional. The name to attach under; null or an empty view for the name derived from the path. Borrowed * and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param path Path to the database file, or `:memory:` / an empty view for an in-memory database. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. * @param options Optional attach options created from `instance`, or null to attach with defaults under the derived * name. * @param make_default Whether to make the attached database the default for connections created afterwards. @@ -3951,8 +3994,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_destroy(duckdb_v2_instance_handl * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_attach(duckdb_v2_instance_handle instance, - const duckdb_v2_identifier_t *name, const duckdb_v2_str *path, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_attach(duckdb_v2_instance_handle instance, const char *name, + idx_t name_length, const char *path, idx_t path_length, duckdb_v2_attach_options_handle options, bool make_default, duckdb_v2_error_info_handle *err); #endif @@ -3972,13 +4015,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_attach(duckdb_v2_instance_handle * * @param instance The instance handle. * @param name The name the database is attached under. Borrowed. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_detach(duckdb_v2_instance_handle instance, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_detach(duckdb_v2_instance_handle instance, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3997,13 +4041,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_detach(duckdb_v2_instance_handle * * @param instance The instance handle. * @param name The name the database is attached under. Borrowed. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_set_default(duckdb_v2_instance_handle instance, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_set_default(duckdb_v2_instance_handle instance, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -4042,14 +4087,17 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_attach_options_create(duckdb_v2_instance_ * * @param options The attach options. * @param key The option name, e.g. READ_ONLY. + * @param key_length The length of `key` in bytes. `key` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param setting The option value, in the textual form a quoted SQL literal would carry. + * @param setting_length The length of `setting` in bytes. `setting` need not be null-terminated and may be NULL only + * when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_attach_options_set(duckdb_v2_attach_options_handle options, - const duckdb_v2_identifier_t *key, - const duckdb_v2_str *setting, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_attach_options_set(duckdb_v2_attach_options_handle options, const char *key, + idx_t key_length, const char *setting, idx_t setting_length, duckdb_v2_error_info_handle *err); #endif @@ -4076,11 +4124,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_attach_options_destroy(duckdb_v2_attach_o * - unstable: v2.0.0 * * @param out_version The version string. + * @param out_version_length Receives the length of `*out_version` in bytes. `*out_version` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_library_version(duckdb_v2_str *out_version, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_library_version(const char **out_version, idx_t *out_version_length, + duckdb_v2_error_info_handle *err); #endif /* --- Struct definitions for instance --- */ @@ -4141,13 +4192,17 @@ typedef enum DUCKDB_V2_LOG_LEVEL { * @param ctx The context to log through. * @param level Severity of the message. * @param log_type The log type to record under, matched case-sensitively. Empty selects the default type. + * @param log_type_length The length of `log_type` in bytes. `log_type` need not be null-terminated and may be NULL only + * when this is 0. * @param message The message body. Borrowed for the call only. + * @param message_length The length of `message` in bytes. `message` need not be null-terminated and may be NULL only + * when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_log(duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, - const duckdb_v2_str *log_type, const duckdb_v2_str *message, - duckdb_v2_error_info_handle *err); + const char *log_type, idx_t log_type_length, const char *message, + idx_t message_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -4165,13 +4220,17 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_log(duckdb_v2_context_handle ctx, * @param instance The instance to log through. * @param level Severity of the message. * @param log_type The log type to record under, matched case-sensitively. Empty selects the default type. + * @param log_type_length The length of `log_type` in bytes. `log_type` need not be null-terminated and may be NULL only + * when this is 0. * @param message The message body. Borrowed for the call only. + * @param message_length The length of `message` in bytes. `message` need not be null-terminated and may be NULL only + * when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_log(duckdb_v2_instance_handle instance, DUCKDB_V2_LOG_LEVEL level, - const duckdb_v2_str *log_type, const duckdb_v2_str *message, - duckdb_v2_error_info_handle *err); + const char *log_type, idx_t log_type_length, const char *message, + idx_t message_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -4189,13 +4248,17 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_log(duckdb_v2_instance_handle in * @param conn The connection to log through. * @param level Severity of the message. * @param log_type The log type to record under, matched case-sensitively. Empty selects the default type. + * @param log_type_length The length of `log_type` in bytes. `log_type` need not be null-terminated and may be NULL only + * when this is 0. * @param message The message body. Borrowed for the call only. + * @param message_length The length of `message` in bytes. `message` need not be null-terminated and may be NULL only + * when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_log(duckdb_v2_connection_handle conn, DUCKDB_V2_LOG_LEVEL level, - const duckdb_v2_str *log_type, const duckdb_v2_str *message, - duckdb_v2_error_info_handle *err); + const char *log_type, idx_t log_type_length, const char *message, + idx_t message_length, duckdb_v2_error_info_handle *err); #endif /* --- Struct definitions for logging --- */ @@ -4240,12 +4303,14 @@ typedef struct _duckdb_v2_qname { * - unstable: v2.0.0 * * @param text The name text to parse. Borrowed for the call only. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. * @param name On success, receives the qualified name. Owned by the caller; destroy via `duckdb_v2_qname_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_parse(const duckdb_v2_str *text, duckdb_v2_qname_handle *name, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_parse(const char *text, idx_t text_length, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); #endif @@ -4261,14 +4326,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_parse(const duckdb_v2_str *text, du * history: * - unstable: v2.0.0 * - * @param parts An array of `part_count` non-empty identifier views, outermost first. + * @param parts An array of `part_count` non-empty identifiers, outermost first. + * @param parts_lengths Byte lengths of the entries in `parts`; element i is the length of `parts[i]`. May be NULL only + * when `parts` is NULL. * @param part_count The number of parts, between one and three. * @param name On success, receives the qualified name. Owned by the caller; destroy via `duckdb_v2_qname_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_create(const duckdb_v2_identifier_t *parts, idx_t part_count, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_create(const char **parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); #endif @@ -4305,13 +4372,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_get_part_count(duckdb_v2_qname_hand * * @param name The qualified name. * @param index Zero-based part index. - * @param part Receives a borrowed view of the part, valid until the qualified name is destroyed. + * @param part Receives a borrowed pointer to the part, valid until the qualified name is destroyed. + * @param part_length Receives the length of `*part` in bytes. `*part` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_get_part(duckdb_v2_qname_handle name, idx_t index, - duckdb_v2_identifier_t *part, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_get_part(duckdb_v2_qname_handle name, idx_t index, const char **part, + idx_t *part_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -4516,13 +4584,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_get_root(duckdb_v2_query_me * - unstable: v2.0.0 * * @param node The node. - * @param name Receives a borrowed view of the name. Valid until the snapshot is destroyed. + * @param name Receives a borrowed pointer to the name. Valid until the snapshot is destroyed. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_name(duckdb_v2_query_metrics_node_handle node, - duckdb_v2_str *name, + const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -4594,13 +4663,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_count(duckd * * @param node The node. * @param index Zero-based metric index. - * @param name Receives a borrowed view of the name. Valid until the snapshot is destroyed. + * @param name Receives a borrowed pointer to the name. Valid until the snapshot is destroyed. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_name(duckdb_v2_query_metrics_node_handle node, - idx_t index, duckdb_v2_str *name, + idx_t index, const char **name, + idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -4634,6 +4705,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_value(duckd * * @param node The node. * @param name The name of the metric, matched exactly. Borrowed for the call only. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. * @param value Receives the owned value, if present. Destroy via `duckdb_v2_value_destroy()`. * @param present Receives whether the node carries the metric. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via @@ -4641,7 +4714,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_value(duckd * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric(duckdb_v2_query_metrics_node_handle node, - const duckdb_v2_str *name, + const char *name, idx_t name_length, duckdb_v2_value_handle *value, bool *present, duckdb_v2_error_info_handle *err); #endif @@ -4716,13 +4789,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_schema_get_count(duckdb_v2_schema_handle * * @param schema The schema. * @param index Zero-based field index. - * @param out_name Receives a borrowed view of the field name. Valid until the schema is destroyed. + * @param out_name Receives a borrowed pointer to the field name. Valid until the schema is destroyed. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. * @param out_type Receives a borrowed field type. Valid until the schema is destroyed; do not destroy it. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_schema_get_field(duckdb_v2_schema_handle schema, idx_t index, - duckdb_v2_identifier_t *out_name, + const char **out_name, idx_t *out_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif @@ -4925,12 +5000,15 @@ typedef struct _duckdb_v2_token_iterator { * - unstable: v2.0.0 * * @param conn The connection supplying the grammar. - * @param sql The SQL text. Borrowed for the call only; may contain interior null bytes. {NULL, 0} is the empty input. + * @param sql The SQL text. Borrowed for the call only; may contain interior null bytes. NULL with a zero length is the + * empty input. + * @param sql_length The length of `sql` in bytes. `sql` need not be null-terminated and may be NULL only when this is + * 0. * @param out_iterator Receives the new iterator handle. Destroy via token_iterator_destroy. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_tokenize_sql(duckdb_v2_connection_handle conn, const duckdb_v2_str *sql, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_tokenize_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, duckdb_v2_token_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err); #endif @@ -5160,12 +5238,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_create(duckdb_v2_facto * * @param function The function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_name(duckdb_v2_aggregate_function_handle function, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif @@ -6180,8 +6260,8 @@ typedef struct _duckdb_v2_column_description { * partial: an unqualified or schema-qualified name resolves through the connection's search path, exactly as the same * name resolves in SQL. A two-part name tries the first part as a schema and as an attached database, as SQL does, and * is rejected when both readings exist. A name that resolves to nothing is rejected with the engine's missing-table - * error; a name that resolves to a view is rejected with the engine's not-a-table error, since a description snapshots - * a base table. + * error. A name that resolves to a view is rejected with the same error: a description snapshots a base table, and a + * view is not one, so it is reported as a table that does not exist. * * history: * - unstable: v2.0.0 @@ -6311,13 +6391,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_destroy(duckdb_v2_table * - unstable: v2.0.0 * * @param column The column description. - * @param name Receives a borrowed view of the column name. Valid until the column description is destroyed. + * @param name Receives a borrowed pointer to the column name. Valid until the column description is destroyed. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_get_name(duckdb_v2_column_description_handle column, - duckdb_v2_identifier_t *name, + const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -6617,13 +6698,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_create(duckdb_v2_factory_ha * * @param function The function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_function_handle function, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -6640,12 +6722,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_fun * * @param function The function to set the file extension of. * @param extension The extension to set, without the leading dot. Borrowed and copied. + * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL + * only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_file_extension(duckdb_v2_copy_function_handle function, - const duckdb_v2_str *extension, + const char *extension, idx_t extension_length, duckdb_v2_error_info_handle *err); #endif @@ -6859,13 +6943,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_set_bind_data(duckdb_v2_copy * - unstable: v2.0.0 * * @param info The bind info handle. - * @param path Receives a borrowed view of the file path. Valid only for the duration of the callback. + * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. + * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_file_path(duckdb_v2_copy_to_bind_info_handle info, - duckdb_v2_str *path, + const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); #endif @@ -6922,13 +7007,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_type(duckdb_v2_co * * @param info The bind info handle. * @param index The index of the column to get the name of. - * @param name Receives a borrowed view of the column name. Valid only for the duration of the callback. + * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_name(duckdb_v2_copy_to_bind_info_handle info, - idx_t index, duckdb_v2_identifier_t *name, + idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -6965,13 +7051,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_count(duckdb_v2_c * * @param info The bind info handle. * @param index The index of the option to get the name of. - * @param name Receives a borrowed view of the option name. Valid only for the duration of the callback. + * @param name Receives a borrowed pointer to the option name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_name(duckdb_v2_copy_to_bind_info_handle info, - idx_t index, duckdb_v2_identifier_t *name, + idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -7098,13 +7185,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_bind_data(duckdb_v2_copy * - unstable: v2.0.0 * * @param info The init info handle. - * @param path Receives a borrowed view of the file path. Valid only for the duration of the callback. + * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. + * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_file_path(duckdb_v2_copy_to_init_info_handle info, - duckdb_v2_str *path, + const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); #endif @@ -7509,13 +7597,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_set_bind_data(duckdb_v2_co * - unstable: v2.0.0 * * @param info The bind info handle. - * @param path Receives a borrowed view of the file path. Valid only for the duration of the callback. + * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. + * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_file_path(duckdb_v2_copy_from_bind_info_handle info, - duckdb_v2_str *path, + const char **path, idx_t *path_length, duckdb_v2_error_info_handle *err); #endif @@ -7573,13 +7662,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_type(duckdb_v2_ * * @param info The bind info handle. * @param index The index of the column to get the name of. - * @param name Receives a borrowed view of the column name. Valid only for the duration of the callback. + * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_name(duckdb_v2_copy_from_bind_info_handle info, - idx_t index, duckdb_v2_identifier_t *name, + idx_t index, const char **name, + idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -7615,13 +7706,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_count(duckdb_v2 * * @param info The bind info handle. * @param index The index of the option to get the name of. - * @param name Receives a borrowed view of the option name. Valid only for the duration of the callback. + * @param name Receives a borrowed pointer to the option name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_name(duckdb_v2_copy_from_bind_info_handle info, - idx_t index, duckdb_v2_identifier_t *name, + idx_t index, const char **name, + idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -8243,13 +8336,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_create(duckdb_v2_factory_ha * * @param option The option to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -8304,12 +8398,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_value(duckdb_v2 * * @param option The option to set the description of. * @param description The description to set. Borrowed and copied. + * @param description_length The length of `description` in bytes. `description` need not be null-terminated and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_description(duckdb_v2_custom_option_handle option, - const duckdb_v2_str *description, + const char *description, idx_t description_length, duckdb_v2_error_info_handle *err); #endif @@ -8815,13 +8911,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_column_ref_get_index(duckdb_v2 * - unstable: v2.0.0 * * @param expression The function node. - * @param name Receives a borrowed view of the function name. + * @param name Receives a borrowed pointer to the function name. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_name(duckdb_v2_expression_handle expression, - duckdb_v2_identifier_t *name, + const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif @@ -8926,8 +9023,9 @@ typedef struct _duckdb_v2_log_sink_flush_info { typedef void (*duckdb_v2_log_sink_write_callback_fn)(duckdb_v2_log_sink_write_info_handle info, void *user_data, int64_t timestamp, DUCKDB_V2_LOG_LEVEL level, - DUCKDB_V2_LOG_SCOPE scope, const duckdb_v2_str *type, - const duckdb_v2_str *message, duckdb_v2_error_info_handle *err); + DUCKDB_V2_LOG_SCOPE scope, const char *type, idx_t type_length, + const char *message, idx_t message_length, + duckdb_v2_error_info_handle *err); typedef void (*duckdb_v2_log_sink_flush_callback_fn)(duckdb_v2_log_sink_flush_info_handle info, void *user_data, duckdb_v2_error_info_handle *err); @@ -8970,13 +9068,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_create(duckdb_v2_factory_handle * * @param sink The log sink to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -9323,8 +9422,10 @@ typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { * * @param factory The factory to resolve the type in. * @param type_id The type id to instantiate. - * @param param_names Optional. An array of param_count parameter names; a {NULL, 0} entry is positional. Pass NULL for - * all-positional parameters. + * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is + * positional. Pass NULL for all-positional parameters. + * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. + * May be NULL only when `param_names` is NULL. * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. * @param param_count The number of parameters. 0 instantiates a parameterless primitive. * @param out_type Receives the new logical type handle. @@ -9332,9 +9433,9 @@ typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( - duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -9350,7 +9451,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( * the type in that catalog or schema or fails. * * Parameters are (name, value) pairs in two parallel arrays. param_names may be NULL to make every parameter - * positional, and a {NULL, 0} entry makes that one parameter positional. Child types cross as TYPE values, built with + * positional, and an empty entry makes that one parameter positional. Child types cross as TYPE values, built with * value_create_type. The built-in shapes are: decimal(width, scale); list(T); array(T, size); map(K, V); struct(fields, * as named or all-positional TYPE values); union(members, as named TYPE values); enum(entries, as VARCHAR values); and * varchar with a named "collation" VARCHAR parameter. @@ -9372,8 +9473,10 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( * @param factory The factory to resolve the type in. * @param name The type name to resolve. Parts are matched case-insensitively; qualify it to name a type in a particular * catalog or schema. - * @param param_names Optional. An array of param_count parameter names; a {NULL, 0} entry is positional. Pass NULL for - * all-positional parameters. + * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is + * positional. Pass NULL for all-positional parameters. + * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. + * May be NULL only when `param_names` is NULL. * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. * @param param_count The number of parameters. * @param out_type Receives the new logical type handle. @@ -9381,9 +9484,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name( - duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); + duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -9408,13 +9511,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name( * - unstable: v2.0.0 * * @param factory The factory to resolve the type in. - * @param text View of the SQL type expression to parse. + * @param text The SQL type expression to parse. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. * @param out_type Receives the new logical type handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, - const duckdb_v2_str *text, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, const char *text, + idx_t text_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif @@ -9505,13 +9610,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_id(duckdb_v2_logical_typ * - unstable: v2.0.0 * * @param type The logical type. - * @param out_name Receives a borrowed view of the name (alias when set, else the id's canonical name). + * @param out_name Receives a borrowed pointer to the name (alias when set, else the id's canonical name). + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, - duckdb_v2_identifier_t *out_name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -9575,9 +9681,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_lo * Returns one value parameter of a logical type. * * out_name receives a borrowed view of the parameter name — a STRUCT field name, a UNION member name, "collation" — or - * the empty view {NULL, 0} for a positional parameter. A non-empty view is valid until the logical type is destroyed. - * out_value receives an owned value, destroyed via value_destroy: child types come back as TYPE values (unwrap them - * with value_get_type), DECIMAL width and scale as UTINYINT, ARRAY size as BIGINT, and ENUM dictionary entries and + * an empty name for a positional parameter. A non-empty view is valid until the logical type is destroyed. out_value + * receives an owned value, destroyed via value_destroy: child types come back as TYPE values (unwrap them with + * value_get_type), DECIMAL width and scale as UTINYINT, ARRAY size as BIGINT, and ENUM dictionary entries and * collations as VARCHAR. An out-of-range index returns ERROR_INPUT_INVALID. Each call allocates one owned value. * * history: @@ -9585,14 +9691,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_lo * * @param type The logical type. * @param index The parameter index, in [0, param_count). - * @param out_name Receives a borrowed view of the parameter name, or the empty view {NULL, 0} for a positional + * @param out_name Receives a borrowed pointer to the parameter name, or NULL with a zero length for a positional * parameter. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. * @param out_value Receives the owned parameter value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, - duckdb_v2_identifier_t *out_name, + const char **out_name, idx_t *out_name_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif @@ -9615,13 +9723,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_ * @param base_type The logical type to alias. Typically the base type supplied in the custom type bind info. * @param alias_name The name for the resulting type. Typically the name of the custom type being constructed, also * available from the bind info. + * @param alias_name_length The length of `alias_name` in bytes. `alias_name` must be valid UTF-8, need not be + * null-terminated, and may be NULL only when this is 0. * @param out_type Receives the new type: the base type's internal representation under the given alias name. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_with_alias(duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle base_type, - const duckdb_v2_identifier_t *alias_name, + const char *alias_name, idx_t alias_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif @@ -9736,12 +9846,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_create(duckdb_v2_factory_h * * @param function The macro function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_function_handle function, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif @@ -9759,12 +9871,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_f * * @param function The macro function to set the body of. * @param body The SQL text of the body. Borrowed and copied. + * @param body_length The length of `body` in bytes. `body` need not be null-terminated and may be NULL only when this + * is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_body(duckdb_v2_macro_function_handle function, - const duckdb_v2_str *body, + const char *body, idx_t body_length, duckdb_v2_error_info_handle *err); #endif @@ -9940,12 +10054,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_create(duckdb_v2_factory_ * * @param function The function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_name(duckdb_v2_pragma_function_handle function, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif @@ -10072,12 +10188,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_exec_callback( * * @param info The query info handle. * @param query The SQL to run. Borrowed and copied. + * @param query_length The length of `query` in bytes. `query` need not be null-terminated and may be NULL only when + * this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_query_set_query(duckdb_v2_pragma_function_query_info_handle info, - const duckdb_v2_str *query, + const char *query, idx_t query_length, duckdb_v2_error_info_handle *err); #endif @@ -10363,13 +10481,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_argument(duckdb_v2_r * * @param info The info handle. * @param name The name of the parameter to bind the value to. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param value The argument value. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckdb_v2_replacement_scan_info_handle info, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif @@ -10404,6 +10524,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckd * @param collection The collection to read instead. Borrowed; the caller keeps ownership and must keep it alive. * @param column_names Optional. An array of `column_count` column names, in order. Pass NULL for the default names * col1..colN. + * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of + * `column_names[i]`. May be NULL only when `column_names` is NULL. * @param column_count The number of names in `column_names`. Must equal the collection's column count, or 0 for the * default names. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via @@ -10412,7 +10534,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckd */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection( duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const duckdb_v2_identifier_t *column_names, idx_t column_count, duckdb_v2_error_info_handle *err); + const char **column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -10433,12 +10555,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection( * * @param info The info handle. * @param sql The SELECT statement to read instead. Borrowed for the call only. + * @param sql_length The length of `sql` in bytes. `sql` need not be null-terminated and may be NULL only when this is + * 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_subquery(duckdb_v2_replacement_scan_info_handle info, - const duckdb_v2_str *sql, + const char *sql, idx_t sql_length, duckdb_v2_error_info_handle *err); #endif @@ -10455,12 +10579,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_subquery(duckdb_v2_r * * @param info The info handle. * @param alias The alias to bind the replacement under. Borrowed and copied. + * @param alias_length The length of `alias` in bytes. `alias` must be valid UTF-8, need not be null-terminated, and may + * be NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_alias(duckdb_v2_replacement_scan_info_handle info, - const duckdb_v2_identifier_t *alias, + const char *alias, idx_t alias_length, duckdb_v2_error_info_handle *err); #endif @@ -10691,12 +10817,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_create(duckdb_v2_factory_ * * @param function The function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_name(duckdb_v2_scalar_function_handle function, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif @@ -11405,14 +11533,16 @@ typedef struct _duckdb_v2_statement_iterator { * - unstable: v2.0.0 * * @param conn The connection supplying the parser configuration. - * @param sql Null-terminated SQL string; may contain any number of statements. + * @param sql The SQL text, `sql_length` bytes long; may contain any number of statements. Need not be null-terminated. + * May be NULL only when `sql_length` is 0. + * @param sql_length The length of `sql` in bytes. * @param apply_invalidation_policy Whether a parse error invalidates the active transaction, according to the * transaction invalidation policy. * @param out_iterator Receives the new iterator handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, bool apply_invalidation_policy, duckdb_v2_statement_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err); @@ -11503,9 +11633,13 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_bind(duckdb_v2_connection_handl * * @param statement The statement to bind the collection to. Modified in place. * @param name The non-empty name the statement refers to the collection by. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param collection The collection to bind. Borrowed; the caller keeps ownership and must keep it alive. * @param column_names Optional. An array of `column_count` names for the collection's columns, in order. Pass NULL for * col1..colN. + * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of + * `column_names[i]`. May be NULL only when `column_names` is NULL. * @param column_count The number of names in `column_names`. 0 for the default names; otherwise the collection's column * count. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via @@ -11513,10 +11647,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_bind(duckdb_v2_connection_handl * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, - const duckdb_v2_identifier_t *column_names, - idx_t column_count, duckdb_v2_error_info_handle *err); + const char **column_names, + const idx_t *column_names_lengths, idx_t column_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -11555,12 +11690,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_type(duckdb_v2_sql_stat * - unstable: v2.0.0 * * @param statement The statement. - * @param out_text Receives a borrowed view of the statement text, valid until the statement is destroyed. + * @param out_text Receives a borrowed pointer to the statement text, valid until the statement is destroyed. + * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, - duckdb_v2_str *out_text, + const char **out_text, idx_t *out_text_length, duckdb_v2_error_info_handle *err); #endif @@ -11600,12 +11737,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_count(duckdb_ * * @param statement The statement. * @param index Zero-based position in binding order. - * @param out_name Receives a borrowed view of the parameter name, valid until the statement is destroyed. + * @param out_name Receives a borrowed pointer to the parameter name, valid until the statement is destroyed. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_statement_handle statement, - idx_t index, duckdb_v2_identifier_t *out_name, + idx_t index, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err); #endif @@ -12214,23 +12354,25 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_encode(const uint8_t *in_data, idx #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Validates all text->len bytes as UTF-8, including bytes after embedded NUL characters. + * Validates all `text_length` bytes of `text` as UTF-8, including bytes after embedded NUL characters. * * Returns ERROR_INPUT_INVALID if any of: - * - text is NULL. - * - text->ptr is NULL and text->len is nonzero. + * - text is NULL and text_length is nonzero. * - The input contains malformed UTF-8. * - * A view with a NULL ptr and zero length is valid. + * A NULL text with a zero length is valid. * * history: * - unstable: v2.0.0 * * @param text The bytes to validate. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const duckdb_v2_str *text, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const char *text, idx_t text_length, + duckdb_v2_error_info_handle *err); #endif /* --- Struct definitions for vector --- */ @@ -12344,11 +12486,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_conne * * `parameter_values` binds the statement's parameters as constants for this execution. Binding is positional by default * ($1 = element 0); supply `parameter_names` to bind by name instead, where a non-empty entry binds its value to that - * named parameter ($name, matched case-insensitively) and a {NULL, 0} entry stays positional. Pass NULL for both - * arrays, or a count of 0, for a statement without parameters. Both arrays are borrowed and copied in, so the caller - * still owns and destroys them. A key set that does not match the statement's parameters is rejected with - * `ERROR_INPUT_INVALID`, with one exception: a named parameter left without a value reads the session variable of the - * same name (`SET VARIABLE`) when one exists. + * named parameter ($name, matched case-insensitively) and an empty entry stays positional. Pass NULL for both arrays, + * or a count of 0, for a statement without parameters. Both arrays are borrowed and copied in, so the caller still owns + * and destroys them. A key set that does not match the statement's parameters is rejected with `ERROR_INPUT_INVALID`, + * with one exception: a named parameter left without a value reads the session variable of the same name (`SET + * VARIABLE`) when one exists. * * Not consumed: execute the same handle again, with the same values or different ones, as often as you like. Values are * bound per execution and nothing carries over between them. A catalog change since the statement was prepared, or a @@ -12364,8 +12506,10 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_conne * * @param prepared The prepared statement to execute. Borrowed; not consumed. * @param parameter_names Optional. An array of `parameter_count` parameter names; a non-empty entry binds its value to - * the named parameter ($name, case-insensitive), a {NULL, 0} entry keeps it positional ($1 = element 0). Pass NULL to - * bind everything positionally. + * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element + * 0). Pass NULL to bind everything positionally. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. * @param parameter_values Optional. An array of `parameter_count` values. Each binds by name when `parameter_names` * supplies one, and positionally ($1 = element 0) otherwise. Borrowed and copied in. Pass NULL for a statement without * parameters. @@ -12376,12 +12520,10 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_conne * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute(duckdb_v2_prepared_statement_handle prepared, - const duckdb_v2_identifier_t *parameter_names, - const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, - duckdb_v2_result_handle *out_result, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute( + duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, + const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -12494,7 +12636,7 @@ typedef enum DUCKDB_V2_RESULT_STEP_STATUS { * parameter_values binds the statement's parameters as constants for this execution. Binding is positional by default: * the i-th value binds $(i+1), matching SQL's own convention, so dense $1..$N and ? placeholders work directly. Supply * parameter_names to bind by name instead — a non-empty name binds its value to that named parameter ($name, matched - * case-insensitively), while a {NULL, 0} entry leaves that value positional. The parameter schema from statement_bind + * case-insensitively), while an empty entry leaves that value positional. The parameter schema from statement_bind * lists the names to use. Both arrays are borrowed and copied in; the caller still owns and destroys them. Pass NULL * for both, or a count of 0, for an unparameterized statement. A key set that does not match the statement's parameters * — names for a positional statement, or the reverse — is rejected with ERROR_INPUT_INVALID, and named and positional @@ -12520,8 +12662,10 @@ typedef enum DUCKDB_V2_RESULT_STEP_STATUS { * @param conn The connection on which to execute the statement. * @param statement The statement to execute. Borrowed and copied; not consumed. Destroy it with sql_statement_destroy. * @param parameter_names Optional. An array of parameter_count parameter names; a non-empty entry binds its value to - * the named parameter ($name, case-insensitive), a {NULL, 0} entry keeps it positional ($1 = element 0). Pass NULL for - * all-positional binding. Named and positional parameters cannot be mixed within one statement. + * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element + * 0). Pass NULL for all-positional binding. Named and positional parameters cannot be mixed within one statement. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. * @param parameter_values Optional. An array of parameter_count value handles. Each binds by name when parameter_names * supplies one, otherwise positionally ($1 = element 0). Borrowed (copied in). Pass NULL for an unparameterized * statement. @@ -12531,12 +12675,10 @@ typedef enum DUCKDB_V2_RESULT_STEP_STATUS { * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, - const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, duckdb_v2_result_handle *out_result, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute( + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -12666,6 +12808,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_wait(duckdb_v2_result_handle resul * @param max_width Maximum total width in characters; 0 selects the renderer default. * @param max_col_width Maximum width of one column; 0 selects the renderer default (20). * @param null_value Text rendered for NULL cells; empty selects "NULL". + * @param null_value_length The length of `null_value` in bytes. `null_value` need not be null-terminated and may be + * NULL only when this is 0. * @param render_mode 0 renders rows (records down the page); 1 renders columns; other values are rejected with * INVALID_INPUT. * @param limit The row limit the caller applied to the query before rendering; 0 means none. When the materialized @@ -12678,9 +12822,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_wait(duckdb_v2_result_handle resul * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx_t max_rows, - idx_t max_width, idx_t max_col_width, - const duckdb_v2_str *null_value, idx_t render_mode, - idx_t limit, duckdb_v2_text_sink_fn sink, void *user_data, + idx_t max_width, idx_t max_col_width, const char *null_value, + idx_t null_value_length, idx_t render_mode, idx_t limit, + duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); #endif @@ -13025,12 +13169,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_create(duckdb_v2_factory_h * * @param function The function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handle function, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif @@ -13347,13 +13493,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback( * * @param info The bind info handle. * @param name The name of the column. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param type The type of the column. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column( - duckdb_v2_table_function_bind_info_handle info, const duckdb_v2_identifier_t *name, + duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); #endif @@ -14680,14 +14828,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_column_i * * @param info The get bind info handle. * @param key The key of the option. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. * @param value The value of the option. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_option( - duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_str *key, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); + duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -14728,12 +14878,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_create(duckdb_v2_fact * * @param function The function to set the name of. * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, - duckdb_v2_str *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif @@ -14760,12 +14912,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_mu * * @param function The function to set the single-file function of. * @param name The name of the registered single-file table function. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_single_file_function( - duckdb_v2_multi_file_function_handle function, duckdb_v2_str *name, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_single_file_function(duckdb_v2_multi_file_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -14780,12 +14935,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_single_file_funct * * @param function The function to set the reader type of. * @param reader_type The reader type. Borrowed and copied. + * @param reader_type_length The length of `reader_type` in bytes. `reader_type` need not be null-terminated and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_reader_type( - duckdb_v2_multi_file_function_handle function, duckdb_v2_str *reader_type, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_reader_type(duckdb_v2_multi_file_function_handle function, const char *reader_type, + idx_t reader_type_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -14801,12 +14959,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_reader_type( * * @param function The function to set the file extension of. * @param extension The file extension, without a leading dot. Borrowed and copied. + * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL + * only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_file_extension( - duckdb_v2_multi_file_function_handle function, duckdb_v2_str *extension, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_file_extension(duckdb_v2_multi_file_function_handle function, const char *extension, + idx_t extension_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -15135,11 +15296,12 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_hugeint(duckdb_v2_value_handle * @param value The value to read. * @param out Receives the payload as a UTF-8 string. The returned string is borrowed and valid until the value handle * is destroyed. + * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, duckdb_v2_str *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, const char **out, + idx_t *out_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -15156,10 +15318,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle * @param value The value to read. * @param out Receives the payload as a byte string. The returned string is borrowed and valid until the value handle is * destroyed. + * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, duckdb_v2_str *out, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err); #endif @@ -15750,14 +15913,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_hugeint(duckdb_v2_factory_ha * - unstable: v2.0.0 * * @param factory The factory to create with. - * @param in_value The UTF-8 string to wrap. May be null only when len is 0 (empty string). + * @param in_value The UTF-8 string to wrap. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. * @param out_value Receives the new VARCHAR value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, - const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif @@ -15771,14 +15935,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_ha * - unstable: v2.0.0 * * @param factory The factory to create with. - * @param in_value The byte string to wrap. May be null only when len is 0 (empty string). + * @param in_value The byte string to wrap. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. * @param out_value Receives the new BLOB value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, - const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif @@ -16140,12 +16305,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uuid(duckdb_v2_factory_handl * * @param factory The factory to create with. * @param in_value The wire bytes, a padding header byte followed by data. Must be at least 1 byte. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. * @param out_value Receives the new BIT value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif @@ -16162,13 +16329,14 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle * * @param factory The factory to create with. * @param in_value The opaque storage bytes from bignum_encode. Must exceed 3 bytes. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. * @param out_value Receives the new BIGNUM value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, - const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif @@ -16244,14 +16412,16 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_hand * * @param factory The factory to create with. * @param names An array of field_count field names. Pass NULL when field_count is 0. + * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only + * when `names` is NULL. * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. * @param field_count The number of fields. * @param out_value Receives the new composite value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, - const duckdb_v2_identifier_t *names, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char **names, + const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); @@ -16686,6 +16856,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_destroy(duckdb_v2_arrow_im * @param types An array of `count` column types. May be NULL only when `count` is 0. * @param names An array of `count` column names, parallel to `types`. Each name must be valid UTF-8. May be NULL only * when `count` is 0. + * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only + * when `names` is NULL. * @param count The number of columns, being the length of both `types` and `names`. * @param batch_size Maximum rows per produced array, or 0 for no maximum. * @param out_exporter On success, receives the new exporter. Owned by the caller; destroy via @@ -16696,7 +16868,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_destroy(duckdb_v2_arrow_im */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_create(duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, - const duckdb_v2_str *names, idx_t count, idx_t batch_size, + const char **names, const idx_t *names_lengths, + idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err); #endif @@ -16815,6 +16988,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_destroy(duckdb_v2_arrow_ex * @param conn The connection to run the statement on. * @param statement The statement to execute. Not consumed. * @param parameter_names Optional. As in `duckdb_v2_statement_execute()`. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. * @param parameter_values Optional. As in `duckdb_v2_statement_execute()`. * @param parameter_count The number of parameters. 0 for none. * @param batch_size Maximum rows per array. Arrays can be shorter. 0 means 131072. @@ -16823,13 +16998,10 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_destroy(duckdb_v2_arrow_ex * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, - const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow( + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -16843,6 +17015,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow(duckdb_v2_connect * * @param prepared The prepared statement to execute. Not consumed. * @param parameter_names Optional. As in `duckdb_v2_prepared_statement_execute()`. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. * @param parameter_values Optional. As in `duckdb_v2_prepared_statement_execute()`. * @param parameter_count The number of parameters. 0 for none. * @param batch_size Maximum rows per array. Arrays can be shorter. 0 means 131072. @@ -16851,12 +17025,10 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow(duckdb_v2_connect * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow(duckdb_v2_prepared_statement_handle prepared, - const duckdb_v2_identifier_t *parameter_names, - const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow( + duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, + const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, + duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE diff --git a/src/duckdb/src/logging/log_manager.cpp b/src/duckdb/src/logging/log_manager.cpp index 2e6fe5452..55d2a3813 100644 --- a/src/duckdb/src/logging/log_manager.cpp +++ b/src/duckdb/src/logging/log_manager.cpp @@ -10,31 +10,48 @@ namespace duckdb { -unique_ptr LogManager::CreateLogger(LoggingContext context, bool thread_safe, bool mutable_settings) { - unique_lock lck(lock); - - auto registered_logging_context = RegisterLoggingContextInternal(context); - +unique_ptr LogManager::CreateLogger(const LoggingContext &context, bool thread_safe, bool mutable_settings) { + annotated_unique_lock lck(lock); if (mutable_settings) { - return make_uniq(config, registered_logging_context, *this); - } - if (!config.enabled) { - return make_uniq(*this); + return make_uniq(*config, RegisterLoggingContextInternal(context), *this); } if (!thread_safe) { // TODO: implement ThreadLocalLogger and return it here } - return make_uniq(config, registered_logging_context, *this); + return CreateLoggerInternal(context, config); +} + +unique_ptr LogManager::CreateLogger(const LoggingContext &context, const LogConfigSnapshot &snapshot) { + if (snapshot.config && snapshot.version == config_version.load()) { + return CreateLoggerInternal(context, snapshot.config); + } + annotated_unique_lock lck(lock); + return CreateLoggerInternal(context, config); +} + +unique_ptr LogManager::CreateLogger(const LoggingContext &context, LogConfigSnapshot &snapshot) { + if (!snapshot.config || snapshot.version != config_version.load()) { + annotated_unique_lock lck(lock); + snapshot.config = config; + snapshot.version = config_version.load(); + } + return CreateLoggerInternal(context, snapshot.config); } -RegisteredLoggingContext LogManager::RegisterLoggingContext(LoggingContext &context) { - unique_lock lck(lock); +unique_ptr LogManager::CreateLoggerInternal(const LoggingContext &context, + const shared_ptr &logger_config) { + if (!logger_config->enabled) { + return make_uniq(*this); + } + return make_uniq(logger_config, RegisterLoggingContextInternal(context), *this); +} +RegisteredLoggingContext LogManager::RegisterLoggingContext(const LoggingContext &context) { return RegisterLoggingContextInternal(context); } bool LogManager::RegisterLogStorage(const string &name, shared_ptr &storage) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); if (registered_log_storages.find(name) != registered_log_storages.end()) { return false; } @@ -51,21 +68,22 @@ shared_ptr LogManager::GlobalLoggerReference() { } void LogManager::Flush() { - unique_lock lck(lock); + annotated_unique_lock lck(lock); log_storage->FlushAll(); } shared_ptr LogManager::GetLogStorage() { - unique_lock lck(lock); + annotated_unique_lock lck(lock); return log_storage; } bool LogManager::CanScan(LoggingTargetTable table) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); return log_storage->CanScan(table); } -LogManager::LogManager(DatabaseInstance &db, LogConfig config_p) : config(std::move(config_p)), db_instance(db) { +LogManager::LogManager(DatabaseInstance &db, LogConfig config_p) + : config(make_shared_ptr(std::move(config_p))), db_instance(db) { log_storage = make_uniq(db); } @@ -83,16 +101,12 @@ LogManager &LogManager::Get(ClientContext &context) { return context.db->GetLogManager(); } -RegisteredLoggingContext LogManager::RegisterLoggingContextInternal(LoggingContext &context) { - RegisteredLoggingContext result = {next_registered_logging_context_index, context}; - - next_registered_logging_context_index += 1; - - if (next_registered_logging_context_index == NumericLimits::Maximum()) { +RegisteredLoggingContext LogManager::RegisterLoggingContextInternal(const LoggingContext &context) { + auto context_id = next_registered_logging_context_index++; + if (context_id >= NumericLimits::Maximum() - 1) { throw InternalException("Ran out of available log context ids."); } - - return result; + return {context_id, context}; } void LogManager::WriteLogEntry(timestamp_t timestamp, const char *log_type, LogLevel log_level, const char *log_message, @@ -100,7 +114,7 @@ void LogManager::WriteLogEntry(timestamp_t timestamp, const char *log_type, LogL if (log_level == LogLevel::LOG_WARNING && Settings::Get(db_instance)) { throw InvalidInputException(log_message); } else { - unique_lock lck(lock); + annotated_unique_lock lck(lock); log_storage->WriteLogEntry(timestamp, log_level, log_type, log_message, context); } } @@ -110,84 +124,90 @@ void LogManager::FlushCachedLogEntries(DataChunk &chunk, const RegisteredLogging } void LogManager::SetConfig(DatabaseInstance &db, const LogConfig &config_p) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); // We need extra handling for switching storage - SetLogStorageInternal(db, config_p.storage); - - // keep the storage name as SetLogStorageInternal lowercased it, so that it is recognized when set again auto new_config = config_p; - new_config.storage = config.storage; + SetLogStorageInternal(db, new_config, config_p.storage); SetConfigInternal(std::move(new_config)); } pair> LogManager::GetConfigAndStorage() { - unique_lock lck(lock); - return make_pair(config, log_storage); + annotated_unique_lock lck(lock); + return make_pair(*config, log_storage); } void LogManager::RestoreConfig(const LogConfig &config_p, shared_ptr storage) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); log_storage = std::move(storage); SetConfigInternal(config_p); } void LogManager::SetEnableLogging(bool enable) { - unique_lock lck(lock); - config.enabled = enable; - global_logger->UpdateConfig(config); + annotated_unique_lock lck(lock); + auto new_config = *config; + new_config.enabled = enable; + SetConfigInternal(std::move(new_config)); } void LogManager::SetLogMode(LogMode mode) { - unique_lock lck(lock); - config.mode = mode; - global_logger->UpdateConfig(config); + annotated_unique_lock lck(lock); + auto new_config = *config; + new_config.mode = mode; + SetConfigInternal(std::move(new_config)); } void LogManager::SetLogLevel(LogLevel level) { - unique_lock lck(lock); - config.level = level; - global_logger->UpdateConfig(config); + annotated_unique_lock lck(lock); + auto new_config = *config; + new_config.level = level; + SetConfigInternal(std::move(new_config)); } void LogManager::SetEnabledLogTypes(optional_ptr> enabled_log_types) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); + auto new_config = *config; if (enabled_log_types) { - config.enabled_log_types = *enabled_log_types; + new_config.enabled_log_types = *enabled_log_types; } else { - config.enabled_log_types = {}; + new_config.enabled_log_types = {}; } - global_logger->UpdateConfig(config); + SetConfigInternal(std::move(new_config)); } void LogManager::SetDisabledLogTypes(optional_ptr> disabled_log_types) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); + auto new_config = *config; if (disabled_log_types) { - config.disabled_log_types = *disabled_log_types; + new_config.disabled_log_types = *disabled_log_types; } else { - config.disabled_log_types = {}; + new_config.disabled_log_types = {}; } - global_logger->UpdateConfig(config); + SetConfigInternal(std::move(new_config)); } void LogManager::SetLogStorage(DatabaseInstance &db, const string &storage_name) { - unique_lock lck(lock); + 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) { + if (storage_name_to_lower == LogConfig::FILE_STORAGE_NAME && config->storage != storage_name_to_lower) { throw InvalidConfigurationException( "Cannot select 'file' log storage via 'SET logging_storage' because it requires a path. " "Use CALL enable_logging(storage='file', storage_path='...') instead."); } - SetLogStorageInternal(db, storage_name); + auto new_config = *config; + SetLogStorageInternal(db, new_config, storage_name); + SetConfigInternal(std::move(new_config)); } -void LogManager::SetLogStorageInternal(DatabaseInstance &db, const string &storage_name) { +void LogManager::SetLogStorageInternal(DatabaseInstance &db, LogConfig &new_config, const string &storage_name) { auto storage_name_to_lower = StringUtil::Lower(storage_name); - if (config.storage == storage_name_to_lower) { + // 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) { return; } @@ -212,18 +232,17 @@ void LogManager::SetLogStorageInternal(DatabaseInstance &db, const string &stora } else { throw InvalidInputException("Log storage '%s' is not yet registered", storage_name); } - config.storage = storage_name_to_lower; } void LogManager::UpdateLogStorageConfig(DatabaseInstance &db, case_insensitive_map_t &config_value) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); log_storage->UpdateConfig(db, config_value); } void LogManager::SetEnableStructuredLoggers(vector &enabled_logger_types) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); - LogConfig new_config = config; + LogConfig new_config = *config; new_config.enabled_log_types.clear(); LogLevel min_log_level = LogLevel::LOG_FATAL; @@ -243,21 +262,21 @@ void LogManager::SetEnableStructuredLoggers(vector &enabled_logger_types new_config.mode = LogMode::ENABLE_SELECTED; new_config.enabled = true; - SetConfigInternal(new_config); + SetConfigInternal(std::move(new_config)); } void LogManager::TruncateLogStorage() { - unique_lock lck(lock); + annotated_unique_lock lck(lock); log_storage->Truncate(); } LogConfig LogManager::GetConfig() { - unique_lock lck(lock); - return config; + annotated_unique_lock lck(lock); + return *config; } optional_ptr LogManager::LookupLogType(const string &type) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); return LookupLogTypeInternal(type); } @@ -272,14 +291,14 @@ optional_ptr LogManager::LookupLogTypeInternal(const string &type return nullptr; } -void LogManager::SetConfigInternal(LogConfig config_p) { - // Apply the remainder of the config - config = std::move(config_p); - global_logger->UpdateConfig(config); +void LogManager::SetConfigInternal(LogConfig new_config) { + config = make_shared_ptr(std::move(new_config)); + config_version++; + global_logger->UpdateConfig(*config); } void LogManager::RegisterLogType(unique_ptr type) { - unique_lock lck(lock); + annotated_unique_lock lck(lock); auto lookup = registered_log_types.find(type->name); if (lookup != registered_log_types.end()) { diff --git a/src/duckdb/src/logging/logger.cpp b/src/duckdb/src/logging/logger.cpp index a6e0facff..3b81d20db 100644 --- a/src/duckdb/src/logging/logger.cpp +++ b/src/duckdb/src/logging/logger.cpp @@ -46,28 +46,25 @@ Logger &Logger::Get(const shared_ptr &logger) { return *logger; } -ThreadSafeLogger::ThreadSafeLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager) - : ThreadSafeLogger(config_p, manager.RegisterLoggingContext(context_p), manager) { -} - -ThreadSafeLogger::ThreadSafeLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager) - : Logger(manager), config(config_p), context(context_p) { +ThreadSafeLogger::ThreadSafeLogger(shared_ptr config_p, RegisteredLoggingContext context_p, + LogManager &manager) + : Logger(manager), config(std::move(config_p)), context(context_p) { // NopLogger should be used instead - D_ASSERT(config_p.enabled); + D_ASSERT(config && config->enabled); } bool ThreadSafeLogger::ShouldLog(const char *log_type, LogLevel log_level) { - if (config.level > log_level) { + if (config->level > log_level) { return false; } // TODO: improve these: they are currently fairly expensive due to requiring allocations when looking up const char* // also, we would ideally do prefix matching, not string matching here - if (config.mode == LogMode::ENABLE_SELECTED) { - return config.enabled_log_types.find(log_type) != config.enabled_log_types.end(); + if (config->mode == LogMode::ENABLE_SELECTED) { + return config->enabled_log_types.find(log_type) != config->enabled_log_types.end(); } - if (config.mode == LogMode::DISABLE_SELECTED) { - return config.disabled_log_types.find(log_type) == config.disabled_log_types.end(); + if (config->mode == LogMode::DISABLE_SELECTED) { + return config->disabled_log_types.find(log_type) == config->disabled_log_types.end(); } return true; } @@ -103,18 +100,18 @@ void ThreadLocalLogger::Flush() { manager.Flush(); } -MutableLogger::MutableLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager) +MutableLogger::MutableLogger(const LogConfig &config_p, LoggingContext &context_p, LogManager &manager) : MutableLogger(config_p, manager.RegisterLoggingContext(context_p), manager) { } -MutableLogger::MutableLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager) +MutableLogger::MutableLogger(const LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager) : Logger(manager), config(config_p), context(context_p) { enabled = config.enabled; level = config.level; mode = config.mode; } -void MutableLogger::UpdateConfig(LogConfig &new_config) { +void MutableLogger::UpdateConfig(const LogConfig &new_config) { unique_lock lck(lock); config = new_config; diff --git a/src/duckdb/src/main/capi/v1/arrow-c.cpp b/src/duckdb/src/main/capi/v1/arrow-c.cpp index 282caa906..5a84ffa78 100644 --- a/src/duckdb/src/main/capi/v1/arrow-c.cpp +++ b/src/duckdb/src/main/capi/v1/arrow-c.cpp @@ -496,7 +496,7 @@ duckdb_state Ingest(duckdb_connection connection, const char *table_name, struct } auto factory = duckdb::make_shared_ptr(*input); cconn->TableFunction("arrow_scan", {}, {}, std::move(factory)) - ->CreateView(duckdb::Identifier(table_name), true, false); + ->CreateView(duckdb::Identifier(table_name), true, true); } catch (...) { // LCOV_EXCL_START // Tried covering this in tests, but it proved harder than expected. At the time of writing: // - Passing any name to `CreateView` worked without throwing an exception diff --git a/src/duckdb/src/main/capi/v1/cast/from_decimal-c.cpp b/src/duckdb/src/main/capi/v1/cast/from_decimal-c.cpp index 4990c635d..d76f0bce3 100644 --- a/src/duckdb/src/main/capi/v1/cast/from_decimal-c.cpp +++ b/src/duckdb/src/main/capi/v1/cast/from_decimal-c.cpp @@ -108,7 +108,10 @@ duckdb_hugeint FetchInternals(void *source_address) { template <> bool CastDecimalCInternal(duckdb_result *source, duckdb_decimal &result, idx_t col, idx_t row) { auto result_data = (duckdb::DuckDBResultData *)source->internal_data; - result_data->result->GetTypes()[col].GetDecimalProperties(result.width, result.scale); + uint32_t width, scale; + result_data->result->GetTypes()[col].GetDecimalProperties(width, scale); + result.width = duckdb::NumericCast(width); + result.scale = duckdb::NumericCast(scale); auto source_address = UnsafeFetchPtr(source, col, row); if (result.width > duckdb::Decimal::MAX_WIDTH_INT64) { diff --git a/src/duckdb/src/main/capi/v1/cast/utils-c.cpp b/src/duckdb/src/main/capi/v1/cast/utils-c.cpp index 321314ff4..d87a2eced 100644 --- a/src/duckdb/src/main/capi/v1/cast/utils-c.cpp +++ b/src/duckdb/src/main/capi/v1/cast/utils-c.cpp @@ -84,6 +84,10 @@ bool CanUseDeprecatedFetch(duckdb_result *result, idx_t col, idx_t row) { if (col >= result->deprecated_column_count || row >= result->deprecated_row_count) { return false; } + if (!result->deprecated_columns[col].deprecated_nullmask) { + // the column was not translated, e.g. because an earlier column failed to materialize + return false; + } return true; } diff --git a/src/duckdb/src/main/capi/v1/duckdb_value-c.cpp b/src/duckdb/src/main/capi/v1/duckdb_value-c.cpp index c181c3857..d63f537b1 100644 --- a/src/duckdb/src/main/capi/v1/duckdb_value-c.cpp +++ b/src/duckdb/src/main/capi/v1/duckdb_value-c.cpp @@ -166,7 +166,7 @@ duckdb_decimal duckdb_get_decimal(duckdb_value val) { auto width = duckdb::DecimalType::GetWidth(type); auto scale = duckdb::DecimalType::GetScale(type); duckdb::hugeint_t hugeint = duckdb::IntegralValue::Get(v); - return {width, scale, {hugeint.lower, hugeint.upper}}; + return {duckdb::NumericCast(width), duckdb::NumericCast(scale), {hugeint.lower, hugeint.upper}}; } duckdb_value duckdb_create_float(float input) { return CAPICreateValue(input); diff --git a/src/duckdb/src/main/capi/v1/logical_types-c.cpp b/src/duckdb/src/main/capi/v1/logical_types-c.cpp index d96ee3f5d..540e3ba3b 100644 --- a/src/duckdb/src/main/capi/v1/logical_types-c.cpp +++ b/src/duckdb/src/main/capi/v1/logical_types-c.cpp @@ -198,7 +198,7 @@ uint8_t duckdb_decimal_width(duckdb_logical_type type) { return 0; } auto &logical_type = *(reinterpret_cast(type)); - return duckdb::DecimalType::GetWidth(logical_type); + return duckdb::NumericCast(duckdb::DecimalType::GetWidth(logical_type)); } uint8_t duckdb_decimal_scale(duckdb_logical_type type) { @@ -206,7 +206,7 @@ uint8_t duckdb_decimal_scale(duckdb_logical_type type) { return 0; } auto &logical_type = *(reinterpret_cast(type)); - return duckdb::DecimalType::GetScale(logical_type); + return duckdb::NumericCast(duckdb::DecimalType::GetScale(logical_type)); } duckdb_type duckdb_decimal_internal_type(duckdb_logical_type type) { diff --git a/src/duckdb/src/main/capi/v1/result-c.cpp b/src/duckdb/src/main/capi/v1/result-c.cpp index 8d127cd19..9ccc60f2a 100644 --- a/src/duckdb/src/main/capi/v1/result-c.cpp +++ b/src/duckdb/src/main/capi/v1/result-c.cpp @@ -186,6 +186,10 @@ duckdb_state deprecated_duckdb_translate_column(QueryResult &result, duckdb_colu } // then write the data switch (result.GetTypes()[col].id()) { + case LogicalTypeId::SQLNULL: + // every value of a SQLNULL column is NULL, which the nullmask already reflects - zero the data + memset(column->deprecated_data, 0, type_size * row_count); + break; case LogicalTypeId::BOOLEAN: WriteData(column, collection, column_ids); break; diff --git a/src/duckdb/src/main/capi/v1/table_function-c.cpp b/src/duckdb/src/main/capi/v1/table_function-c.cpp index 82f4472b2..92598e08a 100644 --- a/src/duckdb/src/main/capi/v1/table_function-c.cpp +++ b/src/duckdb/src/main/capi/v1/table_function-c.cpp @@ -186,6 +186,8 @@ duckdb_table_function duckdb_create_table_function() { duckdb::CTableFunctionInit, duckdb::CTableFunctionLocalInit); function->function_info = duckdb::make_shared_ptr(); function->cardinality = duckdb::CTableFunctionCardinality; + // a function registered through the legacy C API makes no stability promise + function->stability = duckdb::FunctionStability::VOLATILE; return reinterpret_cast(function); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp b/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp index ba944aa9d..e8f64b6c2 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp @@ -495,8 +495,8 @@ DUCKDB_V2_ERROR duckdb_v2_arrow_importer_destroy(duckdb_v2_arrow_importer_handle //---------------------------------------------------------------------------------------------------------------------- DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_create(duckdb_v2_context_handle context, - const duckdb_v2_logical_type_handle *types, const duckdb_v2_str *names, - idx_t count, idx_t batch_size, + const duckdb_v2_logical_type_handle *types, const char **names, + const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(context); @@ -514,16 +514,14 @@ DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_create(duckdb_v2_context_handle context exporter->batch_size = batch_size; exporter->types.reserve(count); exporter->names.reserve(count); + string_view_array name_views(names, names_lengths, count); for (idx_t i = 0; i < count; i++) { if (!types[i]) { throw duckdb::InvalidInputException("null logical type at index %llu", i); } - if (IsNullArgument(&names[i])) { - throw duckdb::InvalidInputException("malformed column name at index %llu", i); - } auto type = Convert(types[i]); exporter->types.push_back(*type); - exporter->names.emplace_back(ConvertIdentifierName(names[i])); + exporter->names.emplace_back(name_views[i]); } // Pin the settings and the extension map now: the schema below and every array this exporter produces are built // from them, which is what keeps the two consistent. @@ -617,7 +615,7 @@ DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_destroy(duckdb_v2_arrow_exporter_handle DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow(duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, + const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err) { @@ -629,10 +627,11 @@ DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow(duckdb_v2_connection_handle co return NullArgumentError(err, __func__, "parameter_values"); } return WithErrorHandler(err, [&]() { - *out_result = ConvertArrowResult(ExecuteStatementV2(Convert(conn)->context, *Convert(statement), - parameter_names, parameter_values, parameter_count, - __func__, ArrowResultFormat(batch_size)) - .release()); + *out_result = ConvertArrowResult( + ExecuteStatementV2(Convert(conn)->context, *Convert(statement), + string_view_array(parameter_names, parameter_names_lengths, parameter_count), + parameter_values, parameter_count, __func__, ArrowResultFormat(batch_size)) + .release()); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_catalog.cpp b/src/duckdb/src/main/capi/v2/capi_v2_catalog.cpp index badd2e281..eb452049b 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_catalog.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_catalog.cpp @@ -98,12 +98,14 @@ DUCKDB_V2_ERROR duckdb_v2_table_description_destroy(duckdb_v2_table_description_ // Column Description //---------------------------------------------------------------------------------------------------------------------- -DUCKDB_V2_ERROR duckdb_v2_column_description_get_name(duckdb_v2_column_description_handle column, - duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_column_description_get_name(duckdb_v2_column_description_handle column, const char **name, + idx_t *name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(column); DUCKDB_CHECK_ARG(name); - *name = duckdb_v2_identifier_t {nullptr, 0}; - return WithErrorHandler(err, [&]() { *name = Convert(Convert(column)->Name()); }); + DUCKDB_CHECK_ARG(name_length); + *name = nullptr; + *name_length = 0; + return WithErrorHandler(err, [&]() { SetStringOut(name, name_length, Convert(column)->Name()); }); } DUCKDB_V2_ERROR duckdb_v2_column_description_get_type(duckdb_v2_column_description_handle column, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_config.cpp b/src/duckdb/src/main/capi/v2/capi_v2_config.cpp index 3c8a6c748..b28ca4419 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_config.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_config.cpp @@ -87,53 +87,54 @@ DUCKDB_V2_ERROR duckdb_v2_context_get_config(duckdb_v2_context_handle ctx, duckd return WithErrorHandler(err, [&]() { *out_config = Convert(&Convert(ctx)->config_handle); }); } -DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_value_handle *out_value, DUCKDB_V2_SETTING_SCOPE *out_scope, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(config); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(out_value); DUCKDB_CHECK_ARG(out_scope); *out_value = nullptr; return WithErrorHandler(err, [&]() { duckdb::Value value; - *out_scope = Convert(config)->ReadValue(ConvertIdentifierName(name), value); + *out_scope = Convert(config)->ReadValue(ConvertIdentifierName(name, name_length), value); *out_value = Convert(new duckdb::Value(std::move(value))); }); } -DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_value_handle value, DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(config); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(value); return WithErrorHandler(err, [&]() { - Convert(config)->Write(duckdb::Identifier(ConvertIdentifierName(name)), *Convert(value), scope); + Convert(config)->Write(duckdb::Identifier(ConvertIdentifierName(name, name_length)), *Convert(value), scope); }); } -DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, - const duckdb_v2_str *setting, DUCKDB_V2_SETTING_SCOPE scope, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_handle config, const char *name, idx_t name_length, + const char *setting, idx_t setting_length, + DUCKDB_V2_SETTING_SCOPE scope, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(config); - DUCKDB_CHECK_ARG(name); - DUCKDB_CHECK_ARG(setting); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_STR_ARG(setting, setting_length); return WithErrorHandler(err, [&]() { - Convert(config)->Write(duckdb::Identifier(ConvertIdentifierName(name)), - duckdb::Value(duckdb::string(Convert(setting))), scope); + Convert(config)->Write(duckdb::Identifier(ConvertIdentifierName(name, name_length)), + duckdb::Value(duckdb::string(Convert(setting, setting_length))), scope); }); } -DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_name(duckdb_v2_config_handle config, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_name(duckdb_v2_config_handle config, const char *name, idx_t name_length, duckdb_v2_option_handle *out_option, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(config); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(out_option); *out_option = nullptr; - return WithErrorHandler( - err, [&]() { *out_option = Convert(Convert(config)->GetOption(ConvertIdentifierName(name)).release()); }); + return WithErrorHandler(err, [&]() { + *out_option = Convert(Convert(config)->GetOption(ConvertIdentifierName(name, name_length)).release()); + }); } DUCKDB_V2_ERROR duckdb_v2_config_get_option_count(duckdb_v2_config_handle config, idx_t *out_count, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_custom_option.cpp b/src/duckdb/src/main/capi/v2/capi_v2_custom_option.cpp index 99e03d37f..9a5d90bbb 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_custom_option.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_custom_option.cpp @@ -156,11 +156,12 @@ DUCKDB_V2_ERROR duckdb_v2_custom_option_create(duckdb_v2_factory_handle factory, }); } -DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, - const duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(option); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(option)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(option)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_custom_option_set_type(duckdb_v2_custom_option_handle option, @@ -181,12 +182,12 @@ DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_value(duckdb_v2_custom_optio return WithErrorHandler(err, [&]() { Convert(option)->default_value = *Convert(value); }); } -DUCKDB_V2_ERROR duckdb_v2_custom_option_set_description(duckdb_v2_custom_option_handle option, - const duckdb_v2_str *description, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_custom_option_set_description(duckdb_v2_custom_option_handle option, const char *description, + idx_t description_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(option); - DUCKDB_CHECK_ARG(description); - return WithErrorHandler(err, [&]() { Convert(option)->description = duckdb::string(Convert(description)); }); + DUCKDB_CHECK_STR_ARG(description, description_length); + return WithErrorHandler( + err, [&]() { Convert(option)->description = duckdb::string(Convert(description, description_length)); }); } DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_scope(duckdb_v2_custom_option_handle option, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_custom_type.cpp b/src/duckdb/src/main/capi/v2/capi_v2_custom_type.cpp index 74ba3a4fd..c8c6bd273 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_custom_type.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_custom_type.cpp @@ -58,11 +58,12 @@ DUCKDB_V2_ERROR duckdb_v2_custom_type_create(duckdb_v2_factory_handle factory, d }); } -DUCKDB_V2_ERROR duckdb_v2_custom_type_set_name(duckdb_v2_custom_type_handle type, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_custom_type_set_name(duckdb_v2_custom_type_handle type, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(type); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(type)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(type)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_custom_type_set_base_type(duckdb_v2_custom_type_handle type, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_error.cpp b/src/duckdb/src/main/capi/v2/capi_v2_error.cpp index 792d688cb..c71c9ce22 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_error.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_error.cpp @@ -2,30 +2,36 @@ using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_handle info, duckdb_v2_str *out_text) { - if (!info || !out_text) { +DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_handle info, const char **out_text, + idx_t *out_text_length) { + if (!info || !out_text || !out_text_length) { return DUCKDB_V2_ERROR_INPUT_INVALID; } const auto *ei = Convert(info); - *out_text = Convert(ei->message); + SetStringOut(out_text, out_text_length, ei->message); return DUCKDB_V2_ERROR_NONE; } -DUCKDB_V2_ERROR duckdb_v2_error_info_get_raw_text(duckdb_v2_error_info_handle info, duckdb_v2_str *out_raw_text) { - if (!info || !out_raw_text) { +DUCKDB_V2_ERROR duckdb_v2_error_info_get_raw_text(duckdb_v2_error_info_handle info, const char **out_raw_text, + idx_t *out_raw_text_length) { + if (!info || !out_raw_text || !out_raw_text_length) { return DUCKDB_V2_ERROR_INPUT_INVALID; } const auto *ei = Convert(info); - *out_raw_text = ei->raw_message ? Convert(ei->raw_message.value()) : duckdb_v2_str {nullptr, 0}; + SetStringOut(out_raw_text, out_raw_text_length, + ei->raw_message ? std::string_view(ei->raw_message.value()) : std::string_view()); return DUCKDB_V2_ERROR_NONE; } -DUCKDB_V2_ERROR duckdb_v2_error_info_set_text(duckdb_v2_error_info_handle info, const duckdb_v2_str *text) { - if (!info || IsNullArgument(text)) { +DUCKDB_V2_ERROR duckdb_v2_error_info_set_text(duckdb_v2_error_info_handle info, const char *text, idx_t text_length) { + if (!info) { + return DUCKDB_V2_ERROR_NONE; + } + if (IsNullArgument(text, text_length)) { return DUCKDB_V2_ERROR_INPUT_INVALID; } auto *ei = Convert(info); - ei->message = Convert(text); + ei->message = Convert(text, text_length); ei->raw_message.reset(); // Directly-set message has no raw body. return DUCKDB_V2_ERROR_NONE; } @@ -41,7 +47,7 @@ DUCKDB_V2_ERROR duckdb_v2_error_info_get_code(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR duckdb_v2_error_info_set_code(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR code) { if (!info) { - return DUCKDB_V2_ERROR_INPUT_INVALID; + return DUCKDB_V2_ERROR_NONE; } const auto ei = Convert(info); ei->code = code; diff --git a/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp b/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp index c9cef4d26..f86af63db 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp @@ -174,16 +174,18 @@ DUCKDB_V2_ERROR duckdb_v2_expression_column_ref_get_index(duckdb_v2_expression_h }); } -DUCKDB_V2_ERROR duckdb_v2_expression_function_get_name(duckdb_v2_expression_handle expression, - duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_expression_function_get_name(duckdb_v2_expression_handle expression, const char **name, + idx_t *name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(expression); DUCKDB_CHECK_ARG(name); - *name = duckdb_v2_identifier_t {nullptr, 0}; + DUCKDB_CHECK_ARG(name_length); + *name = nullptr; + *name_length = 0; return WithErrorHandler(err, [&]() { const auto &function = CV2ExpressionRequireFunction(*Convert(expression), "duckdb_v2_expression_function_get_name"); // Borrowed from the bound function's own name, which lives as long as the node. - *name = Convert(function.GetName()); + SetStringOut(name, name_length, function.GetName()); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_extension.cpp b/src/duckdb/src/main/capi/v2/capi_v2_extension.cpp index b1145dcc9..bd90dd5ee 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_extension.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_extension.cpp @@ -85,7 +85,7 @@ class CAPIV2LoadScope { //! Called by the extension to get a pointer to the correctly versioned extension C API struct. Runs directly under the //! extension's call frame, so it reports failure through the load state rather than throwing. -const void *ExtensionGetAPIV2(duckdb_v2_extension_handle handle, const char *version) { +const void *ExtensionGetAPIV2(duckdb_v2_extension_handle handle, const char *version, idx_t version_length) { if (!handle) { return nullptr; } @@ -94,7 +94,7 @@ const void *ExtensionGetAPIV2(duckdb_v2_extension_handle handle, const char *ver // C_STRUCT_UNSTABLE extensions are tied 1:1 to a DuckDB version, so they always receive the whole struct and // the version they report is a build tag rather than a semver. if (load_state.init_result.abi_type == ExtensionABIType::C_STRUCT) { - string version_string = version ? version : ""; + string version_string = version ? string(version, version_length) : string(); idx_t major, minor, patch; const auto parsed = VersioningUtils::ParseSemver(version_string, major, minor, patch); if (!parsed || major != DUCKDB_EXTENSION_API_V2_VERSION_MAJOR || diff --git a/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp b/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp index e0704579a..8c83df6b6 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp @@ -142,14 +142,14 @@ DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_flag(duckdb_v2_file_open_options return WithErrorHandler(err, [&]() { ApplyFileFlag(*Convert(options), flag); }); } -DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_value(duckdb_v2_file_open_options_handle options, - const duckdb_v2_str *name, duckdb_v2_value_handle value, +DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_value(duckdb_v2_file_open_options_handle options, const char *name, + idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(options); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(value); return WithErrorHandler(err, [&]() { - auto key = duckdb::string(Convert(name)); + auto key = duckdb::string(Convert(name, name_length)); if (key.empty()) { throw duckdb::InvalidInputException("A file option name cannot be empty."); } @@ -169,11 +169,11 @@ DUCKDB_V2_ERROR duckdb_v2_file_open_options_destroy(duckdb_v2_file_open_options_ }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_system, const duckdb_v2_str *file_path, - duckdb_v2_file_open_options_handle options, +DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_system, const char *file_path, + idx_t file_path_length, duckdb_v2_file_open_options_handle options, duckdb_v2_file_handle *out_file_handle, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(file_path); + DUCKDB_CHECK_STR_ARG(file_path, file_path_length); DUCKDB_CHECK_ARG(options); DUCKDB_CHECK_ARG(out_file_handle); *out_file_handle = nullptr; @@ -190,7 +190,7 @@ DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_sys "cache."); } - duckdb::OpenFileInfo info(duckdb::string(Convert(file_path))); + duckdb::OpenFileInfo info(duckdb::string(Convert(file_path, file_path_length))); info.extended_info = opts.extended_info; // No opener is passed: FileSystem::GetFileSystem hands back the context's own OpenerFileSystem, which @@ -207,50 +207,51 @@ DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_sys }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_path_exists(duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, - bool *out_exists, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_file_system_path_exists(duckdb_v2_file_system_handle file_system, const char *path, + idx_t path_length, bool *out_exists, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(path); + DUCKDB_CHECK_STR_ARG(path, path_length); DUCKDB_CHECK_ARG(out_exists); return WithErrorHandler( - err, [&]() { *out_exists = Convert(file_system)->fs.FileExists(duckdb::string(Convert(path))); }); + err, [&]() { *out_exists = Convert(file_system)->fs.FileExists(duckdb::string(Convert(path, path_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file_system_handle file_system, - const duckdb_v2_str *path, bool *out_is_remote, +DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file_system_handle file_system, const char *path, + idx_t path_length, bool *out_is_remote, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(path); + DUCKDB_CHECK_STR_ARG(path, path_length); DUCKDB_CHECK_ARG(out_is_remote); return WithErrorHandler( - err, [&]() { *out_is_remote = duckdb::FileSystem::IsRemoteFile(duckdb::string(Convert(path))); }); + err, [&]() { *out_is_remote = duckdb::FileSystem::IsRemoteFile(duckdb::string(Convert(path, path_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, - duckdb_v2_text_sink_fn sink, void *user_data, +DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_system_handle file_system, const char *path, + idx_t path_length, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(path); + DUCKDB_CHECK_STR_ARG(path, path_length); DUCKDB_CHECK_ARG(sink); return WithErrorHandler(err, [&]() { - auto expanded = Convert(file_system)->fs.ExpandPath(duckdb::string(Convert(path))); - InvokeTextSink(sink, duckdb_v2_str {expanded.data(), expanded.size()}, user_data); + auto expanded = Convert(file_system)->fs.ExpandPath(duckdb::string(Convert(path, path_length))); + InvokeTextSink(sink, expanded, user_data); }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_system_handle file_system, const duckdb_v2_str *pattern, +DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_system_handle file_system, const char *pattern, + idx_t pattern_length, duckdb_v2_file_system_path_glob_callback_fn callback, void *user_data, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(pattern); + DUCKDB_CHECK_STR_ARG(pattern, pattern_length); DUCKDB_CHECK_ARG(callback); return WithErrorHandler(err, [&]() { - auto matches = Convert(file_system)->fs.Glob(duckdb::string(Convert(pattern))); + auto matches = Convert(file_system)->fs.Glob(duckdb::string(Convert(pattern, pattern_length))); for (auto &match : matches) { CV2ErrorInfo info; auto handle = Convert(&info); - duckdb_v2_str path {match.path.data(), match.path.size()}; - callback(&path, user_data, &handle); + callback(match.path.data(), match.path.size(), user_data, &handle); if (info.HasError()) { info.ThrowAsException(); } @@ -258,22 +259,26 @@ DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_system_handle fil }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_path_move(duckdb_v2_file_system_handle file_system, const duckdb_v2_str *source, - const duckdb_v2_str *target, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_file_system_path_move(duckdb_v2_file_system_handle file_system, const char *source, + idx_t source_length, const char *target, idx_t target_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(source); - DUCKDB_CHECK_ARG(target); + DUCKDB_CHECK_STR_ARG(source, source_length); + DUCKDB_CHECK_STR_ARG(target, target_length); return WithErrorHandler(err, [&]() { - Convert(file_system)->fs.MoveFile(duckdb::string(Convert(source)), duckdb::string(Convert(target))); + Convert(file_system) + ->fs.MoveFile(duckdb::string(Convert(source, source_length)), + duckdb::string(Convert(target, target_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_file_system_path_remove(duckdb_v2_file_system_handle file_system, const duckdb_v2_str *path, - bool *out_removed, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_file_system_path_remove(duckdb_v2_file_system_handle file_system, const char *path, + idx_t path_length, bool *out_removed, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(file_system); - DUCKDB_CHECK_ARG(path); + DUCKDB_CHECK_STR_ARG(path, path_length); return WithErrorHandler(err, [&]() { - auto removed = Convert(file_system)->fs.TryRemoveFile(duckdb::string(Convert(path))); + auto removed = Convert(file_system)->fs.TryRemoveFile(duckdb::string(Convert(path, path_length))); if (out_removed) { *out_removed = removed; } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func.cpp index 597089d82..e0aecec15 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func.cpp @@ -142,25 +142,27 @@ DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_value(duckdb_v2_function_bind_in } DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_name(duckdb_v2_function_bind_info_handle info, idx_t index, - duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err) { + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_ARG(name_length); return WithErrorHandler(err, [&]() { auto &bind_info = *Convert(info); CheckArgIndex(bind_info, index, "duckdb_v2_function_bind_get_arg_name"); - *name = Convert(bind_info.GetArgName(index)); + SetStringOut(name, name_length, bind_info.GetArgName(index)); }); } -DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_index(duckdb_v2_function_bind_info_handle info, - const duckdb_v2_identifier_t *name, idx_t *index, bool *found, +DUCKDB_V2_ERROR duckdb_v2_function_bind_get_arg_index(duckdb_v2_function_bind_info_handle info, const char *name, + idx_t name_length, idx_t *index, bool *found, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(index); DUCKDB_CHECK_ARG(found); return WithErrorHandler(err, [&]() { - auto entry = Convert(info)->FindArg(duckdb::Identifier(ConvertIdentifierName(name))); + auto entry = Convert(info)->FindArg(duckdb::Identifier(ConvertIdentifierName(name, name_length))); *found = entry.IsValid(); if (entry.IsValid()) { *index = entry.GetIndex(); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp index 576d5a2fd..bef5544d8 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp @@ -480,11 +480,12 @@ DUCKDB_V2_ERROR duckdb_v2_aggregate_function_create(duckdb_v2_factory_handle fac }); } -DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_name(duckdb_v2_aggregate_function_handle function, - const duckdb_v2_str *name, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_name(duckdb_v2_aggregate_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_docs(duckdb_v2_aggregate_function_handle function, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp index 9f02cd3ec..2bafecc30 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp @@ -843,12 +843,12 @@ static auto GetColumnType(INFO &args, idx_t index, const char *function) -> duck } template -static auto GetColumnName(INFO &args, idx_t index, const char *function) -> duckdb_v2_identifier_t { +static auto GetColumnName(INFO &args, idx_t index, const char *function) -> const auto & { const auto &names = *args.in_names; if (index >= names.size()) { throw InvalidInputException("Index out of bounds in %s", function); } - return Convert(names[index]); + return names[index]; } template @@ -897,20 +897,21 @@ DUCKDB_V2_ERROR duckdb_v2_copy_function_create(duckdb_v2_factory_handle factory, }); } -DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_function_handle function, const duckdb_v2_str *name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_copy_function_set_file_extension(duckdb_v2_copy_function_handle function, - const duckdb_v2_str *extension, + const char *extension, idx_t extension_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(extension); + DUCKDB_CHECK_STR_ARG(extension, extension_length); return WithErrorHandler(err, [&]() { - duckdb::string value(extension->ptr, extension->len); + duckdb::string value(Convert(extension, extension_length)); if (!value.empty() && value[0] == '.') { throw duckdb::InvalidInputException("The file extension of a copy function is set without its leading dot, " "e.g. \"parquet\" rather than \".parquet\"."); @@ -996,11 +997,12 @@ DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_set_bind_data(duckdb_v2_copy_to_bind_info }); } -DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_file_path(duckdb_v2_copy_to_bind_info_handle info, duckdb_v2_str *path, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_file_path(duckdb_v2_copy_to_bind_info_handle info, const char **path, + idx_t *path_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(path); - return WithErrorHandler(err, [&]() { *path = Convert(*Convert(info)->in_file_path); }); + DUCKDB_CHECK_ARG(path_length); + return WithErrorHandler(err, [&]() { SetStringOut(path, path_length, *Convert(info)->in_file_path); }); } DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_count(duckdb_v2_copy_to_bind_info_handle info, idx_t *count, @@ -1021,11 +1023,14 @@ DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_type(duckdb_v2_copy_to_bind_in } DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_name(duckdb_v2_copy_to_bind_info_handle info, idx_t index, - duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err) { + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(name); - return WithErrorHandler( - err, [&]() { *name = GetColumnName(*Convert(info), index, "duckdb_v2_copy_to_bind_get_column_name"); }); + DUCKDB_CHECK_ARG(name_length); + return WithErrorHandler(err, [&]() { + SetStringOut(name, name_length, GetColumnName(*Convert(info), index, "duckdb_v2_copy_to_bind_get_column_name")); + }); } DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_count(duckdb_v2_copy_to_bind_info_handle info, idx_t *count, @@ -1036,11 +1041,14 @@ DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_count(duckdb_v2_copy_to_bind_i } DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_name(duckdb_v2_copy_to_bind_info_handle info, idx_t index, - duckdb_v2_identifier_t *name, duckdb_v2_error_info_handle *err) { + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_ARG(name_length); return WithErrorHandler(err, [&]() { - *name = Convert(*GetOption(*Convert(info), index, "duckdb_v2_copy_to_bind_get_option_name").first); + SetStringOut(name, name_length, + *GetOption(*Convert(info), index, "duckdb_v2_copy_to_bind_get_option_name").first); }); } @@ -1096,11 +1104,12 @@ DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_bind_data(duckdb_v2_copy_to_init_info return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); } -DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_file_path(duckdb_v2_copy_to_init_info_handle info, duckdb_v2_str *path, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_file_path(duckdb_v2_copy_to_init_info_handle info, const char **path, + idx_t *path_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(path); - return WithErrorHandler(err, [&]() { *path = Convert(*Convert(info)->in_file_path); }); + DUCKDB_CHECK_ARG(path_length); + return WithErrorHandler(err, [&]() { SetStringOut(path, path_length, *Convert(info)->in_file_path); }); } DUCKDB_V2_ERROR duckdb_v2_copy_to_init_set_init_data(duckdb_v2_copy_to_init_info_handle info, duckdb_v2_opaque *data, @@ -1274,11 +1283,12 @@ DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_set_bind_data(duckdb_v2_copy_from_bind_ }); } -DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_file_path(duckdb_v2_copy_from_bind_info_handle info, duckdb_v2_str *path, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_file_path(duckdb_v2_copy_from_bind_info_handle info, const char **path, + idx_t *path_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(path); - return WithErrorHandler(err, [&]() { *path = Convert(*Convert(info)->in_file_path); }); + DUCKDB_CHECK_ARG(path_length); + return WithErrorHandler(err, [&]() { SetStringOut(path, path_length, *Convert(info)->in_file_path); }); } DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_count(duckdb_v2_copy_from_bind_info_handle info, idx_t *count, @@ -1299,12 +1309,15 @@ DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_type(duckdb_v2_copy_from_bin } DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_name(duckdb_v2_copy_from_bind_info_handle info, idx_t index, - duckdb_v2_identifier_t *name, + const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(name); - return WithErrorHandler( - err, [&]() { *name = GetColumnName(*Convert(info), index, "duckdb_v2_copy_from_bind_get_column_name"); }); + DUCKDB_CHECK_ARG(name_length); + return WithErrorHandler(err, [&]() { + SetStringOut(name, name_length, + GetColumnName(*Convert(info), index, "duckdb_v2_copy_from_bind_get_column_name")); + }); } DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_count(duckdb_v2_copy_from_bind_info_handle info, idx_t *count, @@ -1315,12 +1328,14 @@ DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_count(duckdb_v2_copy_from_bi } DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_name(duckdb_v2_copy_from_bind_info_handle info, idx_t index, - duckdb_v2_identifier_t *name, + const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_ARG(name_length); return WithErrorHandler(err, [&]() { - *name = Convert(*GetOption(*Convert(info), index, "duckdb_v2_copy_from_bind_get_option_name").first); + SetStringOut(name, name_length, + *GetOption(*Convert(info), index, "duckdb_v2_copy_from_bind_get_option_name").first); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_docs.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_docs.cpp index cc3f07cfa..14d89af67 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_docs.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_docs.cpp @@ -6,30 +6,29 @@ using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_function_docs_set_description(duckdb_v2_function_docs_handle docs, - const duckdb_v2_str *description, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_function_docs_set_description(duckdb_v2_function_docs_handle docs, const char *description, + idx_t description_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(docs); - DUCKDB_CHECK_ARG(description); - return WithErrorHandler(err, [&]() { Convert(docs)->description = duckdb::string(Convert(description)); }); + DUCKDB_CHECK_STR_ARG(description, description_length); + return WithErrorHandler( + err, [&]() { Convert(docs)->description = duckdb::string(Convert(description, description_length)); }); } -DUCKDB_V2_ERROR duckdb_v2_function_docs_add_example(duckdb_v2_function_docs_handle docs, const duckdb_v2_str *title, - const duckdb_v2_str *example, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_function_docs_add_example(duckdb_v2_function_docs_handle docs, const char *title, + idx_t title_length, const char *example, idx_t example_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(docs); - if (title) { - DUCKDB_CHECK_ARG(title); - } - DUCKDB_CHECK_ARG(example); + DUCKDB_CHECK_STR_ARG(title, title_length); + DUCKDB_CHECK_STR_ARG(example, example_length); return WithErrorHandler(err, [&]() { - duckdb::string title_text = title ? duckdb::string(Convert(title)) : duckdb::string(); - Convert(docs)->examples.push_back({std::move(title_text), duckdb::string(Convert(example))}); + duckdb::string title_text(Convert(title, title_length)); + Convert(docs)->examples.push_back({std::move(title_text), duckdb::string(Convert(example, example_length))}); }); } -DUCKDB_V2_ERROR duckdb_v2_function_docs_add_category(duckdb_v2_function_docs_handle docs, const duckdb_v2_str *category, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_function_docs_add_category(duckdb_v2_function_docs_handle docs, const char *category, + idx_t category_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(docs); - DUCKDB_CHECK_ARG(category); - return WithErrorHandler(err, [&]() { Convert(docs)->categories.emplace_back(Convert(category)); }); + DUCKDB_CHECK_STR_ARG(category, category_length); + return WithErrorHandler(err, [&]() { Convert(docs)->categories.emplace_back(Convert(category, category_length)); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_macro.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_macro.cpp index 098cdef4b..e49438a07 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_macro.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_macro.cpp @@ -142,19 +142,19 @@ DUCKDB_V2_ERROR duckdb_v2_macro_function_create(duckdb_v2_factory_handle factory }); } -DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_function_handle function, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } -DUCKDB_V2_ERROR duckdb_v2_macro_function_set_body(duckdb_v2_macro_function_handle function, const duckdb_v2_str *body, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_macro_function_set_body(duckdb_v2_macro_function_handle function, const char *body, + idx_t body_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(body); - return WithErrorHandler(err, [&]() { Convert(function)->body = duckdb::string(Convert(body)); }); + DUCKDB_CHECK_STR_ARG(body, body_length); + return WithErrorHandler(err, [&]() { Convert(function)->body = duckdb::string(Convert(body, body_length)); }); } DUCKDB_V2_ERROR duckdb_v2_macro_function_get_signature(duckdb_v2_macro_function_handle function, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_pragma.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_pragma.cpp index 6082cf61a..80c7567be 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_pragma.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_pragma.cpp @@ -140,12 +140,12 @@ DUCKDB_V2_ERROR duckdb_v2_pragma_function_create(duckdb_v2_factory_handle factor }); } -DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_name(duckdb_v2_pragma_function_handle function, - const duckdb_v2_identifier_t *name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_name(duckdb_v2_pragma_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_docs(duckdb_v2_pragma_function_handle function, @@ -189,11 +189,11 @@ DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_exec_callback(duckdb_v2_pragma_fun } DUCKDB_V2_ERROR duckdb_v2_pragma_function_query_set_query(duckdb_v2_pragma_function_query_info_handle info, - const duckdb_v2_str *query, + const char *query, idx_t query_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(query); - return WithErrorHandler(err, [&]() { Convert(info)->out_query = duckdb::string(Convert(query)); }); + DUCKDB_CHECK_STR_ARG(query, query_length); + return WithErrorHandler(err, [&]() { Convert(info)->out_query = duckdb::string(Convert(query, query_length)); }); } DUCKDB_V2_ERROR duckdb_v2_connection_register_pragma_function(duckdb_v2_connection_handle conn, 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 87d2fa6b4..6f158a304 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 @@ -378,11 +378,12 @@ DUCKDB_V2_ERROR duckdb_v2_scalar_function_create(duckdb_v2_factory_handle factor }); } -DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_name(duckdb_v2_scalar_function_handle function, const duckdb_v2_str *name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_name(duckdb_v2_scalar_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_docs(duckdb_v2_scalar_function_handle function, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_signature.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_signature.cpp index 4c0942ad8..95d91729c 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_signature.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_signature.cpp @@ -21,7 +21,7 @@ static auto ConvertParameterKind(DUCKDB_V2_FUNCTION_PARAMETER_KIND kind) -> duck } DUCKDB_V2_ERROR -duckdb_v2_function_signature_add_parameter(duckdb_v2_function_signature_handle sig, const duckdb_v2_identifier_t *name, +duckdb_v2_function_signature_add_parameter(duckdb_v2_function_signature_handle sig, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_value_handle value, DUCKDB_V2_FUNCTION_PARAMETER_KIND kind, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(sig); @@ -30,7 +30,7 @@ duckdb_v2_function_signature_add_parameter(duckdb_v2_function_signature_handle s return WithErrorHandler(err, [&]() { auto &signature = *Convert(sig); auto param_kind = ConvertParameterKind(kind); - auto param_name = duckdb::Identifier(ConvertIdentifierName(name)); + auto param_name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); duckdb::optional default_value; if (value) { default_value = *Convert(value); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp index dcc5f7ce5..29fe5e07d 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 @@ -885,6 +885,9 @@ class CV2TableFunction { function.get_bind_info = CV2TableGetBindInfo; } + // a function registered through the C API makes no stability promise unless one was declared + function.stability = stability; + info.name = name; function.function_info = make_shared_ptr(std::move(info)); @@ -898,6 +901,7 @@ class CV2TableFunction { CV2FunctionDocs docs; CV2TableFunctionInfo info; Identifier name; + FunctionStability stability = FunctionStability::VOLATILE; }; static auto Convert(duckdb_v2_table_function_handle func) -> CV2TableFunction * { @@ -1008,11 +1012,12 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_create(duckdb_v2_factory_handle factory }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handle function, const duckdb_v2_str *name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_table_function_get_docs(duckdb_v2_table_function_handle function, @@ -1116,11 +1121,11 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback(duckdb_v2_table_func } DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column(duckdb_v2_table_function_bind_info_handle info, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(type); return WithErrorHandler(err, [&]() { auto column_type_ref = Convert(type); @@ -1130,7 +1135,7 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column(duckdb_v2_table_ throw duckdb::InvalidInputException("Result column type must be a fully defined concrete type"); } auto &bind_info = *Convert(info); - bind_info.out_column_names.emplace_back(ConvertIdentifierName(name)); + bind_info.out_column_names.emplace_back(ConvertIdentifierName(name, name_length)); bind_info.out_column_types.push_back(column_type); }); } @@ -1791,13 +1796,14 @@ duckdb_v2_table_function_get_bind_info_set_column_identifier(duckdb_v2_table_fun DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_option(duckdb_v2_table_function_get_bind_info_info_handle info, - duckdb_v2_str *key, duckdb_v2_value_handle value, + const char *key, idx_t key_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(key); + DUCKDB_CHECK_STR_ARG(key, key_length); DUCKDB_CHECK_ARG(value); - return WithErrorHandler( - err, [&]() { Convert(info)->out_bind_info.options[duckdb::string(Convert(*key))] = *Convert(value); }); + return WithErrorHandler(err, [&]() { + Convert(info)->out_bind_info.options[duckdb::string(Convert(key, key_length))] = *Convert(value); + }); } //---------------------------------------------------------------------------------------------------------------------- @@ -1816,37 +1822,38 @@ DUCKDB_V2_ERROR duckdb_v2_multi_file_function_create(duckdb_v2_factory_handle fa }); } -DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, - duckdb_v2_str *name, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(Convert(*name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler(err, [&]() { Convert(function)->name = duckdb::Identifier(Convert(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_single_file_function(duckdb_v2_multi_file_function_handle function, - duckdb_v2_str *name, + const char *name, idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, - [&]() { Convert(function)->single_file_function = duckdb::Identifier(Convert(*name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler( + err, [&]() { Convert(function)->single_file_function = duckdb::Identifier(Convert(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_reader_type(duckdb_v2_multi_file_function_handle function, - duckdb_v2_str *reader_type, + const char *reader_type, idx_t reader_type_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(reader_type); - return WithErrorHandler(err, [&]() { Convert(function)->reader_type = duckdb::string(Convert(*reader_type)); }); + DUCKDB_CHECK_STR_ARG(reader_type, reader_type_length); + return WithErrorHandler( + err, [&]() { Convert(function)->reader_type = duckdb::string(Convert(reader_type, reader_type_length)); }); } DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_file_extension(duckdb_v2_multi_file_function_handle function, - duckdb_v2_str *extension, + const char *extension, idx_t extension_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(extension); + DUCKDB_CHECK_STR_ARG(extension, extension_length); return WithErrorHandler(err, [&]() { - auto file_extension = duckdb::string(Convert(*extension)); + auto file_extension = duckdb::string(Convert(extension, extension_length)); if (duckdb::StringUtil::StartsWith(file_extension, ".")) { throw duckdb::InvalidInputException("The file extension \"%s\" must be given without a leading dot", file_extension); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_identifier.cpp b/src/duckdb/src/main/capi/v2/capi_v2_identifier.cpp index 9af919b2b..d9560a0be 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_identifier.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_identifier.cpp @@ -3,14 +3,14 @@ using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_identifier_render_quoted(const duckdb_v2_identifier_t *name, char *out_text, +DUCKDB_V2_ERROR duckdb_v2_identifier_render_quoted(const char *name, idx_t name_length, char *out_text, idx_t out_capacity, idx_t *out_length, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(out_length); return WithErrorHandler(err, [&]() { *out_length = 0; - auto rendered = duckdb::SQLIdentifier::ToString(duckdb::string(ConvertIdentifierName(name))); + auto rendered = duckdb::SQLIdentifier::ToString(duckdb::string(ConvertIdentifierName(name, name_length))); FillCallerText(out_text, out_capacity, out_length, rendered, "duckdb_v2_identifier_render_quoted"); }); } 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 8225a6e9f..1f32709ed 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp @@ -106,12 +106,12 @@ using namespace duckdb::capiv2; DUCKDB_V2_ERROR duckdb_v2_instance_create(duckdb_v2_environment_handle env, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err) { - return duckdb_v2_instance_create_with_options(env, nullptr, nullptr, 0, out_instance, err); + return duckdb_v2_instance_create_with_options(env, nullptr, nullptr, nullptr, nullptr, 0, out_instance, err); } -DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options(duckdb_v2_environment_handle env, - const duckdb_v2_str *option_names, - const duckdb_v2_str *option_values, idx_t option_count, +DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options(duckdb_v2_environment_handle env, const char **option_names, + const idx_t *option_names_lengths, const char **option_values, + const idx_t *option_values_lengths, idx_t option_count, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(env); @@ -125,12 +125,11 @@ DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options(duckdb_v2_environment_han } return WithErrorHandler(err, [&]() { duckdb::DBConfig startup_config; + string_view_array names(option_names, option_names_lengths, option_count); + string_view_array values(option_values, option_values_lengths, option_count); for (idx_t i = 0; i < option_count; i++) { - if (IsNullArgument(&option_names[i]) || IsNullArgument(&option_values[i])) { - throw duckdb::InvalidInputException("malformed startup option at index %llu", i); - } - startup_config.SetOptionByName(duckdb::Identifier(duckdb::string(Convert(&option_names[i]))), - duckdb::Value(duckdb::string(Convert(&option_values[i])))); + startup_config.SetOptionByName(duckdb::Identifier(duckdb::string(names[i])), + duckdb::Value(duckdb::string(values[i]))); } auto *env_wrapper = Convert(env); auto wrapper = duckdb::make_uniq(*env_wrapper, startup_config); @@ -154,18 +153,16 @@ DUCKDB_V2_ERROR duckdb_v2_instance_destroy(duckdb_v2_instance_handle *instance) }); } -DUCKDB_V2_ERROR duckdb_v2_instance_attach(duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, - const duckdb_v2_str *path, duckdb_v2_attach_options_handle options, +DUCKDB_V2_ERROR duckdb_v2_instance_attach(duckdb_v2_instance_handle instance, const char *name, idx_t name_length, + const char *path, idx_t path_length, duckdb_v2_attach_options_handle options, bool make_default, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(instance); - DUCKDB_CHECK_ARG(path); - if (name) { - DUCKDB_CHECK_ARG(name); - } + DUCKDB_CHECK_STR_ARG(path, path_length); + DUCKDB_CHECK_STR_ARG(name, name_length); return WithErrorHandler(err, [&]() { auto &wrapper = *Convert(instance); - duckdb::Identifier attach_name = name ? duckdb::Identifier(ConvertIdentifierName(name)) : duckdb::Identifier(); - wrapper.Attach(duckdb::string(Convert(path)), attach_name, Convert(options), make_default); + duckdb::Identifier attach_name(ConvertIdentifierName(name, name_length)); + wrapper.Attach(duckdb::string(Convert(path, path_length)), attach_name, Convert(options), make_default); }); } @@ -181,15 +178,16 @@ DUCKDB_V2_ERROR duckdb_v2_attach_options_create(duckdb_v2_instance_handle instan }); } -DUCKDB_V2_ERROR duckdb_v2_attach_options_set(duckdb_v2_attach_options_handle options, const duckdb_v2_identifier_t *key, - const duckdb_v2_str *setting, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_attach_options_set(duckdb_v2_attach_options_handle options, const char *key, idx_t key_length, + const char *setting, idx_t setting_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(options); - DUCKDB_CHECK_ARG(key); - DUCKDB_CHECK_ARG(setting); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_STR_ARG(setting, setting_length); return WithErrorHandler(err, [&]() { // Keys are unquoted SQL identifiers, which the parser lowercases. - auto lowered = duckdb::StringUtil::Lower(duckdb::string(ConvertIdentifierName(key))); - Convert(options)->options[lowered] = duckdb::Value(duckdb::string(Convert(setting))); + auto lowered = duckdb::StringUtil::Lower(duckdb::string(ConvertIdentifierName(key, key_length))); + Convert(options)->options[lowered] = duckdb::Value(duckdb::string(Convert(setting, setting_length))); }); } @@ -205,30 +203,32 @@ DUCKDB_V2_ERROR duckdb_v2_attach_options_destroy(duckdb_v2_attach_options_handle }); } -DUCKDB_V2_ERROR duckdb_v2_instance_detach(duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_instance_detach(duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(instance); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); return WithErrorHandler(err, [&]() { auto &wrapper = *Convert(instance); - wrapper.Detach(duckdb::Identifier(ConvertIdentifierName(name))); + wrapper.Detach(duckdb::Identifier(ConvertIdentifierName(name, name_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_instance_set_default(duckdb_v2_instance_handle instance, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_instance_set_default(duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(instance); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); return WithErrorHandler(err, [&]() { auto &wrapper = *Convert(instance); - wrapper.SetDefault(duckdb::Identifier(ConvertIdentifierName(name))); + wrapper.SetDefault(duckdb::Identifier(ConvertIdentifierName(name, name_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_library_version(duckdb_v2_str *out_version, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_library_version(const char **out_version, idx_t *out_version_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_version); + DUCKDB_CHECK_ARG(out_version_length); return WithErrorHandler(err, [&]() { const auto version = duckdb::DuckDB::LibraryVersion(); - *out_version = duckdb_v2_str {version, std::strlen(version)}; + SetStringOut(out_version, out_version_length, std::string_view(version)); }); } 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 760324d21..65ff63422 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 @@ -44,13 +44,12 @@ class CV2CallbackLogSink final : public LogStorage { void WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type, const string &log_message, const RegisteredLoggingContext &context) override { CV2LogSinkWriteInfo info(context.context); - duckdb_v2_str type {log_type.data(), log_type.size()}; - duckdb_v2_str message {log_message.data(), log_message.size()}; CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); // the values of the level and scope enums match duckdb::LogLevel and duckdb::LogContextScope write_cb(Convert(&info), GetUserData(), timestamp.value, static_cast(level), - static_cast(context.context.scope), &type, &message, &err_ptr); + static_cast(context.context.scope), log_type.data(), log_type.size(), + log_message.data(), log_message.size(), &err_ptr); } void WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) override { @@ -152,11 +151,12 @@ DUCKDB_V2_ERROR duckdb_v2_log_sink_create(duckdb_v2_factory_handle factory, duck }); } -DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(sink); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { Convert(sink)->name = duckdb::string(ConvertIdentifierName(name)); }); + DUCKDB_CHECK_STR_ARG(name, name_length); + return WithErrorHandler(err, + [&]() { Convert(sink)->name = duckdb::string(ConvertIdentifierName(name, name_length)); }); } DUCKDB_V2_ERROR duckdb_v2_log_sink_set_user_data(duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_logging.cpp b/src/duckdb/src/main/capi/v2/capi_v2_logging.cpp index 35287218f..8617ee0be 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_logging.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_logging.cpp @@ -25,14 +25,13 @@ static LogLevel ConvertLogLevel(DUCKDB_V2_LOG_LEVEL level) { } } -static void WriteLog(Logger &logger, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_str *log_type, - const duckdb_v2_str *message) { +static void WriteLog(Logger &logger, DUCKDB_V2_LOG_LEVEL level, std::string_view log_type, std::string_view message) { const auto log_level = ConvertLogLevel(level); // ShouldLog/WriteLog take a C string, so the borrowed view has to be materialized. - const string type(Convert(log_type)); + const string type(log_type); const auto *type_name = type.empty() ? DefaultLogType::NAME : type.c_str(); if (logger.ShouldLog(type_name, log_level)) { - logger.WriteLog(type_name, log_level, string(Convert(message))); + logger.WriteLog(type_name, log_level, string(message)); } } @@ -45,27 +44,32 @@ static void WriteLog(Logger &logger, DUCKDB_V2_LOG_LEVEL level, const duckdb_v2_ using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_context_log(duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, - const duckdb_v2_str *log_type, const duckdb_v2_str *message, +DUCKDB_V2_ERROR duckdb_v2_context_log(duckdb_v2_context_handle ctx, DUCKDB_V2_LOG_LEVEL level, const char *log_type, + idx_t log_type_length, const char *message, idx_t message_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(ctx); - return WithErrorHandler(err, - [&]() { WriteLog(duckdb::Logger::Get(Convert(ctx)->context), level, log_type, message); }); + return WithErrorHandler(err, [&]() { + WriteLog(duckdb::Logger::Get(Convert(ctx)->context), level, Convert(log_type, log_type_length), + Convert(message, message_length)); + }); } DUCKDB_V2_ERROR duckdb_v2_instance_log(duckdb_v2_instance_handle instance, DUCKDB_V2_LOG_LEVEL level, - const duckdb_v2_str *log_type, const duckdb_v2_str *message, - duckdb_v2_error_info_handle *err) { + const char *log_type, idx_t log_type_length, const char *message, + idx_t message_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(instance); return WithErrorHandler(err, [&]() { - WriteLog(duckdb::Logger::Get(*Convert(instance)->GetDatabase().instance), level, log_type, message); + WriteLog(duckdb::Logger::Get(*Convert(instance)->GetDatabase().instance), level, + Convert(log_type, log_type_length), Convert(message, message_length)); }); } DUCKDB_V2_ERROR duckdb_v2_connection_log(duckdb_v2_connection_handle conn, DUCKDB_V2_LOG_LEVEL level, - const duckdb_v2_str *log_type, const duckdb_v2_str *message, - duckdb_v2_error_info_handle *err) { + const char *log_type, idx_t log_type_length, const char *message, + idx_t message_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(conn); - return WithErrorHandler( - err, [&]() { WriteLog(duckdb::Logger::Get(*Convert(conn)->context), level, log_type, message); }); + return WithErrorHandler(err, [&]() { + WriteLog(duckdb::Logger::Get(*Convert(conn)->context), level, Convert(log_type, log_type_length), + Convert(message, message_length)); + }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp b/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp index 78def864a..c237dd766 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp @@ -176,12 +176,13 @@ idx_t TypeParamCount(const LogicalType &type) { // Produces param `index` of `type`: the owned value is returned, the // borrowed name (off the type, or a static literal) goes into out_name, -// which arrives pre-set to the positional {NULL, 0}. The caller has +// which arrives pre-set to the positional empty name. The caller has // bounds-checked index against TypeParamCount. -Value TypeParamValue(const LogicalType &type, idx_t index, duckdb_v2_identifier_t &out_name) { +Value TypeParamValue(const LogicalType &type, idx_t index, std::string_view &out_name) { switch (type.id()) { case LogicalTypeId::DECIMAL: - return index == 0 ? Value::UTINYINT(DecimalType::GetWidth(type)) : Value::UTINYINT(DecimalType::GetScale(type)); + return index == 0 ? Value::UTINYINT(NumericCast(DecimalType::GetWidth(type))) + : Value::UTINYINT(NumericCast(DecimalType::GetScale(type))); case LogicalTypeId::LIST: return Value::TYPE(ListType::GetChildType(type)); case LogicalTypeId::ARRAY: @@ -192,16 +193,19 @@ Value TypeParamValue(const LogicalType &type, idx_t index, duckdb_v2_identifier_ case LogicalTypeId::STRUCT: case LogicalTypeId::TUPLE: if (!StructType::IsUnnamed(type)) { - out_name = Convert(StructType::GetChildName(type, index)); + auto &child_name = StructType::GetChildName(type, index); + out_name = std::string_view(child_name.c_str(), child_name.size()); } return Value::TYPE(StructType::GetChildType(type, index)); - case LogicalTypeId::UNION: - out_name = Convert(UnionType::GetMemberName(type, index)); + case LogicalTypeId::UNION: { + auto &member_name = UnionType::GetMemberName(type, index); + out_name = std::string_view(member_name.c_str(), member_name.size()); return Value::TYPE(UnionType::GetMemberType(type, index)); + } case LogicalTypeId::ENUM: return Value(EnumType::GetString(type, index).GetString()); case LogicalTypeId::VARCHAR: - out_name = duckdb_v2_identifier_t {"collation", 9}; + out_name = "collation"; return Value(StringType::GetCollation(type)); case LogicalTypeId::GEOMETRY: return Value(GeoType::GetCRS(type).GetDefinition()); @@ -241,21 +245,17 @@ auto ResolveCommonType(CV2Factory &factory, const vector &types) -> using namespace duckdb::capiv2; // Collects the parallel (name, value) arrays into bind arguments. An absent -// or {NULL, 0} name makes that parameter positional. -static duckdb::vector CollectTypeArgsV2(const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, - idx_t param_count) { +// or empty name makes that parameter positional. +static duckdb::vector +CollectTypeArgsV2(const string_view_array ¶m_names, const duckdb_v2_value_handle *param_values, idx_t param_count) { duckdb::vector args; args.reserve(param_count); for (idx_t i = 0; i < param_count; i++) { - auto param_name = param_names ? param_names[i] : duckdb_v2_str {nullptr, 0}; - if (!param_name.ptr && param_name.len > 0) { - throw duckdb::InvalidInputException("null parameter name at index %llu", i); - } + auto param_name = param_names[i]; if (!param_values[i]) { throw duckdb::InvalidInputException("null parameter value at index %llu", i); } - args.emplace_back(duckdb::string(ConvertIdentifierName(param_name)), *Convert(param_values[i])); + args.emplace_back(duckdb::string(param_name), *Convert(param_values[i])); } return args; } @@ -264,9 +264,8 @@ static duckdb::vector CollectTypeArgsV2(const duckdb_v2_id // the id resolves to its canonical name and binds through the same path as // create_type_from_name. static void CreateLogicalTypeFromIdV2(CV2Factory &factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, - const duckdb_v2_identifier_t *param_names, - const duckdb_v2_value_handle *param_values, idx_t param_count, - duckdb_v2_logical_type_handle *out_type, const char *fn) { + const string_view_array ¶m_names, const duckdb_v2_value_handle *param_values, + idx_t param_count, duckdb_v2_logical_type_handle *out_type, const char *fn) { if (param_count > 0 && !param_values) { throw duckdb::InvalidInputException("'param_values' cannot be null when param_count > 0"); } @@ -289,8 +288,8 @@ static void CreateLogicalTypeFromIdV2(CV2Factory &factory, DUCKDB_V2_LOGICAL_TYP } DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id(duckdb_v2_factory_handle factory, - DUCKDB_V2_LOGICAL_TYPE_ID type_id, - const duckdb_v2_identifier_t *param_names, + DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err) { @@ -298,15 +297,17 @@ DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id(duckdb_v2_factory_handle f DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_type); return WithErrorHandler(err, [&]() { - CreateLogicalTypeFromIdV2(*Convert(factory), type_id, param_names, param_values, param_count, out_type, fn); + CreateLogicalTypeFromIdV2(*Convert(factory), type_id, + string_view_array(param_names, param_names_lengths, param_count), param_values, + param_count, out_type, fn); }); } -static void CreateLogicalTypeFromTextV2(CV2Factory &factory, const duckdb_v2_str *text, +static void CreateLogicalTypeFromTextV2(CV2Factory &factory, std::string_view text, duckdb_v2_logical_type_handle *out_type) { *out_type = nullptr; // Parse and bind errors propagate. - auto string = duckdb::string(Convert(text)); + auto string = duckdb::string(text); if (!factory.TryGetClientContext()) { *out_type = Convert(duckdb::TypeManager::Get(factory.GetDatabase()).ParseLogicalType(string)); return; @@ -317,17 +318,18 @@ static void CreateLogicalTypeFromTextV2(CV2Factory &factory, const duckdb_v2_str *out_type = Convert(std::move(parsed)); } -DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, const duckdb_v2_str *text, - duckdb_v2_logical_type_handle *out_type, +DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, const char *text, + idx_t text_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_type); - DUCKDB_CHECK_ARG(text); - return WithErrorHandler(err, [&]() { CreateLogicalTypeFromTextV2(*Convert(factory), text, out_type); }); + DUCKDB_CHECK_STR_ARG(text, text_length); + return WithErrorHandler( + err, [&]() { CreateLogicalTypeFromTextV2(*Convert(factory), Convert(text, text_length), out_type); }); } static void CreateLogicalTypeFromArgsV2(CV2Factory &factory, duckdb_v2_qname_handle name, - const duckdb_v2_identifier_t *param_names, + const string_view_array ¶m_names, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type) { if (param_count > 0 && !param_values) { @@ -341,7 +343,7 @@ static void CreateLogicalTypeFromArgsV2(CV2Factory &factory, duckdb_v2_qname_han } DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name(duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, - const duckdb_v2_identifier_t *param_names, + const char **param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err) { @@ -349,7 +351,9 @@ DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name(duckdb_v2_factory_handle DUCKDB_CHECK_ARG(out_type); DUCKDB_CHECK_ARG(name); return WithErrorHandler(err, [&]() { - CreateLogicalTypeFromArgsV2(*Convert(factory), name, param_names, param_values, param_count, out_type); + CreateLogicalTypeFromArgsV2(*Convert(factory), name, + string_view_array(param_names, param_names_lengths, param_count), param_values, + param_count, out_type); }); } @@ -399,21 +403,22 @@ DUCKDB_V2_ERROR duckdb_v2_logical_type_get_id(duckdb_v2_logical_type_handle type return WithErrorHandler(err, [&]() { *out_id = static_cast(Convert(type)->id()); }); } -DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, duckdb_v2_identifier_t *out_name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(type); DUCKDB_CHECK_ARG(out_name); + DUCKDB_CHECK_ARG(out_name_length); return WithErrorHandler(err, [&]() { auto lt = Convert(type); auto &info = lt->GetTypeInfo(); if (!info.alias.empty()) { - *out_name = Convert(info.alias); + SetStringOut(out_name, out_name_length, info.alias); return; } // Canonical fixed name of the id: static storage, so the borrowed // view outlives even the handle. const char *canonical = duckdb::EnumUtil::ToChars(lt->id()); - *out_name = duckdb_v2_str {canonical, std::strlen(canonical)}; + SetStringOut(out_name, out_name_length, std::string_view(canonical)); }); } @@ -441,23 +446,25 @@ DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_logical_type_ha }); } -DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, - duckdb_v2_identifier_t *out_name, duckdb_v2_value_handle *out_value, +DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, const char **out_name, + idx_t *out_name_length, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(type); DUCKDB_CHECK_ARG(out_name); + DUCKDB_CHECK_ARG(out_name_length); DUCKDB_CHECK_ARG(out_value); return WithErrorHandler(err, [&]() { - *out_name = duckdb_v2_identifier_t {nullptr, 0}; + *out_name = nullptr; + *out_name_length = 0; *out_value = nullptr; auto lt_ref = Convert(type); auto < = *lt_ref; if (index >= TypeParamCount(lt)) { throw duckdb::InvalidInputException("parameter index out of range in duckdb_v2_logical_type_get_param"); } - duckdb_v2_identifier_t name {nullptr, 0}; + std::string_view name; auto *value = new duckdb::Value(TypeParamValue(lt, index, name)); - *out_name = name; + SetStringOut(out_name, out_name_length, name); *out_value = Convert(value); }); } @@ -466,10 +473,9 @@ namespace { // The alias keeps the base type's internal representation; only the name and // its catalog identity change. -duckdb::LogicalType AliasOf(duckdb_v2_logical_type_handle base_type, const duckdb_v2_identifier_t *alias_name, +duckdb::LogicalType AliasOf(duckdb_v2_logical_type_handle base_type, std::string_view name, duckdb_v2_logical_type_handle *out_type) { *out_type = nullptr; - auto name = ConvertIdentifierName(alias_name); if (name.empty()) { throw duckdb::InvalidInputException("alias name cannot be empty"); } @@ -480,14 +486,16 @@ duckdb::LogicalType AliasOf(duckdb_v2_logical_type_handle base_type, const duckd DUCKDB_V2_ERROR duckdb_v2_factory_create_type_with_alias(duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle base_type, - const duckdb_v2_identifier_t *alias_name, + const char *alias_name, idx_t alias_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(base_type); - DUCKDB_CHECK_ARG(alias_name); + DUCKDB_CHECK_STR_ARG(alias_name, alias_name_length); DUCKDB_CHECK_ARG(out_type); - return WithErrorHandler(err, [&]() { *out_type = Convert(AliasOf(base_type, alias_name, out_type)); }); + return WithErrorHandler(err, [&]() { + *out_type = Convert(AliasOf(base_type, ConvertIdentifierName(alias_name, alias_name_length), out_type)); + }); } DUCKDB_V2_ERROR duckdb_v2_factory_create_common_type(duckdb_v2_factory_handle factory, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_option.cpp b/src/duckdb/src/main/capi/v2/capi_v2_option.cpp index cf1215c79..0c2620a7a 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_option.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_option.cpp @@ -14,11 +14,12 @@ DUCKDB_V2_ERROR duckdb_v2_option_destroy(duckdb_v2_option_handle *option) { }); } -DUCKDB_V2_ERROR duckdb_v2_option_get_name(duckdb_v2_option_handle option, duckdb_v2_identifier_t *out_name, +DUCKDB_V2_ERROR duckdb_v2_option_get_name(duckdb_v2_option_handle option, const char **out_name, idx_t *out_name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(option); DUCKDB_CHECK_ARG(out_name); - return WithErrorHandler(err, [&]() { *out_name = Convert(Convert(option)->name); }); + DUCKDB_CHECK_ARG(out_name_length); + return WithErrorHandler(err, [&]() { SetStringOut(out_name, out_name_length, Convert(option)->name); }); } DUCKDB_V2_ERROR duckdb_v2_option_get_default_value(duckdb_v2_option_handle option, duckdb_v2_value_handle *out_value, @@ -29,11 +30,13 @@ DUCKDB_V2_ERROR duckdb_v2_option_get_default_value(duckdb_v2_option_handle optio return WithErrorHandler(err, [&]() { *out_value = Convert(new duckdb::Value(Convert(option)->default_value)); }); } -DUCKDB_V2_ERROR duckdb_v2_option_get_description(duckdb_v2_option_handle option, duckdb_v2_str *out_description, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_option_get_description(duckdb_v2_option_handle option, const char **out_description, + idx_t *out_description_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(option); DUCKDB_CHECK_ARG(out_description); - return WithErrorHandler(err, [&]() { *out_description = Convert(Convert(option)->description); }); + DUCKDB_CHECK_ARG(out_description_length); + return WithErrorHandler( + err, [&]() { SetStringOut(out_description, out_description_length, Convert(option)->description); }); } DUCKDB_V2_ERROR duckdb_v2_option_supports_scope(duckdb_v2_option_handle option, DUCKDB_V2_SETTING_SCOPE scope, @@ -70,17 +73,19 @@ DUCKDB_V2_ERROR duckdb_v2_option_get_alias_count(duckdb_v2_option_handle option, return WithErrorHandler(err, [&]() { *out_count = static_cast(Convert(option)->aliases.size()); }); } -DUCKDB_V2_ERROR duckdb_v2_option_get_alias(duckdb_v2_option_handle option, idx_t index, - duckdb_v2_identifier_t *out_alias, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_option_get_alias(duckdb_v2_option_handle option, idx_t index, const char **out_alias, + idx_t *out_alias_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(option); DUCKDB_CHECK_ARG(out_alias); + DUCKDB_CHECK_ARG(out_alias_length); return WithErrorHandler(err, [&]() { const auto &wrapper = *Convert(option); if (index >= wrapper.aliases.size()) { - *out_alias = duckdb_v2_str {nullptr, 0}; + *out_alias = nullptr; + *out_alias_length = 0; throw duckdb::InvalidInputException("alias index out of range in duckdb_v2_option_get_alias"); } - *out_alias = Convert(wrapper.aliases[index]); + SetStringOut(out_alias, out_alias_length, wrapper.aliases[index]); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp b/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp index d36b021ce..9cd4e5721 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp @@ -71,7 +71,7 @@ DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_connection_handle } DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute(duckdb_v2_prepared_statement_handle prepared, - const duckdb_v2_identifier_t *parameter_names, + const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err) { @@ -87,18 +87,17 @@ DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute(duckdb_v2_prepared_statemen // supplies one and positionally ("1".."N") otherwise. Per execution: nothing is // retained on the handle between calls. duckdb::identifier_map_t values; - BuildParameterMap(parameter_names, parameter_values, parameter_count, __func__, values); + BuildParameterMap(string_view_array(parameter_names, parameter_names_lengths, parameter_count), + parameter_values, parameter_count, __func__, values); *out_result = Convert(ExecutePreparedStatementV2(wrapper->context, *wrapper->prepared, values, nullptr).release()); }); } -DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow(duckdb_v2_prepared_statement_handle prepared, - const duckdb_v2_identifier_t *parameter_names, - const duckdb_v2_value_handle *parameter_values, - idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow( + duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, + const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, + duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_result); *out_result = nullptr; DUCKDB_CHECK_ARG(prepared); @@ -108,7 +107,8 @@ DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow(duckdb_v2_prepared_st return WithErrorHandler(err, [&]() { auto *wrapper = Convert(prepared); duckdb::identifier_map_t values; - BuildParameterMap(parameter_names, parameter_values, parameter_count, __func__, values); + BuildParameterMap(string_view_array(parameter_names, parameter_names_lengths, parameter_count), + parameter_values, parameter_count, __func__, values); *out_result = ConvertArrowResult( ExecutePreparedStatementV2(wrapper->context, *wrapper->prepared, values, ArrowResultFormat(batch_size)) .release()); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp b/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp index 03392a84d..571fe9e74 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp @@ -26,15 +26,15 @@ static void CheckQNameParts(const QualifiedName &name, const char *function_name using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_qname_parse(const duckdb_v2_str *text, duckdb_v2_qname_handle *out_name, +DUCKDB_V2_ERROR duckdb_v2_qname_parse(const char *text, idx_t text_length, duckdb_v2_qname_handle *out_name, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(text); + DUCKDB_CHECK_STR_ARG(text, text_length); DUCKDB_CHECK_ARG(out_name); *out_name = nullptr; return WithErrorHandler(err, [&]() { duckdb::QualifiedName parsed; duckdb::string error; - if (!duckdb::QualifiedName::TryParse(duckdb::string(ConvertIdentifierName(text)), parsed, error)) { + if (!duckdb::QualifiedName::TryParse(duckdb::string(ConvertIdentifierName(text, text_length)), parsed, error)) { throw duckdb::InvalidInputException("%s in duckdb_v2_qname_parse.", error); } CheckQNameParts(parsed, "duckdb_v2_qname_parse"); @@ -42,7 +42,7 @@ DUCKDB_V2_ERROR duckdb_v2_qname_parse(const duckdb_v2_str *text, duckdb_v2_qname }); } -DUCKDB_V2_ERROR duckdb_v2_qname_create(const duckdb_v2_identifier_t *parts, idx_t part_count, +DUCKDB_V2_ERROR duckdb_v2_qname_create(const char **parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *out_name, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_name); *out_name = nullptr; @@ -54,14 +54,14 @@ DUCKDB_V2_ERROR duckdb_v2_qname_create(const duckdb_v2_identifier_t *parts, idx_ if (!parts) { throw duckdb::InvalidInputException("Parts cannot be null when part_count is non-zero."); } + string_view_array part_views(parts, parts_lengths, part_count); // The last part is the object name; everything before it is the qualification. duckdb::vector qualification; for (idx_t i = 0; i + 1 < part_count; i++) { - qualification.push_back(duckdb::Identifier(ConvertIdentifierName(parts[i]))); + qualification.push_back(duckdb::Identifier(part_views[i])); } - auto name = duckdb::QualifiedName(std::move(qualification), - duckdb::Identifier(ConvertIdentifierName(parts[part_count - 1]))); + auto name = duckdb::QualifiedName(std::move(qualification), duckdb::Identifier(part_views[part_count - 1])); CheckQNameParts(name, "duckdb_v2_qname_create"); *out_name = Convert(new duckdb::QualifiedName(std::move(name))); }); @@ -74,11 +74,13 @@ DUCKDB_V2_ERROR duckdb_v2_qname_get_part_count(duckdb_v2_qname_handle name, idx_ return WithErrorHandler(err, [&]() { *out_count = Convert(name)->Path().size(); }); } -DUCKDB_V2_ERROR duckdb_v2_qname_get_part(duckdb_v2_qname_handle name, idx_t index, duckdb_v2_identifier_t *out_part, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_qname_get_part(duckdb_v2_qname_handle name, idx_t index, const char **out_part, + idx_t *out_part_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(name); DUCKDB_CHECK_ARG(out_part); - *out_part = duckdb_v2_identifier_t {nullptr, 0}; + DUCKDB_CHECK_ARG(out_part_length); + *out_part = nullptr; + *out_part_length = 0; return WithErrorHandler(err, [&]() { auto &path = Convert(name)->Path(); if (index >= path.size()) { @@ -88,7 +90,7 @@ DUCKDB_V2_ERROR duckdb_v2_qname_get_part(duckdb_v2_qname_handle name, idx_t inde static_cast(index), static_cast(path.size()))); } - *out_part = Convert(path[index]); + SetStringOut(out_part, out_part_length, path[index]); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp b/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp index f4a89a89a..d8a529a2d 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp @@ -133,12 +133,14 @@ DUCKDB_V2_ERROR duckdb_v2_query_metrics_get_root(duckdb_v2_query_metrics_handle return WithErrorHandler(err, [&]() { *node = Convert(&Convert(metrics)->root); }); } -DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_name(duckdb_v2_query_metrics_node_handle node, duckdb_v2_str *name, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_name(duckdb_v2_query_metrics_node_handle node, const char **name, + idx_t *name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(node); DUCKDB_CHECK_ARG(name); - *name = duckdb_v2_str {nullptr, 0}; - return WithErrorHandler(err, [&]() { *name = Convert(Convert(node)->name); }); + DUCKDB_CHECK_ARG(name_length); + *name = nullptr; + *name_length = 0; + return WithErrorHandler(err, [&]() { SetStringOut(name, name_length, Convert(node)->name); }); } DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_child_count(duckdb_v2_query_metrics_node_handle node, idx_t *count, @@ -166,12 +168,15 @@ DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_count(duckdb_v2_query_me } DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_name(duckdb_v2_query_metrics_node_handle node, idx_t index, - duckdb_v2_str *name, duckdb_v2_error_info_handle *err) { + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(node); DUCKDB_CHECK_ARG(name); - *name = duckdb_v2_str {nullptr, 0}; - return WithErrorHandler(err, - [&]() { *name = Convert(GetCheckedQueryMetric(*Convert(node), index, __func__).first); }); + DUCKDB_CHECK_ARG(name_length); + *name = nullptr; + *name_length = 0; + return WithErrorHandler( + err, [&]() { SetStringOut(name, name_length, GetCheckedQueryMetric(*Convert(node), index, __func__).first); }); } DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_value(duckdb_v2_query_metrics_node_handle node, idx_t index, @@ -186,17 +191,17 @@ DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric_value(duckdb_v2_query_me }); } -DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric(duckdb_v2_query_metrics_node_handle node, - const duckdb_v2_str *name, duckdb_v2_value_handle *value, - bool *present, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_query_metrics_node_get_metric(duckdb_v2_query_metrics_node_handle node, const char *name, + idx_t name_length, duckdb_v2_value_handle *value, bool *present, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(node); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(value); DUCKDB_CHECK_ARG(present); *value = nullptr; *present = false; return WithErrorHandler(err, [&]() { - std::string_view key(name->ptr, name->len); + auto key = Convert(name, name_length); for (auto &metric : Convert(node)->metrics) { if (metric.first == key) { *value = Convert(new duckdb::Value(metric.second)); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp b/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp index 7b37ba0d7..3ee93d148 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp @@ -241,22 +241,23 @@ DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_argument(duckdb_v2_replacement_sc } DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckdb_v2_replacement_scan_info_handle info, - const duckdb_v2_identifier_t *name, + const char *name, idx_t name_length, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(value); return WithErrorHandler(err, [&]() { auto &args = *Convert(info); args.RequireFunctionClaim("duckdb_v2_replacement_scan_add_named_argument"); - args.out_named_arguments.emplace_back(duckdb::Identifier(ConvertIdentifierName(name)), *Convert(value)); + args.out_named_arguments.emplace_back(duckdb::Identifier(ConvertIdentifierName(name, name_length)), + *Convert(value)); }); } DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection(duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const duckdb_v2_identifier_t *column_names, + const char **column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(collection); @@ -275,8 +276,9 @@ DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection(duckdb_v2_replacement_ cdc.ColumnCount()); } duckdb::vector names; + string_view_array name_views(column_names, column_names_lengths, column_count); for (idx_t i = 0; i < column_count; i++) { - auto name = duckdb::Identifier(ConvertIdentifierName(column_names[i])); + auto name = duckdb::Identifier(name_views[i]); if (name.empty()) { throw duckdb::InvalidInputException("Column names cannot be empty."); } @@ -289,17 +291,17 @@ DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection(duckdb_v2_replacement_ }); } -DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_subquery(duckdb_v2_replacement_scan_info_handle info, - const duckdb_v2_str *sql, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_subquery(duckdb_v2_replacement_scan_info_handle info, const char *sql, + idx_t sql_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(sql); + DUCKDB_CHECK_STR_ARG(sql, sql_length); return WithErrorHandler(err, [&]() { auto &args = *Convert(info); // Parsed here rather than when the claim is materialized, so a bad query fails this call instead of // surfacing later as an opaque binding error. duckdb::Parser parser(*args.in_context); - parser.ParseQuery(duckdb::string(Convert(sql))); + parser.ParseQuery(duckdb::string(Convert(sql, sql_length))); if (parser.statements.size() != 1) { throw duckdb::InvalidInputException("The replacement subquery must be exactly one SELECT statement."); } @@ -313,13 +315,12 @@ DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_subquery(duckdb_v2_replacement_sc }); } -DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_alias(duckdb_v2_replacement_scan_info_handle info, - const duckdb_v2_identifier_t *alias, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_alias(duckdb_v2_replacement_scan_info_handle info, const char *alias, + idx_t alias_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(alias); - return WithErrorHandler(err, - [&]() { Convert(info)->out_alias = duckdb::Identifier(ConvertIdentifierName(alias)); }); + DUCKDB_CHECK_STR_ARG(alias, alias_length); + return WithErrorHandler( + err, [&]() { Convert(info)->out_alias = duckdb::Identifier(ConvertIdentifierName(alias, alias_length)); }); } DUCKDB_V2_ERROR duckdb_v2_connection_register_replacement_scan(duckdb_v2_connection_handle conn, @@ -331,7 +332,8 @@ DUCKDB_V2_ERROR duckdb_v2_connection_register_replacement_scan(duckdb_v2_connect auto &context = *Convert(conn)->context; auto built = Convert(scan)->Build(*context.db); // Connection-scoped: this touches only the client's own state, never the shared database config. - context.config.replacement_scans.push_back(duckdb::make_shared_ptr(std::move(built))); + duckdb::ClientConfig::GetConfig(context).replacement_scans.push_back( + duckdb::make_shared_ptr(std::move(built))); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_result.cpp b/src/duckdb/src/main/capi/v2/capi_v2_result.cpp index c7b7391cc..ab9a72567 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_result.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_result.cpp @@ -395,7 +395,7 @@ auto ExecutePreparedStatementV2(const shared_ptr &context, Prepar } auto ExecuteStatementV2(const shared_ptr &context, const SQLStatement &statement, - const duckdb_v2_identifier_t *parameter_names, const duckdb_v2_value_handle *parameter_values, + const string_view_array ¶meter_names, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, const char *function_name, shared_ptr format) -> unique_ptr { auto wrapper = make_uniq(); @@ -431,7 +431,7 @@ auto ExecuteStatementV2(const shared_ptr &context, const SQLState using namespace duckdb::capiv2; DUCKDB_V2_ERROR duckdb_v2_statement_execute(duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *parameter_names, + const char **parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err) { // The refusals here never reach the engine and leave the statement intact @@ -444,9 +444,11 @@ DUCKDB_V2_ERROR duckdb_v2_statement_execute(duckdb_v2_connection_handle conn, du return NullArgumentError(err, __func__, "parameter_values"); } return WithErrorHandler(err, [&]() { - *out_result = Convert(ExecuteStatementV2(Convert(conn)->context, *Convert(statement), parameter_names, - parameter_values, parameter_count, __func__, nullptr) - .release()); + *out_result = + Convert(ExecuteStatementV2(Convert(conn)->context, *Convert(statement), + string_view_array(parameter_names, parameter_names_lengths, parameter_count), + parameter_values, parameter_count, __func__, nullptr) + .release()); }); } @@ -458,16 +460,16 @@ DUCKDB_V2_ERROR duckdb_v2_result_drain(duckdb_v2_result_handle result, idx_t *ou } DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx_t max_rows, idx_t max_width, - idx_t max_col_width, const duckdb_v2_str *null_value, idx_t render_mode, - idx_t limit, duckdb_v2_text_sink_fn sink, void *user_data, - duckdb_v2_error_info_handle *err) { + idx_t max_col_width, const char *null_value, idx_t null_value_length, + idx_t render_mode, idx_t limit, duckdb_v2_text_sink_fn sink, + void *user_data, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(result); DUCKDB_CHECK_ARG(*result); DUCKDB_CHECK_ARG(sink); // Validate the view arguments before consuming the result, so an // argument rejection leaves the caller's result intact (as the null-arg // rejections above do). - DUCKDB_CHECK_ARG(null_value); + DUCKDB_CHECK_STR_ARG(null_value, null_value_length); return WithErrorHandler(err, [&]() { if (render_mode > 1) { throw duckdb::InvalidInputException("render_mode must be 0 (rows) or 1 (columns)"); @@ -498,8 +500,8 @@ DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx if (max_col_width != 0) { config.max_col_width = max_col_width; } - if (null_value->len) { - config.null_value = std::string(null_value->ptr, null_value->len); + if (null_value_length) { + config.null_value = std::string(Convert(null_value, null_value_length)); } config.render_mode = render_mode == 1 ? duckdb::RenderMode::COLUMNS : duckdb::RenderMode::ROWS; // The caller's query-side LIMIT: when the materialized result fills it, the @@ -516,7 +518,7 @@ DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx } auto text = renderer.ToString(render_context, names, data); - InvokeTextSink(sink, Convert(text), user_data); + InvokeTextSink(sink, text, user_data); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_schema.cpp b/src/duckdb/src/main/capi/v2/capi_v2_schema.cpp index c7d79d554..28c9ea960 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_schema.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_schema.cpp @@ -9,14 +9,16 @@ DUCKDB_V2_ERROR duckdb_v2_schema_get_count(duckdb_v2_schema_handle schema, idx_t return WithErrorHandler(err, [&]() { *out_count = Convert(schema)->fields.size(); }); } -DUCKDB_V2_ERROR duckdb_v2_schema_get_field(duckdb_v2_schema_handle schema, idx_t index, - duckdb_v2_identifier_t *out_name, duckdb_v2_logical_type_handle *out_type, +DUCKDB_V2_ERROR duckdb_v2_schema_get_field(duckdb_v2_schema_handle schema, idx_t index, const char **out_name, + idx_t *out_name_length, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(schema); DUCKDB_CHECK_ARG(out_name); + DUCKDB_CHECK_ARG(out_name_length); DUCKDB_CHECK_ARG(out_type); return WithErrorHandler(err, [&]() { - *out_name = duckdb_v2_identifier_t {nullptr, 0}; + *out_name = nullptr; + *out_name_length = 0; *out_type = nullptr; auto &wrapper = *Convert(schema); if (index >= wrapper.fields.size()) { @@ -25,7 +27,7 @@ DUCKDB_V2_ERROR duckdb_v2_schema_get_field(duckdb_v2_schema_handle schema, idx_t auto &field = wrapper.fields[index]; // Both borrowed, valid until the schema is destroyed; out_type aliases the // wrapper-owned LogicalType and must not be destroyed by the caller. - *out_name = Convert(field.name); + SetStringOut(out_name, out_name_length, field.name); *out_type = ConvertBorrowed(field.type); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp b/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp index cb613f775..eafdc30e0 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp @@ -40,11 +40,11 @@ struct StatementIteratorWrapperV2 { //! Binding-index order, as statement_bind's parameter schema; positional indices may be gapped ($1, $3). auto ParameterNamesInBindingOrder(const duckdb::SQLStatement &statement) - -> vector> { - vector> names; + -> vector>> { + vector>> names; names.reserve(statement.named_param_map.size()); for (auto &entry : statement.named_param_map) { - names.emplace_back(entry.second, Convert(entry.first)); + names.emplace_back(entry.second, entry.first); } std::sort(names.begin(), names.end(), [](const auto &a, const auto &b) { return a.first < b.first; }); return names; @@ -87,13 +87,15 @@ auto Convert(StatementIteratorWrapperV2 *ptr) -> duckdb_v2_statement_iterator_ha using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, bool apply_invalidation_policy, - duckdb_v2_statement_iterator_handle *out_iterator, +DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, + bool apply_invalidation_policy, duckdb_v2_statement_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(conn); - DUCKDB_CHECK_ARG(sql); DUCKDB_CHECK_ARG(out_iterator); *out_iterator = nullptr; + if (!sql && sql_length > 0) { + return NullArgumentError(err, __func__, "sql"); + } return WithErrorHandler(err, [&]() { auto *connection = Convert(conn); // Set up a lazy iterator over the connection's parser options and @@ -105,8 +107,8 @@ DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char // statement_execute, so a statement group is never split across the API // boundary. A parse error is not raised here; it surfaces from the next() // that reaches the failing statement. - auto wrapper = duckdb::make_uniq(connection->context, std::string(sql), - apply_invalidation_policy); + auto wrapper = duckdb::make_uniq( + connection->context, sql_length ? std::string(sql, sql_length) : std::string(), apply_invalidation_policy); *out_iterator = Convert(wrapper.release()); }); } @@ -162,16 +164,18 @@ DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_type(duckdb_v2_sql_statement_handle return WithErrorHandler(err, [&]() { *out_type = Convert(Convert(statement)->type); }); } -DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, duckdb_v2_str *out_text, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, const char **out_text, + idx_t *out_text_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(statement); DUCKDB_CHECK_ARG(out_text); - *out_text = duckdb_v2_str {nullptr, 0}; + DUCKDB_CHECK_ARG(out_text_length); + *out_text = nullptr; + *out_text_length = 0; return WithErrorHandler(err, [&]() { // The parse paths already store the statement's own slice in `query`; `stmt_location` covers all of it. auto &query = Convert(statement)->query; if (!query.empty()) { - *out_text = Convert(query); + SetStringOut(out_text, out_text_length, query); } }); } @@ -185,11 +189,13 @@ DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_count(duckdb_v2_sql_statem } DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_statement_handle statement, idx_t index, - duckdb_v2_identifier_t *out_name, + const char **out_name, idx_t *out_name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(statement); DUCKDB_CHECK_ARG(out_name); - *out_name = duckdb_v2_identifier_t {nullptr, 0}; + DUCKDB_CHECK_ARG(out_name_length); + *out_name = nullptr; + *out_name_length = 0; return WithErrorHandler(err, [&]() { auto names = ParameterNamesInBindingOrder(*Convert(statement)); if (index >= names.size()) { @@ -200,22 +206,22 @@ DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_stateme static_cast(index), static_cast(names.size()))); } - *out_name = names[index].second; + SetStringOut(out_name, out_name_length, names[index].second.get()); }); } -DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, - const duckdb_v2_identifier_t *name, +DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, const char *name, + idx_t name_length, duckdb_v2_column_data_collection_handle collection, - const duckdb_v2_identifier_t *column_names, idx_t column_count, - duckdb_v2_error_info_handle *err) { + const char **column_names, const idx_t *column_names_lengths, + idx_t column_count, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(statement); - DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_STR_ARG(name, name_length); DUCKDB_CHECK_ARG(collection); return WithErrorHandler(err, [&]() { auto &stmt = *Convert(statement); auto &cdc = *Convert(collection); - duckdb::Identifier alias(ConvertIdentifierName(name)); + duckdb::Identifier alias(ConvertIdentifierName(name, name_length)); if (alias.empty()) { throw duckdb::InvalidInputException("The name to bind a collection under cannot be empty."); } @@ -228,8 +234,9 @@ DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handl static_cast(column_count), static_cast(cdc.ColumnCount())); } duckdb::vector expected_names; + string_view_array name_views(column_names, column_names_lengths, column_count); for (idx_t i = 0; i < column_count; i++) { - expected_names.emplace_back(ConvertIdentifierName(column_names[i])); + expected_names.emplace_back(name_views[i]); if (expected_names.back().empty()) { throw duckdb::InvalidInputException("Column name %llu of the collection cannot be empty.", static_cast(i)); 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 9049b7b96..f3778ab33 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_tokenizer.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_tokenizer.cpp @@ -69,16 +69,16 @@ auto Convert(TokenIteratorWrapperV2 *ptr) -> duckdb_v2_token_iterator_handle { using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_tokenize_sql(duckdb_v2_connection_handle conn, const duckdb_v2_str *sql, +DUCKDB_V2_ERROR duckdb_v2_tokenize_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, duckdb_v2_token_iterator_handle *out_iterator, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_iterator); *out_iterator = nullptr; DUCKDB_CHECK_ARG(conn); - DUCKDB_CHECK_ARG(sql); + DUCKDB_CHECK_STR_ARG(sql, sql_length); return WithErrorHandler(err, [&]() { auto *connection = Convert(conn); - duckdb::string input(Convert(sql)); + duckdb::string input(Convert(sql, sql_length)); duckdb::vector raw_tokens; CleanExitTokenizerBehavior behavior(input, raw_tokens); auto grammar = duckdb::CompiledGrammar::Get(*connection->context); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_utf8.cpp b/src/duckdb/src/main/capi/v2/capi_v2_utf8.cpp index 49bacb166..7190eb623 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_utf8.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_utf8.cpp @@ -4,21 +4,41 @@ namespace duckdb::capiv2 { -auto ConvertIdentifierName(duckdb_v2_identifier_t name) -> std::string_view { - auto bytes = Convert(name); +auto ConvertIdentifierName(const char *name, idx_t name_length) -> std::string_view { + auto bytes = Convert(name, name_length); if (!Utf8Proc::IsValid(bytes.data(), bytes.size())) { throw InvalidInputException("Identifier is not valid UTF-8"); } return bytes; } +std::string_view string_view_array::operator[](idx_t i) const { + D_ASSERT(i < count); + if (!ptrs) { + return std::string_view(); + } + if (!lengths) { + throw InvalidInputException("string array lengths cannot be null when the array is not null"); + } + if (!ptrs[i]) { + if (lengths[i] > 0) { + throw InvalidInputException("string array entry %llu is null with a non-zero length", i); + } + return std::string_view(); + } + if (!Utf8Proc::IsValid(ptrs[i], lengths[i])) { + throw InvalidInputException("string array entry %llu is not valid UTF-8", i); + } + return std::string_view(ptrs[i], lengths[i]); +} + } // namespace duckdb::capiv2 using namespace duckdb::capiv2; -DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const duckdb_v2_str *text, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const char *text, idx_t text_length, duckdb_v2_error_info_handle *err) { return WithErrorHandler(err, [&]() { - auto bytes = Convert(text); + auto bytes = Convert(text, text_length); if (!duckdb::Utf8Proc::IsValid(bytes.data(), bytes.size())) { throw duckdb::InvalidInputException("Input is not valid UTF-8"); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp index 1f746dc96..fc059b7bd 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -128,16 +128,14 @@ Value BuildDecimal(const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t s // BIT carries a mandatory padding-header byte, BIGNUM a header plus at least // one magnitude byte; anything shorter is not addressable storage. -Value BuildBit(const duckdb_v2_str *in_value) { - auto bytes = Convert(in_value); +Value BuildBit(std::string_view bytes) { if (bytes.empty()) { throw InvalidInputException("the BIT wire form carries a mandatory padding header byte"); } return Value::BIT(const_data_ptr_cast(bytes.data()), bytes.size()); } -Value BuildBignum(const duckdb_v2_str *in_value) { - auto bytes = Convert(in_value); +Value BuildBignum(std::string_view bytes) { if (bytes.size() <= Bignum::BIGNUM_HEADER_SIZE) { throw InvalidInputException("the BIGNUM storage form requires more than " + std::to_string(Bignum::BIGNUM_HEADER_SIZE) + " bytes"); @@ -276,19 +274,21 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_double(duckdb_v2_value_handle value, double return WithErrorHandler(err, [&]() { *out = ReadAs(value, duckdb::LogicalTypeId::DOUBLE); }); } -DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, duckdb_v2_str *out, +DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out); + DUCKDB_CHECK_ARG(out_length); return WithErrorHandler(err, [&]() { RequireTypedValue(value, duckdb::LogicalTypeId::VARCHAR); - *out = Convert(duckdb::StringValue::Get(*Convert(value))); + SetStringOut(out, out_length, duckdb::StringValue::Get(*Convert(value))); }); } -DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, duckdb_v2_str *out, +DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, const char **out, idx_t *out_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(value); DUCKDB_CHECK_ARG(out); + DUCKDB_CHECK_ARG(out_length); return WithErrorHandler(err, [&]() { auto &v = *Convert(value); // The byte-string reader: BLOB plus the kinds whose payload is opaque @@ -302,7 +302,7 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, duckdb_v2 if (v.IsNull()) { throw duckdb::InvalidInputException("duckdb_v2_value_get_blob: value is NULL"); } - *out = Convert(duckdb::StringValue::Get(v)); + SetStringOut(out, out_length, duckdb::StringValue::Get(v)); }); } @@ -341,8 +341,8 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb RequireTypedValue(value, duckdb::LogicalTypeId::DECIMAL); auto &v = *Convert(value); auto &type = v.type(); - *out_width = duckdb::DecimalType::GetWidth(type); - *out_scale = duckdb::DecimalType::GetScale(type); + *out_width = duckdb::NumericCast(duckdb::DecimalType::GetWidth(type)); + *out_scale = duckdb::NumericCast(duckdb::DecimalType::GetScale(type)); // The storage tier follows from the width; widen it to the one form the // caller always gets back. switch (type.InternalType()) { @@ -553,20 +553,23 @@ DUCKDB_V2_ERROR duckdb_v2_value_create_double(duckdb_v2_factory_handle factory, return WithErrorHandler(err, [&]() { *out_value = Emit(duckdb::Value::DOUBLE(in_value)); }); } -DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_value); *out_value = nullptr; - return WithErrorHandler(err, [&]() { *out_value = Emit(duckdb::Value(Convert(in_value))); }); + return WithErrorHandler(err, [&]() { *out_value = Emit(duckdb::Value(Convert(in_value, in_value_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_value); *out_value = nullptr; - return WithErrorHandler(err, [&]() { *out_value = Emit(duckdb::Value::BLOB_RAW(std::string(Convert(in_value)))); }); + return WithErrorHandler( + err, [&]() { *out_value = Emit(duckdb::Value::BLOB_RAW(std::string(Convert(in_value, in_value_length)))); }); } DUCKDB_V2_ERROR duckdb_v2_value_create_null(duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle type, @@ -713,20 +716,22 @@ DUCKDB_V2_ERROR duckdb_v2_value_create_uuid(duckdb_v2_factory_handle factory, co return WithErrorHandler(err, [&]() { *out_value = Emit(duckdb::Value::UUID(Convert(in_value))); }); } -DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_value); *out_value = nullptr; - return WithErrorHandler(err, [&]() { *out_value = Emit(BuildBit(in_value)); }); + return WithErrorHandler(err, [&]() { *out_value = Emit(BuildBit(Convert(in_value, in_value_length))); }); } -DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, const duckdb_v2_str *in_value, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_value); *out_value = nullptr; - return WithErrorHandler(err, [&]() { *out_value = Emit(BuildBignum(in_value)); }); + return WithErrorHandler(err, [&]() { *out_value = Emit(BuildBignum(Convert(in_value, in_value_length))); }); } // --------------------------------------------------------------------------- @@ -791,7 +796,7 @@ duckdb::Value BuildArray(CV2Factory &factory, duckdb_v2_logical_type_handle chil return duckdb::Value::ARRAY(type, std::move(values)); } -duckdb::Value BuildStruct(const duckdb_v2_identifier_t *names, const duckdb_v2_value_handle *children, +duckdb::Value BuildStruct(const char **names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count) { if (field_count > 0 && !names) { throw duckdb::InvalidInputException("'names' cannot be null when field_count > 0"); @@ -801,11 +806,9 @@ duckdb::Value BuildStruct(const duckdb_v2_identifier_t *names, const duckdb_v2_v // rather than resolved across the fields. duckdb::child_list_t fields; fields.reserve(field_count); + string_view_array name_views(names, names_lengths, field_count); for (idx_t i = 0; i < field_count; i++) { - if (!names[i].ptr && names[i].len > 0) { - throw duckdb::InvalidInputException("field names cannot be null"); - } - fields.emplace_back(std::string(ConvertIdentifierName(names[i])), std::move(values[i])); + fields.emplace_back(std::string(name_views[i]), std::move(values[i])); } return duckdb::Value::STRUCT(std::move(fields)); } @@ -852,13 +855,15 @@ DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_handle factory, d err, [&]() { *out_value = Emit(BuildArray(*Convert(factory), child_type, children, child_count)); }); } -DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const duckdb_v2_identifier_t *names, - const duckdb_v2_value_handle *children, idx_t field_count, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char **names, + const idx_t *names_lengths, const duckdb_v2_value_handle *children, + idx_t field_count, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_value); *out_value = nullptr; - return WithErrorHandler(err, [&]() { *out_value = Emit(BuildStruct(names, children, field_count)); }); + return WithErrorHandler(err, + [&]() { *out_value = Emit(BuildStruct(names, names_lengths, children, field_count)); }); } DUCKDB_V2_ERROR duckdb_v2_value_create_tuple(duckdb_v2_factory_handle factory, const duckdb_v2_value_handle *children, diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 321839984..57fa6265d 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -139,14 +139,13 @@ struct DebugClientContextState : public ClientContextState { #endif ClientContext::ClientContext(shared_ptr database) - : db(std::move(database)), interrupt_state(ClientInterruptState::NOT_INTERRUPTED), transaction(*this), - connection_id(DConstants::INVALID_INDEX) { - registered_state = make_uniq(); + : db(std::move(database)), interrupt_state(ClientInterruptState::NOT_INTERRUPTED), + context(make_shared_ptr(*db)), transaction(*this), connection_id(DConstants::INVALID_INDEX) { + context->InitializeClient(*this); #ifdef DEBUG - registered_state->GetOrCreate("debug_client_context_state"); + context->GetRegisteredState().GetOrCreate("debug_client_context_state"); #endif - LoggingContext context(LogContextScope::CONNECTION); - logger = db->GetLogManager().CreateLogger(context, true); + ResetLoggerInternal(LoggingContext(LogContextScope::CONNECTION)); client_data = make_uniq(*this); #ifdef __APPLE__ @@ -287,7 +286,7 @@ void ClientContext::VerifyNoOpenResult() { } Logger &ClientContext::GetLogger() const { - return *logger; + return context->GetLogger(); } connection_t ClientContext::GetConnectionId() const { @@ -365,7 +364,7 @@ shared_ptr ClientContext::CreatePreparedStatement(ClientC const QueryParameters ¶meters) { // check if any client context state could request a rebind bool can_request_rebind = false; - for (auto &state : registered_state->States()) { + for (auto &state : context->GetRegisteredState().States()) { if (state->CanRequestRebind()) { can_request_rebind = true; } @@ -379,7 +378,7 @@ shared_ptr ClientContext::CreatePreparedStatement(ClientC } catch (std::exception &ex) { ErrorData error(ex); // check if any registered client context state wants to try a rebind - for (auto &state : registered_state->States()) { + for (auto &state : context->GetRegisteredState().States()) { auto info = state->OnPlanningError(*this, *statement, error); if (info == RebindQueryInfo::ATTEMPT_TO_REBIND) { rebind = true; @@ -391,7 +390,7 @@ shared_ptr ClientContext::CreatePreparedStatement(ClientC } if (result) { D_ASSERT(!rebind); - for (auto &state : registered_state->States()) { + for (auto &state : context->GetRegisteredState().States()) { auto info = state->OnFinalizePrepare(*this, *result, PreparedStatementMode::PREPARE_AND_EXECUTE); if (info == RebindQueryInfo::ATTEMPT_TO_REBIND) { rebind = true; @@ -843,7 +842,9 @@ unique_ptr ClientContext::SubmitStatement(ClientContextLock &lock, active_query->handle = handle.get(); active_query->SetOpenResult(*handle); } - result = SubmitStatementInternal(lock, active_query->TakeNextStatement(), parameters); + auto statement = active_query->TakeNextStatement(); + NotifyStatementBeginInternal(lock); + result = SubmitStatementInternal(lock, std::move(statement), parameters); if (!result && ClientConfig::GetConfig(*this).get_result_collector) { result = RunToResultStatementInternal(lock, *handle); } @@ -1360,17 +1361,18 @@ unique_ptr ClientContext::TableInfo(const Identifier &database const Identifier &table_name) { unique_ptr result; RunFunctionInTransaction([&]() { - // Obtain the table from the catalog. - auto table = Catalog::GetEntry(*this, QualifiedName(database_name, schema_name, table_name), - OnEntryNotFound::RETURN_NULL); - if (!table) { + // A non-table entry must yield nullptr without throwing, as a throw here aborts the caller's transaction. + EntryLookupInfo lookup_info(CatalogType::TABLE_ENTRY, QualifiedName(database_name, schema_name, table_name)); + auto entry = Catalog::GetEntry(*this, lookup_info, OnEntryNotFound::RETURN_NULL); + if (!entry || entry->type != CatalogType::TABLE_ENTRY) { return; } + auto &table = entry->Cast(); // Describe the table at its resolved location, not the input identifiers. - auto &catalog = table->ParentCatalog(); - result = make_uniq(QualifiedName(catalog.GetName(), table->ParentSchema().name, table->name)); + auto &catalog = table.ParentCatalog(); + result = make_uniq(QualifiedName(catalog.GetName(), table.ParentSchema().name, table.name)); result->readonly = catalog.GetAttached().IsReadOnly(); - for (auto &column : table->GetColumns().Logical()) { + for (auto &column : table.GetColumns().Logical()) { result->columns.emplace_back(column.Copy()); } }); @@ -1517,8 +1519,8 @@ SettingLookupResult ClientContext::TryGetCurrentSetting(const Identifier &key, V auto setting_index = db_config.TryGetSettingIndex(key, option); if (setting_index.IsValid()) { // generic setting - try to fetch it - auto lookup_result = - config.user_settings.TryGetSetting(db_config.user_settings, setting_index.GetIndex(), result); + auto lookup_result = ClientConfig::GetConfig(*this).user_settings.TryGetSetting( + db_config.user_settings, setting_index.GetIndex(), result); if (lookup_result) { return lookup_result; } @@ -1534,7 +1536,7 @@ SettingLookupResult ClientContext::TryGetCurrentSetting(const Identifier &key, V SettingLookupResult ClientContext::TryGetCurrentUserSetting(idx_t setting_index, Value &result) const { auto &db_config = DBConfig::GetConfig(*this); - return config.user_settings.TryGetSetting(db_config.user_settings, setting_index, result); + return ClientConfig::GetConfig(*this).user_settings.TryGetSetting(db_config.user_settings, setting_index, result); } ParserOptions ClientContext::GetParserOptions() { diff --git a/src/duckdb/src/main/client_context_execution.cpp b/src/duckdb/src/main/client_context_execution.cpp index f8981906a..c1400b3cb 100644 --- a/src/duckdb/src/main/client_context_execution.cpp +++ b/src/duckdb/src/main/client_context_execution.cpp @@ -68,7 +68,7 @@ void ClientContext::BeginQueryInternal(ClientContextLock &lock, PreprocessedStat query_deadline.SetInvalid(); } // Notify any registered state of query begin - for (auto &state : registered_state->States()) { + for (auto &state : context->GetRegisteredState().States()) { state->QueryBegin(*this); } RefreshLoggerInternal(); @@ -82,24 +82,40 @@ void ClientContext::BeginStatementInternal(ClientContextLock &lock, const string void ClientContext::RefreshLoggerInternal() { // Flush the old logger. - logger->Flush(); + context->GetLogger().Flush(); // Refresh the logger to ensure we are in sync with the global log settings. LoggingContext logging_context(LogContextScope::CONNECTION); logging_context.connection_id = connection_id; logging_context.transaction_id = transaction.ActiveTransaction().global_transaction_id; logging_context.query_id = transaction.GetActiveQuery(); - logger = db->GetLogManager().CreateLogger(logging_context, true); + ResetLoggerInternal(logging_context); DUCKDB_LOG(*this, QueryLogType, active_query->query); } +void ClientContext::ResetLoggerInternal(const LoggingContext &logging_context) { + context->SetLogger(db->GetLogManager().CreateLogger(logging_context, log_config)); +} + ErrorData ClientContext::EndQueryInternal(ClientContextLock &lock, bool success, bool invalidate_transaction, optional_ptr previous_error) { - if (active_query->executor) { - active_query->executor->CancelTasks(); - } - active_query->progress_bar.reset(); D_ASSERT(active_query.get()); + // whether the statement that finished, or an earlier statement of a query that expands, modifies a database + const bool statement_wrote = + active_query->Wrote() || (active_query->prepared && !active_query->prepared->properties.IsReadOnly()); + auto statement_error = EndStatementInternal(lock, previous_error); + // a statement that a state failed to end did not succeed, the failure is the query's error unless it has one + const bool report_statement_error = statement_error.HasError() && !previous_error; + if (statement_error.HasError()) { + success = false; + } + if (report_statement_error) { + // what the statement wrote can only be dropped with the whole transaction + invalidate_transaction = + invalidate_transaction || statement_wrote || ErrorInvalidatesQueryTransaction(statement_error.Type()); + ProcessError(statement_error, active_query->query); + previous_error = &statement_error; + } invalidate_transaction = invalidate_transaction && !active_query->outside_local_transaction; active_query.reset(); query_deadline.SetInvalid(); @@ -136,13 +152,18 @@ ErrorData ClientContext::EndQueryInternal(ClientContextLock &lock, bool success, EndQueryProfiling(error); // Refresh the logger - logger->Flush(); - LoggingContext context(LogContextScope::CONNECTION); - context.connection_id = connection_id; - logger = db->GetLogManager().CreateLogger(context, true); + context->GetLogger().Flush(); + LoggingContext logging_context(LogContextScope::CONNECTION); + logging_context.connection_id = connection_id; + ResetLoggerInternal(logging_context); + + if (!error.HasError() && report_statement_error) { + // the failure to end the statement is reported on the result the way a failed commit is + error = statement_error; + } // Notify any registered state of query end - for (auto const &s : registered_state->States()) { + for (auto const &s : context->GetRegisteredState().States()) { if (error.HasError()) { s->QueryEnd(*this, &error); } else { @@ -155,7 +176,7 @@ ErrorData ClientContext::EndQueryInternal(ClientContextLock &lock, bool success, void ClientContext::EndQueryProfiling(ErrorData &error) { // this also runs while a connection with an open result is destroyed, so it must not throw try { - client_data->profiler->EndQuery(); + QueryProfiler::Get(*context).EndQuery(); } catch (std::exception &ex) { if (!error.HasError()) { error = ErrorData(ex); @@ -192,7 +213,7 @@ void ClientContext::CleanupInternal(ClientContextLock &lock, BaseQueryResult *re } auto error = EndQueryInternal(lock, result ? !result->HasError() : false, invalidate_transaction, passed_error); if (result && !result->HasError()) { - // if an error occurred while committing report it in the result + // if an error occurred while ending the statement or committing report it in the result result->SetError(error); } D_ASSERT(!active_query); @@ -219,6 +240,10 @@ const string &ClientContext::GetCurrentQuery() { return active_query->query; } +bool ClientContext::ActiveQueryIsLastStatement() const { + return !active_query || !active_query->HasNextStatement(); +} + void BindPreparedStatementParameters(ClientContext &context, PreparedStatementData &statement, const QueryParameters ¶meters) { identifier_map_t owned_values; @@ -243,6 +268,7 @@ unique_ptr ClientContext::SubmitPreparedStatementInternal( active_query->executor = make_uniq(*this); auto &executor = *active_query->executor; + auto &config = ClientConfig::GetConfig(*this); if (config.enable_progress_bar) { progress_bar_display_create_func_t display_create_func = nullptr; if (config.print_progress_bar) { @@ -471,7 +497,7 @@ void ClientContext::AbandonActiveQuery(ClientContextLock &lock) { AbortInternal(lock); } interrupt_state = ClientInterruptState::NOT_INTERRUPTED; - client_data->profiler->ResetQueryStart(); + QueryProfiler::Get(*context).ResetQueryStart(); } unique_ptr ClientContext::CompleteInternal(ClientContextLock &lock, unique_ptr result) { @@ -513,10 +539,17 @@ unique_ptr ClientContext::AdvanceStatementInternal(ClientContextLoc if (QueryDeadlinePassed()) { throw InterruptException(QUERY_DEADLINE_ERROR); } - EndStatementInternal(lock); + auto end_error = EndStatementInternal(lock, nullptr); + if (end_error.HasError()) { + // a state that fails to end the statement fails the query, the way the statement failing would + end_error.Throw(); + } + transaction.ResetActiveQuery(); + QueryProfiler::Get(*context).EndQuery(); auto statement = active_query->TakeNextStatement(); BeginStatementInternal(lock, statement->query); RefreshLoggerInternal(); + NotifyStatementBeginInternal(lock); QueryParameters parameters(active_query->format); auto produced = SubmitStatementInternal(lock, std::move(statement), parameters); // A statement that could not start fails the query; the result object of a collector already ended it @@ -556,14 +589,45 @@ unique_ptr ClientContext::RunToResultStatementInternal(ClientContex return nullptr; } -void ClientContext::EndStatementInternal(ClientContextLock &lock) { - active_query->executor->CancelTasks(); - active_query->executor.reset(); +ErrorData ClientContext::EndStatementInternal(ClientContextLock &lock, optional_ptr error) { + if (active_query->executor) { + active_query->executor->CancelTasks(); + active_query->executor.reset(); + } active_query->progress_bar.reset(); // The plan outlives the executor active_query->prepared.reset(); - transaction.ResetActiveQuery(); - client_data->profiler->EndQuery(); + ErrorData end_error; + if (!active_query->statement_began) { + // the states saw no begin of a statement, or its end already, which a failed step between statements leaves + return end_error; + } + active_query->statement_began = false; + // every state sees the end of the statement, also when one of them fails, and the first failure is reported + context->GetRegisteredState().ForEachState([&](ClientContextState &state) { + try { + state.StatementEnd(*this, error); + } catch (std::exception &ex) { + 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()); + } + if (!end_error.HasError()) { + end_error = std::move(state_error); + } + } catch (...) { // LCOV_EXCL_START + if (!end_error.HasError()) { + end_error = ErrorData("Unhandled exception in StatementEnd"); + } + } // LCOV_EXCL_STOP + }); + return end_error; +} + +void ClientContext::NotifyStatementBeginInternal(ClientContextLock &lock) { + active_query->statement_began = true; + context->GetRegisteredState().ForEachState([&](ClientContextState &state) { state.StatementBegin(*this); }); } unique_ptr ClientContext::TakeFinishedResultInternal(ClientContextLock &lock) { diff --git a/src/duckdb/src/main/client_context_file_opener.cpp b/src/duckdb/src/main/client_context_file_opener.cpp index 02dfd64c6..0261a802c 100644 --- a/src/duckdb/src/main/client_context_file_opener.cpp +++ b/src/duckdb/src/main/client_context_file_opener.cpp @@ -4,6 +4,7 @@ #include "duckdb/main/database.hpp" #include "duckdb/common/file_opener.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/logging/log_manager.hpp" #include "duckdb/main/http/http_util.hpp" @@ -14,7 +15,7 @@ SettingLookupResult ClientContextFileOpener::TryGetCurrentSetting(const Identifi } Logger &ClientContextFileOpener::GetLogger() const { - return Logger::Get(context); + return context.GetLogger(); } // LCOV_EXCL_START @@ -24,7 +25,7 @@ SettingLookupResult ClientContextFileOpener::TryGetCurrentSetting(const Identifi } optional_ptr ClientContextFileOpener::TryGetDatabase() { - return context.db.get(); + return &context.GetDatabase(); } HTTPUtil &ClientContextFileOpener::GetHTTPUtil() { @@ -35,23 +36,14 @@ unique_ptr FileOpener::TryGetCatalogTransaction(optional_ptr if (!opener) { return nullptr; } - auto context = opener->TryGetClientContext(); - if (context) { - return make_uniq(CatalogTransaction::GetSystemCatalogTransaction(*context)); - } - - auto db = opener->TryGetDatabase(); - if (db) { - return make_uniq(CatalogTransaction::GetSystemTransaction(*db)); - } - return nullptr; + return make_uniq(CatalogTransaction::GetSystemCatalogTransaction(opener->TryGetContext())); } -optional_ptr FileOpener::TryGetClientContext(optional_ptr opener) { +optional_ptr FileOpener::TryGetContext(optional_ptr opener) { if (!opener) { return nullptr; } - return opener->TryGetClientContext(); + return &opener->TryGetContext(); } optional_ptr FileOpener::TryGetDatabase(optional_ptr opener) { diff --git a/src/duckdb/src/main/client_data.cpp b/src/duckdb/src/main/client_data.cpp index d7d7c07d9..6b3d3c14c 100644 --- a/src/duckdb/src/main/client_data.cpp +++ b/src/duckdb/src/main/client_data.cpp @@ -13,235 +13,16 @@ #include "duckdb/main/database.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/main/query_profiler.hpp" -#include "duckdb/storage/buffer_manager.hpp" -#include "duckdb/storage/buffer/block_handle.hpp" namespace duckdb { -class ClientFileSystem : public OpenerFileSystem { -public: - explicit ClientFileSystem(ClientContext &context_p) : context(context_p) { - } - - FileSystem &GetFileSystem() const override { - auto &config = DBConfig::GetConfig(context); - return *config.file_system; - } - - optional_ptr GetOpener() const override { - return ClientData::Get(context).file_opener.get(); - } - -private: - ClientContext &context; -}; - -//! ClientBufferManager wraps the buffer manager to optionally forward the client context. -class ClientBufferManager : public BufferManager { -public: - explicit ClientBufferManager(ClientContext &context_p, BufferManager &buffer_manager_p) - : context(context_p), buffer_manager(buffer_manager_p) { - } - -public: - shared_ptr AllocateTemporaryMemory(MemoryTag tag, idx_t block_size, bool can_destroy = true) override { - auto result = buffer_manager.AllocateTemporaryMemory(tag, block_size, can_destroy); - // Track allocation based on actual allocated size from the handle - if (result) { - TrackMemoryAllocation(result->GetMemory().GetMemoryUsage()); - } - return result; - } - shared_ptr AllocateMemory(MemoryTag tag, BlockManager *block_manager, - bool can_destroy = true) override { - auto result = buffer_manager.AllocateMemory(tag, block_manager, can_destroy); - // Track allocation based on actual allocated size from the handle - if (result) { - TrackMemoryAllocation(result->GetMemory().GetMemoryUsage()); - } - return result; - } - BufferHandle Allocate(MemoryTag tag, idx_t block_size, bool can_destroy = true) override { - auto result = buffer_manager.Allocate(QueryContext(context), tag, block_size, can_destroy); - // Track allocation based on actual allocated size from the handle - if (result.GetBlockHandle()) { - TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); - } - return result; - } - BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) override { - auto result = buffer_manager.Allocate(QueryContext(context), tag, block_manager, can_destroy); - // Track allocation based on actual allocated size from the handle - if (result.GetBlockHandle()) { - TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); - } - return result; - } - BufferHandle Allocate(QueryContext context, MemoryTag tag, idx_t block_size, bool can_destroy = true) override { - auto result = buffer_manager.Allocate(context, tag, block_size, can_destroy); - if (result.GetBlockHandle()) { - TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); - } - return result; - } - BufferHandle Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, - bool can_destroy = true) override { - auto result = buffer_manager.Allocate(context, tag, block_manager, can_destroy); - if (result.GetBlockHandle()) { - TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); - } - return result; - } - BufferHandle Pin(shared_ptr &handle) override { - return Pin(QueryContext(context), handle); - } - BufferHandle Pin(const QueryContext &context, shared_ptr &handle) override { - return buffer_manager.Pin(context, handle); - } - void Prefetch(QueryContext context, vector> &handles) override { - return buffer_manager.Prefetch(context, handles); - } - void Unpin(shared_ptr &handle) override { - return buffer_manager.Unpin(handle); - } - - idx_t GetUsedMemory() const override { - return buffer_manager.GetUsedMemory(); - } - idx_t GetMaxMemory() const override { - return buffer_manager.GetMaxMemory(); - } - idx_t GetUsedSwap() const override { - return buffer_manager.GetUsedSwap(); - } - optional_idx GetMaxSwap() const override { - return buffer_manager.GetMaxSwap(); - } - idx_t GetBlockAllocSize() const override { - return buffer_manager.GetBlockAllocSize(); - } - idx_t GetBlockSize() const override { - return buffer_manager.GetBlockSize(); - } - idx_t GetOperatorMemoryLimit() const override { - idx_t global_budget = buffer_manager.GetOperatorMemoryLimit(); - const auto &config = ClientConfig::GetConfig(context); - if (!config.operator_memory_limit.IsValid()) { - return global_budget; - } - return MinValue(global_budget, config.operator_memory_limit.GetIndex()); - } - - shared_ptr RegisterTransientMemory(const idx_t size, BlockManager &block_manager) override { - auto result = buffer_manager.RegisterTransientMemory(size, block_manager); - TrackMemoryAllocation(size); - return result; - } - shared_ptr RegisterSmallMemory(const idx_t size) override { - auto result = buffer_manager.RegisterSmallMemory(size); - TrackMemoryAllocation(size); - return result; - } - shared_ptr RegisterSmallMemory(MemoryTag tag, const idx_t size) override { - auto result = buffer_manager.RegisterSmallMemory(tag, size); - TrackMemoryAllocation(size); - return result; - } - - BufferAllocator &GetBufferAllocator() override { - return buffer_manager.GetBufferAllocator(); - } - void ReserveMemory(idx_t size) override { - return buffer_manager.ReserveMemory(size); - } - void FreeReservedMemory(idx_t size) override { - return buffer_manager.FreeReservedMemory(size); - } - vector GetMemoryUsageInfo() const override { - return buffer_manager.GetMemoryUsageInfo(); - } - void SetMemoryLimit(idx_t limit = (idx_t)-1) override { - return buffer_manager.SetMemoryLimit(limit); - } - void SetSwapLimit(optional_idx limit = optional_idx()) override { - return buffer_manager.SetSwapLimit(limit); - } - - BlockManager &GetTemporaryBlockManager() override { - return buffer_manager.GetTemporaryBlockManager(); - } - vector GetTemporaryFiles() override { - return buffer_manager.GetTemporaryFiles(); - } - const string &GetTemporaryDirectory() const override { - return buffer_manager.GetTemporaryDirectory(); - } - void SetTemporaryDirectory(const string &new_dir) override { - return buffer_manager.SetTemporaryDirectory(new_dir); - } - bool HasTemporaryDirectory() const override { - return buffer_manager.HasTemporaryDirectory(); - } - bool HasFilesInTemporaryDirectory() const override { - return buffer_manager.HasFilesInTemporaryDirectory(); - } - - unique_ptr ConstructManagedBuffer(idx_t size, idx_t block_header_size, unique_ptr &&source, - FileBufferType type = FileBufferType::MANAGED_BUFFER) override { - return buffer_manager.ConstructManagedBuffer(size, block_header_size, std::move(source), type); - } - BufferPool &GetBufferPool() const override { - return buffer_manager.GetBufferPool(); - } - const DatabaseInstance &GetDatabase() const override { - return buffer_manager.GetDatabase(); - } - DatabaseInstance &GetDatabase() override { - return buffer_manager.GetDatabase(); - } - TemporaryMemoryManager &GetTemporaryMemoryManager() override { - return buffer_manager.GetTemporaryMemoryManager(); - } - - void PurgeQueue(const BlockHandle &handle) override { - return buffer_manager.PurgeQueue(handle); - } - void AddToEvictionQueue(shared_ptr &handle) override { - return buffer_manager.AddToEvictionQueue(handle); - } - void WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) override { - return buffer_manager.WriteTemporaryBuffer(context, tag, block_id, buffer); - } - unique_ptr ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block, - unique_ptr buffer) override { - return buffer_manager.ReadTemporaryBuffer(context, tag, block, std::move(buffer)); - } - void DeleteTemporaryFile(BlockMemory &memory) override { - return buffer_manager.DeleteTemporaryFile(memory); - } - -private: - void TrackMemoryAllocation(idx_t size) const { - if (size > 0) { - QueryProfiler::Get(context).TrackTotalMemoryAllocated(size); - } - } - - ClientContext &context; - BufferManager &buffer_manager; -}; - ClientData::ClientData(ClientContext &context) : catalog_search_path(make_uniq(context)) { auto &db = DatabaseInstance::GetDatabase(context); default_database = DatabaseManager::Get(db).GetDefaultDatabase(); - profiler = make_shared_ptr(context); temporary_objects = make_shared_ptr(db, AttachedDatabaseType::TEMP_DATABASE); temporary_objects->oid = DatabaseManager::Get(db).NextOid(); random_engine = make_uniq(); - file_opener = make_uniq(context); - client_file_system = make_uniq(context); - client_buffer_manager = make_uniq(context, db.GetBufferManager()); temporary_objects->Initialize(); } diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index c9228bf6f..a9ddf600c 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -145,6 +145,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(DebugWindowModeSetting), DUCKDB_SETTING_CALLBACK(DefaultBlockSizeSetting), DUCKDB_SETTING_CALLBACK(DefaultCollationSetting), + DUCKDB_GLOBAL(DefaultGrammarExtensionsSetting), DUCKDB_SETTING_CALLBACK(DefaultNullOrderSetting), DUCKDB_SETTING_CALLBACK(DefaultOrderSetting), DUCKDB_GLOBAL(DefaultSecretStorageSetting), @@ -245,6 +246,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(ReadAheadDepthSetting), DUCKDB_SETTING(RedactHttpLogsSetting), DUCKDB_SETTING_CALLBACK(RegexMatchOperatorSemanticsSetting), + DUCKDB_SETTING(ScalarAggregateMergeThresholdSetting), DUCKDB_SETTING(ScalarSubqueryErrorOnMultipleRowsSetting), DUCKDB_SETTING(SchedulerProcessPartialSetting), DUCKDB_LOCAL(SchemaSetting), @@ -703,10 +705,11 @@ void DBConfig::CheckLock(const Identifier &name) { // we are always allowed to change these settings return; } - if (!options.allowed_configs.empty()) { + auto allowed_configs = GetAllowedConfigs(); + if (!allowed_configs.empty()) { auto option = GetOptionByName(name); auto canonical_name = option ? Identifier(option->name) : name; - if (options.allowed_configs.find(canonical_name) != options.allowed_configs.end()) { + if (allowed_configs.find(canonical_name) != allowed_configs.end()) { // settings that are allowed through allowed_configs return; } @@ -898,10 +901,10 @@ SettingLookupResult DBConfig::TryGetCurrentSetting(const Identifier &key, Value optional_idx DBConfig::TryGetSettingIndex(const Identifier &name, optional_ptr &option) const { - ExtensionOption extension_option; - if (TryGetExtensionOption(name, extension_option)) { + auto extension_setting_index = user_settings.TryGetExtensionSettingIndex(name); + if (extension_setting_index.IsValid()) { // extension setting - return extension_option.setting_index; + return extension_setting_index; } option = GetOptionByName(name); if (option) { @@ -1020,6 +1023,16 @@ 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; +} + set DBConfig::GetDisabledOptimizers() const { lock_guard guard(disabled_optimizers_lock); return options.disabled_optimizers; diff --git a/src/duckdb/src/main/connection.cpp b/src/duckdb/src/main/connection.cpp index d64883fa2..3ce1fb199 100644 --- a/src/duckdb/src/main/connection.cpp +++ b/src/duckdb/src/main/connection.cpp @@ -15,6 +15,7 @@ #include "duckdb/main/relation/view_relation.hpp" #include "duckdb/parser/parsed_data/transaction_info.hpp" #include "duckdb/parser/parser.hpp" +#include "duckdb/planner/binder.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/main/statement_iterator.hpp" @@ -212,29 +213,17 @@ shared_ptr Connection::Table(const Identifier &table_name) { } shared_ptr Connection::Table(const Identifier &schema_name, const Identifier &table_name) { - auto table_info = TableInfo(Identifier::InvalidCatalog(), schema_name, table_name); - if (!table_info) { - throw CatalogException("Table %s does not exist!", - QualifiedName(Identifier(), schema_name, table_name) - .ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA)); - } - return make_shared_ptr(context, std::move(table_info)); + return Table(Identifier::InvalidCatalog(), schema_name, table_name); } shared_ptr Connection::Table(const Identifier &catalog_name, const Identifier &schema_name, const Identifier &table_name) { - unique_ptr table_info; - do { - table_info = TableInfo(catalog_name, schema_name, table_name); - if (table_info) { - break; - } - - if (catalog_name.empty() && !schema_name.empty()) { - table_info = TableInfo(schema_name, Identifier::DefaultSchema(), table_name); - } - } while (false); - + auto catalog = catalog_name; + auto schema = schema_name; + if (IsInvalidCatalog(catalog) && !IsInvalidSchema(schema)) { + context->RunFunctionInTransaction([&]() { Binder::BindSchemaOrCatalog(*context, catalog, schema); }); + } + auto table_info = TableInfo(catalog, schema, table_name); if (!table_info) { throw CatalogException("Table %s does not exist!", QualifiedName(catalog_name, schema_name, table_name) diff --git a/src/duckdb/src/main/connection_manager.cpp b/src/duckdb/src/main/connection_manager.cpp index 4035d018d..2e27d33a2 100644 --- a/src/duckdb/src/main/connection_manager.cpp +++ b/src/duckdb/src/main/connection_manager.cpp @@ -19,12 +19,17 @@ void ConnectionManager::AddConnection(ClientContext &context) { } void ConnectionManager::RemoveConnection(ClientContext &context) { - lock_guard lock(connections_lock); - for (auto &callback : ExtensionCallback::Iterate(context)) { + unique_lock lock(connections_lock); + auto callbacks = ExtensionCallback::Iterate(context); + for (auto &callback : callbacks) { callback->OnConnectionClosed(context); } connections.erase(context); connection_count = connections.size(); + lock.unlock(); + for (auto &callback : callbacks) { + callback->OnConnectionUnregistered(context); + } } idx_t ConnectionManager::GetConnectionCount() const { diff --git a/src/duckdb/src/main/context.cpp b/src/duckdb/src/main/context.cpp new file mode 100644 index 000000000..34f4c8caf --- /dev/null +++ b/src/duckdb/src/main/context.cpp @@ -0,0 +1,376 @@ +#include "duckdb/main/context.hpp" + +#include "duckdb/catalog/catalog_transaction.hpp" +#include "duckdb/common/opener_file_system.hpp" +#include "duckdb/logging/log_manager.hpp" +#include "duckdb/logging/logger.hpp" +#include "duckdb/main/client_config.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/client_context_file_opener.hpp" +#include "duckdb/main/client_context_state.hpp" +#include "duckdb/main/config.hpp" +#include "duckdb/main/database.hpp" +#include "duckdb/main/profiler/metrics_manager.hpp" +#include "duckdb/main/query_profiler.hpp" +#include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/storage/buffer_manager.hpp" +#include "duckdb/storage/buffer/block_handle.hpp" + +namespace duckdb { + +//! The file system of a client: the database file system with the client file opener +class ClientFileSystem : public OpenerFileSystem { +public: + explicit ClientFileSystem(ClientContext &context_p) : context(context_p) { + } + + FileSystem &GetFileSystem() const override { + auto &config = DBConfig::GetConfig(context); + return *config.file_system; + } + + optional_ptr GetOpener() const override { + return context.GetContext().TryGetFileOpener(); + } + +private: + ClientContext &context; +}; + +//! ContextBufferManager wraps the buffer manager to forward the services of a client. +class ContextBufferManager : public BufferManager { +public: + explicit ContextBufferManager(Context &context_p) : context(context_p) { + } + +public: + shared_ptr AllocateTemporaryMemory(MemoryTag tag, idx_t block_size, bool can_destroy = true) override { + auto result = Inner().AllocateTemporaryMemory(tag, block_size, can_destroy); + // Track allocation based on actual allocated size from the handle + if (result) { + TrackMemoryAllocation(result->GetMemory().GetMemoryUsage()); + } + return result; + } + shared_ptr AllocateMemory(MemoryTag tag, BlockManager *block_manager, + bool can_destroy = true) override { + auto result = Inner().AllocateMemory(tag, block_manager, can_destroy); + // Track allocation based on actual allocated size from the handle + if (result) { + TrackMemoryAllocation(result->GetMemory().GetMemoryUsage()); + } + return result; + } + BufferHandle Allocate(MemoryTag tag, idx_t block_size, bool can_destroy = true) override { + auto result = Inner().Allocate(QueryContext(context), tag, block_size, can_destroy); + // Track allocation based on actual allocated size from the handle + if (result.GetBlockHandle()) { + TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); + } + return result; + } + BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) override { + auto result = Inner().Allocate(QueryContext(context), tag, block_manager, can_destroy); + // Track allocation based on actual allocated size from the handle + if (result.GetBlockHandle()) { + TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); + } + return result; + } + BufferHandle Allocate(QueryContext context, MemoryTag tag, idx_t block_size, bool can_destroy = true) override { + auto result = Inner().Allocate(context, tag, block_size, can_destroy); + if (result.GetBlockHandle()) { + TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); + } + return result; + } + BufferHandle Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, + bool can_destroy = true) override { + auto result = Inner().Allocate(context, tag, block_manager, can_destroy); + if (result.GetBlockHandle()) { + TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); + } + return result; + } + BufferHandle Pin(shared_ptr &handle) override { + return Pin(QueryContext(context), handle); + } + BufferHandle Pin(const QueryContext &context, shared_ptr &handle) override { + return Inner().Pin(context, handle); + } + void Prefetch(QueryContext context, vector> &handles) override { + return Inner().Prefetch(context, handles); + } + void Unpin(shared_ptr &handle) override { + return Inner().Unpin(handle); + } + + idx_t GetUsedMemory() const override { + return Inner().GetUsedMemory(); + } + idx_t GetMaxMemory() const override { + return Inner().GetMaxMemory(); + } + idx_t GetUsedSwap() const override { + return Inner().GetUsedSwap(); + } + optional_idx GetMaxSwap() const override { + return Inner().GetMaxSwap(); + } + idx_t GetBlockAllocSize() const override { + return Inner().GetBlockAllocSize(); + } + idx_t GetBlockSize() const override { + return Inner().GetBlockSize(); + } + idx_t GetOperatorMemoryLimit() const override { + idx_t global_budget = Inner().GetOperatorMemoryLimit(); + auto config = context.TryGetClientConfig(); + if (!config || !config->operator_memory_limit.IsValid()) { + return global_budget; + } + return MinValue(global_budget, config->operator_memory_limit.GetIndex()); + } + + shared_ptr RegisterTransientMemory(const idx_t size, BlockManager &block_manager) override { + auto result = Inner().RegisterTransientMemory(size, block_manager); + TrackMemoryAllocation(size); + return result; + } + shared_ptr RegisterSmallMemory(const idx_t size) override { + auto result = Inner().RegisterSmallMemory(size); + TrackMemoryAllocation(size); + return result; + } + shared_ptr RegisterSmallMemory(MemoryTag tag, const idx_t size) override { + auto result = Inner().RegisterSmallMemory(tag, size); + TrackMemoryAllocation(size); + return result; + } + + BufferAllocator &GetBufferAllocator() override { + return Inner().GetBufferAllocator(); + } + void ReserveMemory(idx_t size) override { + return Inner().ReserveMemory(size); + } + void FreeReservedMemory(idx_t size) override { + return Inner().FreeReservedMemory(size); + } + vector GetMemoryUsageInfo() const override { + return Inner().GetMemoryUsageInfo(); + } + void SetMemoryLimit(idx_t limit = (idx_t)-1) override { + return Inner().SetMemoryLimit(limit); + } + void SetSwapLimit(optional_idx limit = optional_idx()) override { + return Inner().SetSwapLimit(limit); + } + + BlockManager &GetTemporaryBlockManager() override { + return Inner().GetTemporaryBlockManager(); + } + vector GetTemporaryFiles() override { + return Inner().GetTemporaryFiles(); + } + const string &GetTemporaryDirectory() const override { + return Inner().GetTemporaryDirectory(); + } + void SetTemporaryDirectory(const string &new_dir) override { + return Inner().SetTemporaryDirectory(new_dir); + } + bool HasTemporaryDirectory() const override { + return Inner().HasTemporaryDirectory(); + } + bool HasFilesInTemporaryDirectory() const override { + return Inner().HasFilesInTemporaryDirectory(); + } + + unique_ptr ConstructManagedBuffer(idx_t size, idx_t block_header_size, unique_ptr &&source, + FileBufferType type = FileBufferType::MANAGED_BUFFER) override { + return Inner().ConstructManagedBuffer(size, block_header_size, std::move(source), type); + } + BufferPool &GetBufferPool() const override { + return Inner().GetBufferPool(); + } + const DatabaseInstance &GetDatabase() const override { + return Inner().GetDatabase(); + } + DatabaseInstance &GetDatabase() override { + return Inner().GetDatabase(); + } + TemporaryMemoryManager &GetTemporaryMemoryManager() override { + return Inner().GetTemporaryMemoryManager(); + } + + void PurgeQueue(const BlockHandle &handle) override { + return Inner().PurgeQueue(handle); + } + void AddToEvictionQueue(shared_ptr &handle) override { + return Inner().AddToEvictionQueue(handle); + } + void WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) override { + return Inner().WriteTemporaryBuffer(context, tag, block_id, buffer); + } + unique_ptr ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block, + unique_ptr buffer) override { + return Inner().ReadTemporaryBuffer(context, tag, block, std::move(buffer)); + } + void DeleteTemporaryFile(BlockMemory &memory) override { + return Inner().DeleteTemporaryFile(memory); + } + +private: + void TrackMemoryAllocation(idx_t size) const { + auto profiler = context.TryGetQueryProfiler(); + if (size > 0 && profiler) { + profiler->TrackTotalMemoryAllocated(size); + } + } + + //! The database buffer manager is looked up lazily: it might not exist yet when the services are created + BufferManager &Inner() const { + return context.GetDatabase().GetBufferManager(); + } + + Context &context; +}; + +Context::Context(DatabaseInstance &db_p) : db(db_p), buffer_manager(make_uniq(*this)) { +} + +Context::~Context() { +} + +void Context::InitializeClient(ClientContext &context_p) { + D_ASSERT(!context); + context = &context_p; + config = make_uniq(); + file_opener = make_uniq(*this); + client_file_system = make_uniq(context_p); + profiler = make_shared_ptr(context_p); + registered_state = make_uniq(); +} + +DatabaseInstance &Context::GetDatabase() const { + return db; +} + +optional_ptr Context::TryGetClientContext() const { + return context; +} + +optional_ptr Context::TryGetClientContext(optional_ptr context) { + if (!context) { + return nullptr; + } + return context->TryGetClientContext(); +} + +optional_ptr Context::TryGetQueryProfiler(optional_ptr context) { + if (!context) { + return nullptr; + } + return context->TryGetQueryProfiler(); +} + +bool Context::IsClient() const { + return context != nullptr; +} + +bool Context::IsInterrupted() const { + return context && context->IsInterrupted(); +} + +CatalogTransaction Context::GetSystemCatalogTransaction() { + if (context) { + return CatalogTransaction::GetSystemCatalogTransaction(*context); + } + return CatalogTransaction::GetSystemTransaction(db); +} + +optional_ptr Context::TryGetClientConfig() const { + return config.get(); +} + +ClientConfig &Context::GetClientConfig() const { + D_ASSERT(config); + return *config; +} + +SettingLookupResult Context::TryGetCurrentSetting(const Identifier &key, Value &result) const { + if (context) { + return context->TryGetCurrentSetting(key, result); + } + return db.TryGetCurrentSetting(key, result); +} + +SettingLookupResult Context::TryGetCurrentUserSetting(idx_t setting_index, Value &result) const { + auto &db_config = DBConfig::GetConfig(db); + if (config) { + return config->user_settings.TryGetSetting(db_config.user_settings, setting_index, result); + } + return db_config.TryGetCurrentUserSetting(setting_index, result); +} + +Logger &Context::GetLogger() const { + if (logger) { + return *logger; + } + return Logger::Get(db); +} + +void Context::SetLogger(shared_ptr new_logger) { + logger = std::move(new_logger); +} + +const shared_ptr &Context::GetLoggerPtr() const { + return logger; +} + +FileSystem &Context::GetFileSystem() const { + if (client_file_system) { + return *client_file_system; + } + return FileSystem::GetFileSystem(db); +} + +optional_ptr Context::TryGetFileOpener() const { + return file_opener.get(); +} + +BufferManager &Context::GetBufferManager() const { + return *buffer_manager; +} + +TaskScheduler &Context::GetTaskScheduler() const { + return db.GetScheduler(); +} + +MetricsManager &Context::GetMetricsManager() const { + return db.GetMetricsManager(); +} + +RegisteredStateManager &Context::GetRegisteredState() const { + D_ASSERT(registered_state); + return *registered_state; +} + +optional_ptr Context::TryGetQueryProfiler() const { + return profiler.get(); +} + +QueryProfiler &Context::GetQueryProfiler() const { + D_ASSERT(profiler); + return *profiler; +} + +const shared_ptr &Context::GetQueryProfilerPtr() const { + return profiler; +} + +shared_ptr DatabaseInstance::Services() { + return make_shared_ptr(*this); +} + +} // namespace duckdb diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index 7694ac811..b258206eb 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -98,7 +98,10 @@ DatabaseInstance::~DatabaseInstance() { if (db_manager) { db_manager->ResetDatabases(); } - config.http_transport_manager->Close(); + // an instance whose initialization failed may not have every member yet, and a destructor cannot throw + if (config.http_transport_manager) { + config.http_transport_manager->Close(); + } // destroy child elements connection_manager.reset(); object_cache.reset(); @@ -114,7 +117,9 @@ DatabaseInstance::~DatabaseInstance() { buffer_manager.reset(); // Flush allocations and disable the background thread. - config.block_allocator->FlushOnShutdown(); + if (config.block_allocator) { + config.block_allocator->FlushOnShutdown(); + } Allocator::SetBackgroundThreads(false); // after all destruction is complete clear the cache entry config.db_cache_entry.reset(); @@ -174,7 +179,7 @@ DBConfig &DBConfig::GetConfig(DatabaseInstance &db) { } ClientConfig &ClientConfig::GetConfig(ClientContext &context) { - return context.config; + return context.GetContext().GetClientConfig(); } DBConfig &DBConfig::Get(AttachedDatabase &db) { @@ -186,7 +191,7 @@ const DBConfig &DBConfig::GetConfig(const DatabaseInstance &db) { } const ClientConfig &ClientConfig::GetConfig(const ClientContext &context) { - return context.config; + return context.GetContext().GetClientConfig(); } TransactionManager &TransactionManager::Get(AttachedDatabase &db) { diff --git a/src/duckdb/src/main/database_manager.cpp b/src/duckdb/src/main/database_manager.cpp index 4568ca841..c6ed33a8c 100644 --- a/src/duckdb/src/main/database_manager.cpp +++ b/src/duckdb/src/main/database_manager.cpp @@ -164,7 +164,7 @@ shared_ptr DatabaseManager::AttachDatabase(ClientContext &cont if (requires_tracking_attaches) { // Start timing the ATTACH-delay step. - auto timer = context.client_data->profiler->StartTimer(); + auto timer = QueryProfiler::Get(context.GetContext()).StartTimer(); // Start trying to attach. while (InsertDatabasePath(info, options) == InsertDatabasePathResult::ALREADY_EXISTS) { // database with this name and path already exists diff --git a/src/duckdb/src/main/db_instance_cache.cpp b/src/duckdb/src/main/db_instance_cache.cpp index 9c0d64abe..33e676ae2 100644 --- a/src/duckdb/src/main/db_instance_cache.cpp +++ b/src/duckdb/src/main/db_instance_cache.cpp @@ -136,7 +136,13 @@ shared_ptr DBInstanceCache::CreateInstanceInternal(const string &databas lock_guard create_db_lock(cache_entry->update_database_mutex); db_instances[cache_key] = cache_entry; db_instances_lock.unlock(); - db_instance = make_shared_ptr(instance_path, &config); + try { + db_instance = make_shared_ptr(instance_path, &config); + } catch (...) { + // the instance did not take the entry over, so the next attempt must not wait for it to expire + config.db_cache_entry.reset(); + throw; + } cache_entry->instance = db_instance->instance; } else { db_instances_lock.unlock(); diff --git a/src/duckdb/src/main/extension/extension_load.cpp b/src/duckdb/src/main/extension/extension_load.cpp index 5e0d7f25d..eef2efc3a 100644 --- a/src/duckdb/src/main/extension/extension_load.cpp +++ b/src/duckdb/src/main/extension/extension_load.cpp @@ -12,12 +12,9 @@ #include "duckdb/main/extension_manager.hpp" #include "duckdb/main/extension_repository_manager.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/parallel/task_executor.hpp" #include "mbedtls_wrapper.hpp" -#ifndef DUCKDB_NO_THREADS -#include -#endif // DUCKDB_NO_THREADS - namespace duckdb { //===--------------------------------------------------------------------===// @@ -316,24 +313,46 @@ static void ComputeSHA256FileSegment(FileHandle *handle, const idx_t start, cons *res = state.Finalize(); } +//! Hashes one segment of an extension that is being checked for a valid signature template -static void ComputeHashesOnSegments(F ComputeHashFun, T handle, const vector &splits, - vector &hash_chunks) { -#ifndef DUCKDB_NO_THREADS - vector threads; - threads.reserve(hash_chunks.size()); - for (idx_t i = 0; i < hash_chunks.size(); i++) { - threads.emplace_back(ComputeHashFun, handle, splits[i], splits[i + 1], &hash_chunks[i]); +class ExtensionHashTask : public BaseExecutorTask { +public: + ExtensionHashTask(TaskExecutor &executor, F compute_hash_fun_p, T handle_p, idx_t start_p, idx_t end_p, + string &hash_p) + : BaseExecutorTask(executor), compute_hash_fun(compute_hash_fun_p), handle(handle_p), start(start_p), + end(end_p), hash(hash_p) { } - for (auto &thread : threads) { - thread.join(); +public: + void ExecuteTask() override { + compute_hash_fun(handle, start, end, &hash); } -#else + + string TaskType() const override { + return "ExtensionHashTask"; + } + +private: + F compute_hash_fun; + T handle; + const idx_t start; + const idx_t end; + string &hash; +}; + +template +static void ComputeHashesOnSegments(DatabaseInstance &db, F compute_hash_fun, T handle, const vector &splits, + vector &hash_chunks) { + // the segments are hashed by the worker threads of the scheduler and by this thread, which waits for all of them + TaskExecutor executor(TaskScheduler::GetScheduler(db)); + vector> tasks; + tasks.reserve(hash_chunks.size()); for (idx_t i = 0; i < hash_chunks.size(); i++) { - ComputeHashFun(handle, splits[i], splits[i + 1], &hash_chunks[i]); + tasks.push_back(make_uniq>(executor, compute_hash_fun, handle, splits[i], splits[i + 1], + hash_chunks[i])); } -#endif // DUCKDB_NO_THREADS + executor.ScheduleTasks(std::move(tasks)); + executor.WorkOnTasks(); } static string FilterZeroAtEnd(string s) { @@ -430,7 +449,7 @@ bool ExtensionHelper::CheckExtensionSignature(DatabaseInstance &db, FileHandle & vector splits; InitializeAncillaryData(hash_chunks, splits, signature_offset); - ComputeHashesOnSegments(ComputeSHA256FileSegment, &handle, splits, hash_chunks); + ComputeHashesOnSegments(db, ComputeSHA256FileSegment, &handle, splits, hash_chunks); const string resulting_hash = ComputeFinalHash(hash_chunks); @@ -448,7 +467,7 @@ bool ExtensionHelper::CheckExtensionBufferSignature(DatabaseInstance &db, const vector splits; InitializeAncillaryData(hash_chunks, splits, buffer_length); - ComputeHashesOnSegments(ComputeSHA256Buffer, buffer, splits, hash_chunks); + ComputeHashesOnSegments(db, ComputeSHA256Buffer, buffer, splits, hash_chunks); const string resulting_hash = ComputeFinalHash(hash_chunks); diff --git a/src/duckdb/src/main/extension_callback_manager.cpp b/src/duckdb/src/main/extension_callback_manager.cpp index a59a69d65..f0298448a 100644 --- a/src/duckdb/src/main/extension_callback_manager.cpp +++ b/src/duckdb/src/main/extension_callback_manager.cpp @@ -47,24 +47,36 @@ ExtensionCallbackManager &ExtensionCallbackManager::Get(DatabaseInstance &db) { return DBConfig::GetConfig(db).GetCallbackManager(); } -ExtensionCallbackManager::ExtensionCallbackManager() : callback_registry(make_shared_ptr()) { +ExtensionCallbackManager::ExtensionCallbackManager() { + PublishRegistry(make_shared_ptr()); } ExtensionCallbackManager::~ExtensionCallbackManager() { } void ExtensionCallbackManager::AddExtensionSchema(const Identifier &schema) { + lock_guard guard(registry_lock); extension_schemas.push_back(schema.GetIdentifierName()); } vector ExtensionCallbackManager::GetExtensionSchemas() const { + lock_guard guard(registry_lock); return extension_schemas; } +shared_ptr ExtensionCallbackManager::CopyRegistry() const { + return make_shared_ptr(*callback_registry.load()); +} + +void ExtensionCallbackManager::PublishRegistry(shared_ptr new_registry) { + callback_registry.store(new_registry.get()); + registry_versions.push_back(std::move(new_registry)); +} + void ExtensionCallbackManager::Register(ParserExtension extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->parser_extensions.push_back(std::move(extension)); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(shared_ptr extension) { @@ -72,7 +84,7 @@ void ExtensionCallbackManager::Register(shared_ptr extension) throw InvalidInputException("Cannot register a null parser extension"); } lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); auto name = extension->Name(); auto res = new_registry->grammar_extensions.emplace(name, std::move(extension)); if (!res.second) { @@ -80,7 +92,9 @@ void ExtensionCallbackManager::Register(shared_ptr extension) throw InvalidInputException( "Can't add GrammarExtension \"%s\", a GrammarExtension by that name already exists"); } - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); + // sessions compare this against their cached grammar's version and recompose when it moved + ++grammar_registry_version; } void ExtensionCallbackManager::Register(shared_ptr extension) { @@ -91,62 +105,60 @@ void ExtensionCallbackManager::Register(shared_ptr extension) throw InvalidInputException("Dialect name cannot be empty"); } lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); for (auto &existing : new_registry->dialect_extensions) { if (StringUtil::CIEquals(existing->Name(), extension->Name())) { throw InvalidInputException("Dialect \"%s\" is already registered", extension->Name()); } } new_registry->dialect_extensions.push_back(std::move(extension)); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(PlannerExtension extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->planner_extensions.push_back(std::move(extension)); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(OptimizerExtension extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->optimizer_extensions.push_back(std::move(extension)); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(shared_ptr extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->operator_extensions.push_back(std::move(extension)); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(const string &name, shared_ptr extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->storage_extensions[name] = std::move(extension); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(shared_ptr extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->extension_callbacks.push_back(std::move(extension)); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } void ExtensionCallbackManager::Register(const string &name, shared_ptr extension) { lock_guard guard(registry_lock); - auto new_registry = make_shared_ptr(*callback_registry); + auto new_registry = CopyRegistry(); new_registry->profiler_extensions[name] = std::move(extension); - callback_registry.atomic_store(new_registry); + PublishRegistry(std::move(new_registry)); } template -ExtensionCallbackIteratorHelper::ExtensionCallbackIteratorHelper( - const vector &vec, shared_ptr callback_registry) - : vec(vec), callback_registry(std::move(callback_registry)) { +ExtensionCallbackIteratorHelper::ExtensionCallbackIteratorHelper(const vector &vec) : vec(vec) { } template @@ -154,48 +166,48 @@ ExtensionCallbackIteratorHelper::~ExtensionCallbackIteratorHelper() { } ExtensionCallbackIteratorHelper> ExtensionCallbackManager::OperatorExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto &operator_extensions = registry->operator_extensions; - return ExtensionCallbackIteratorHelper>(operator_extensions, std::move(registry)); + return ExtensionCallbackIteratorHelper>(operator_extensions); } case_insensitive_map_t> ExtensionCallbackManager::GrammarExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); return registry->grammar_extensions; } ExtensionCallbackIteratorHelper ExtensionCallbackManager::OptimizerExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto &optimizer_extensions = registry->optimizer_extensions; - return ExtensionCallbackIteratorHelper(optimizer_extensions, std::move(registry)); + return ExtensionCallbackIteratorHelper(optimizer_extensions); } ExtensionCallbackIteratorHelper ExtensionCallbackManager::ParserExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto &parser_extensions = registry->parser_extensions; - return ExtensionCallbackIteratorHelper(parser_extensions, std::move(registry)); + return ExtensionCallbackIteratorHelper(parser_extensions); } ExtensionCallbackIteratorHelper> ExtensionCallbackManager::DialectExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto &dialect_extensions = registry->dialect_extensions; - return ExtensionCallbackIteratorHelper>(dialect_extensions, std::move(registry)); + return ExtensionCallbackIteratorHelper>(dialect_extensions); } ExtensionCallbackIteratorHelper ExtensionCallbackManager::PlannerExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto &planner_extensions = registry->planner_extensions; - return ExtensionCallbackIteratorHelper(planner_extensions, std::move(registry)); + return ExtensionCallbackIteratorHelper(planner_extensions); } ExtensionCallbackIteratorHelper> ExtensionCallbackManager::ExtensionCallbacks() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto &extension_callbacks = registry->extension_callbacks; - return ExtensionCallbackIteratorHelper>(extension_callbacks, std::move(registry)); + return ExtensionCallbackIteratorHelper>(extension_callbacks); } optional_ptr ExtensionCallbackManager::FindGrammarExtension(const string &name) const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto entry = registry->grammar_extensions.find(name); if (entry == registry->grammar_extensions.end()) { return nullptr; @@ -204,7 +216,7 @@ optional_ptr ExtensionCallbackManager::FindGrammarExtension(co } optional_ptr ExtensionCallbackManager::FindStorageExtension(const string &name) const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto entry = registry->storage_extensions.find(name); if (entry == registry->storage_extensions.end()) { return nullptr; @@ -213,7 +225,7 @@ optional_ptr ExtensionCallbackManager::FindStorageExtension(co } optional_ptr ExtensionCallbackManager::FindProfilerExtension(const string &name) const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); auto entry = registry->profiler_extensions.find(name); if (entry == registry->profiler_extensions.end()) { return nullptr; @@ -222,12 +234,12 @@ optional_ptr ExtensionCallbackManager::FindProfilerExtension( } bool ExtensionCallbackManager::HasParserExtensions() const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); return !registry->parser_extensions.empty(); } optional_ptr ExtensionCallbackManager::GetDialectExtension(const string &name) const { - auto registry = callback_registry.atomic_load(); + auto registry = callback_registry.load(); for (auto &dialect : registry->dialect_extensions) { if (StringUtil::CIEquals(dialect->Name(), name)) { return dialect.get(); diff --git a/src/duckdb/src/main/external_resource_type_registry.cpp b/src/duckdb/src/main/external_resource_type_registry.cpp index c4175f712..daa840988 100644 --- a/src/duckdb/src/main/external_resource_type_registry.cpp +++ b/src/duckdb/src/main/external_resource_type_registry.cpp @@ -3,6 +3,8 @@ #include "duckdb/common/exception.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" +#include "duckdb/main/extension_entries.hpp" +#include "duckdb/main/extension_helper.hpp" #include "duckdb/parser/qualified_name.hpp" namespace duckdb { @@ -81,4 +83,20 @@ unique_ptr ExternalResourceTypeRegistry::Lookup(const stri return nullptr; } +unique_ptr ExternalResourceTypeRegistry::LookupOrAutoload(DatabaseInstance &db, + const string &name) { + auto ®istry = Get(db); + auto type = registry.Lookup(name); + if (type) { + return type; + } + // The extension registers its types on load, so a successful autoload makes the second lookup succeed + ExtensionHelper::TryAutoloadFromEntry(db, Identifier(name), EXTENSION_EXTERNAL_RESOURCE_TYPES); + return registry.Lookup(name); +} + +string ExternalResourceTypeRegistry::ProvidingExtension(const string &name) { + return ExtensionHelper::FindExtensionInEntries(Identifier(name), EXTENSION_EXTERNAL_RESOURCE_TYPES); +} + } // namespace duckdb diff --git a/src/duckdb/src/main/http/http_retry_budget.cpp b/src/duckdb/src/main/http/http_retry_budget.cpp index 756888a55..2327b51c0 100644 --- a/src/duckdb/src/main/http/http_retry_budget.cpp +++ b/src/duckdb/src/main/http/http_retry_budget.cpp @@ -235,8 +235,11 @@ bool HTTPRetryBudget::TryParseRetryAfterMs(const string &retry_after, uint64_t & delay_ms = seconds > MAX_BACKOFF_MS / 1000 ? MAX_BACKOFF_MS : seconds * 1000; return true; } + StrpTimeFormat::ParseResult parsed; timestamp_t target; - if (!RetryAfterDateFormat().TryParseTimestamp(value.c_str(), value.size(), target)) { + // The timestamp parser accepts the words epoch, infinity and -infinity, which are not HTTP-dates. + if (!RetryAfterDateFormat().Parse(value.c_str(), value.size(), parsed) || parsed.is_special || + !parsed.TryToTimestamp(target)) { return false; } const auto now_ms = Timestamp::GetEpochMs(Timestamp::GetCurrentTimestamp()); diff --git a/src/duckdb/src/main/http/http_util.cpp b/src/duckdb/src/main/http/http_util.cpp index eba3aa92f..9fd3193a0 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/context.hpp" #include "duckdb/common/multi_file/multi_file_list.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/common/exception/http_exception.hpp" @@ -575,23 +576,21 @@ void HTTPParams::Initialize(optional_ptr opener) { http_proxy_password = Settings::Get(*db); } - auto client_context = FileOpener::TryGetClientContext(opener); - if (client_context) { - logger = client_context->logger; + auto context = FileOpener::TryGetContext(opener); + if (context && context->IsClient()) { + logger = context->GetLoggerPtr(); } } unique_ptr HTTPUtil::InitializeParameters(DatabaseInstance &db, const string &url) { DatabaseFileOpener opener(db); - FileOpenerInfo info; - info.file_path = url; + FileOpenerInfo info(url); return InitializeParameters(&opener, &info); } unique_ptr HTTPUtil::InitializeParameters(ClientContext &context, const string &url) { - ClientContextFileOpener opener(context); - FileOpenerInfo info; - info.file_path = url; + ClientContextFileOpener opener(context.GetContext()); + FileOpenerInfo info(url); return InitializeParameters(&opener, &info); } diff --git a/src/duckdb/src/main/parser_context.cpp b/src/duckdb/src/main/parser_context.cpp index ea064a47c..2e28cc8b2 100644 --- a/src/duckdb/src/main/parser_context.cpp +++ b/src/duckdb/src/main/parser_context.cpp @@ -1,3 +1,5 @@ +#include "duckdb/common/string_util.hpp" +#include "duckdb/main/config.hpp" #include "duckdb/parser/parser.hpp" #include "duckdb/parser/peg/compiled_grammar.hpp" #include "duckdb/parser/peg/dialect_extension.hpp" @@ -17,6 +19,21 @@ Parser::Parser(ClientContext &context, IdentifierCaseMode identifier_case_mode) options.identifier_case_mode = identifier_case_mode; } +//! The names in a session's effective selection that are not registered grammar extensions. +//! Both settings validate at SET time, so this re-check guards future paths that could publish an +//! unvalidated default (a broken database default would otherwise make every parse fail, including +//! the SET that fixes it) +static vector MissingGrammarExtensions(const ExtensionCallbackManager &callback_manager, + const vector &names) { + vector missing; + for (auto &name : names) { + if (!callback_manager.FindGrammarExtension(name)) { + missing.push_back(name); + } + } + return missing; +} + shared_ptr CompiledGrammar::Get(ClientContext &context) { auto &client_config = ClientConfig::GetConfig(context); auto &callback_manager = ExtensionCallbackManager::Get(context); @@ -32,10 +49,44 @@ shared_ptr CompiledGrammar::Get(ClientContext &context) { } return dialect_extension->GetCompiledGrammar(context); } - if (client_config.cached_grammar) { - return client_config.cached_grammar; + auto registry_version = callback_manager.GrammarRegistryVersion(); + // the session selection wins when set (an explicitly empty list opts out of the database + // default), otherwise the database-wide default applies + auto selection = client_config.active_grammar_extensions.atomic_load(); + bool from_database_default = false; + if (!selection) { + selection = DBConfig::GetConfig(context).default_grammar_extensions.atomic_load(); + from_database_default = selection != nullptr; + } + auto cached = client_config.cached_grammar.atomic_load(); + if (cached && cached->registry_version == registry_version && cached->selection == selection) { + return cached->grammar; + } + // recompose: either nothing is cached yet, a grammar extension registered since (e.g. a LOAD + // between two statements of this session), or the effective selection was replaced by a SET + // (local or global, both publish fresh immutable snapshots) + if (from_database_default) { + auto missing = MissingGrammarExtensions(callback_manager, *selection); + if (!missing.empty()) { + throw InvalidConfigurationException( + "The 'default_grammar_extensions' setting names grammar extensions that are not loaded: %s. LOAD " + "them, change the global setting, or override the session with SET active_grammar_extensions", + StringUtil::Join(missing, ", ")); + } + } + auto grammar = ComposeSessionGrammar(context, selection ? *selection : vector()); + client_config.cached_grammar.atomic_store( + make_shared_ptr(CachedSessionGrammar {grammar, registry_version, std::move(selection)})); + return grammar; +} + +shared_ptr CompiledGrammar::ComposeSessionGrammar(ClientContext &context, + const vector &extension_names) { + auto &parser_cache = DatabaseInstance::GetDatabase(context).GetParserCache(); + if (extension_names.empty()) { + return parser_cache.GetMatcher(); } - return DatabaseInstance::GetDatabase(context).GetParserCache().GetMatcher(); + return parser_cache.GetMatcher(context, extension_names); } shared_ptr CompiledGrammar::Create(const ClientContext &context, diff --git a/src/duckdb/src/main/query_profiler.cpp b/src/duckdb/src/main/query_profiler.cpp index f08c61fec..203d273ce 100644 --- a/src/duckdb/src/main/query_profiler.cpp +++ b/src/duckdb/src/main/query_profiler.cpp @@ -14,6 +14,7 @@ #include "duckdb/main/client_config.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_data.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/profiler/profiling_utils.hpp" #include "duckdb/main/profiler/gathered_metrics.hpp" @@ -116,7 +117,11 @@ string QueryProfiler::GetSaveLocation() const { } QueryProfiler &QueryProfiler::Get(ClientContext &context) { - return *ClientData::Get(context).profiler; + return Get(context.GetContext()); +} + +QueryProfiler &QueryProfiler::Get(Context &context) { + return context.GetQueryProfiler(); } void QueryProfiler::Start(const string &query) { @@ -697,7 +702,7 @@ void QueryProfiler::RenderQueryTree(BaseTreeRenderer &ss) const { // the registered states write profiling info through an ostream - capture it and emit as layout text duckdb::stringstream state_info; - for (auto &state : context.registered_state->States()) { + for (auto &state : context.GetContext().GetRegisteredState().States()) { state->WriteProfilingInformation(state_info); } ss << state_info.str(); diff --git a/src/duckdb/src/main/secret/secret.cpp b/src/duckdb/src/main/secret/secret.cpp index ae87a2b65..ebb5ab10d 100644 --- a/src/duckdb/src/main/secret/secret.cpp +++ b/src/duckdb/src/main/secret/secret.cpp @@ -8,6 +8,7 @@ #include "duckdb/parser/parsed_data/create_info.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { @@ -161,7 +162,7 @@ KeyValueSecretReader::KeyValueSecretReader(DatabaseInstance &db_p, const char *s KeyValueSecretReader::KeyValueSecretReader(ClientContext &context_p, const char **secret_types, idx_t secret_types_len, string path_p) { - context = context_p; + context = &context_p.GetContext(); path = std::move(path_p); Initialize(secret_types, secret_types_len); } @@ -181,8 +182,7 @@ void KeyValueSecretReader::Initialize(const char **secret_types, idx_t secret_ty } auto &secret_manager = db->GetSecretManager(); - auto transaction = context ? CatalogTransaction::GetSystemCatalogTransaction(*context) - : CatalogTransaction::GetSystemTransaction(*db); + auto transaction = context ? context->GetSystemCatalogTransaction() : CatalogTransaction::GetSystemTransaction(*db); SecretMatch secret_match; for (idx_t i = 0; i < secret_types_len; i++) { @@ -201,16 +201,45 @@ void KeyValueSecretReader::Initialize(const char **secret_types, idx_t secret_ty KeyValueSecretReader::KeyValueSecretReader(const KeyValueSecret &secret_p, FileOpener &opener_p) : secret(secret_p) { db = opener_p.TryGetDatabase(); - context = opener_p.TryGetClientContext(); + context = &opener_p.TryGetContext(); } KeyValueSecretReader::KeyValueSecretReader(FileOpener &opener_p, optional_ptr info, const char **secret_types, idx_t secret_types_len) { db = opener_p.TryGetDatabase(); - context = opener_p.TryGetClientContext(); + context = &opener_p.TryGetContext(); if (info) { - path = info->file_path; + path = info->file.path; + } + string secret_name; + if (info && info->file.extended_info && info->file.extended_info->TryGetSecretName(secret_name)) { + // the file names the secret to open it with: look up none by path + if (!db) { + throw InvalidConfigurationException("Secret '%s' named by '%s' cannot be looked up without a database", + secret_name, path); + } + auto transaction = + context ? context->GetSystemCatalogTransaction() : CatalogTransaction::GetSystemTransaction(*db); + secret_entry = db->GetSecretManager().GetSecretByName(transaction, secret_name); + if (!secret_entry) { + throw InvalidConfigurationException("Secret '%s' named by '%s' not found", secret_name, path); + } + auto &named_secret = *secret_entry->secret; + if (named_secret.MatchScore(path) == NumericLimits::Minimum()) { + throw InvalidConfigurationException( + "Secret '%s' named by '%s' does not apply to it: the path is outside the secret's scope", secret_name, + path); + } + auto &type = named_secret.GetType(); + for (idx_t i = 0; i < secret_types_len; i++) { + if (StringUtil::CIEquals(type.GetIdentifierName(), secret_types[i])) { + secret = named_secret.Cast(); + return; + } + } + throw InvalidConfigurationException("Secret '%s' named by '%s' is of type %s, which this read does not take", + secret_name, path, type); } Initialize(secret_types, secret_types_len); diff --git a/src/duckdb/src/main/secret/secret_manager.cpp b/src/duckdb/src/main/secret/secret_manager.cpp index 8643c6338..03cd4188f 100644 --- a/src/duckdb/src/main/secret/secret_manager.cpp +++ b/src/duckdb/src/main/secret/secret_manager.cpp @@ -643,19 +643,20 @@ void SecretManager::InitializeSecrets(CatalogTransaction transaction) { return; } + // load the persistent storage first if enabled: it can throw (e.g. a permission error), in which case no + // storage is registered yet and the next secret statement retries and throws the same error + if (config.allow_persistent_secrets) { + LoadSecretStorageInternal( + make_uniq(*this, transaction.db, LOCAL_FILE_STORAGE_NAME, config.secret_path)); + } + // load the tmp storage - LoadSecretStorageInternal(make_uniq(TEMPORARY_STORAGE_NAME, *transaction.db)); + LoadSecretStorageInternal(make_uniq(TEMPORARY_STORAGE_NAME, transaction.db)); // load the connection-scoped storage: secrets created `IN connection_storage` are visible only to the // connection that created them, and are dropped automatically when that connection closes. LoadSecretStorageInternal(make_uniq(CONNECTION_STORAGE_NAME)); - if (config.allow_persistent_secrets) { - // load the persistent storage if enabled - LoadSecretStorageInternal( - make_uniq(*this, *transaction.db, LOCAL_FILE_STORAGE_NAME, config.secret_path)); - } - initialized = true; } } @@ -757,8 +758,10 @@ vector> SecretManager::GetSecretStorages() { } DefaultSecretGenerator::DefaultSecretGenerator(Catalog &catalog, SecretManager &secret_manager, - identifier_set_t &persistent_secrets) - : DefaultGenerator(catalog), secret_manager(secret_manager), persistent_secrets(persistent_secrets) { + identifier_set_t &persistent_secrets, + shared_ptr files_p) + : DefaultGenerator(catalog), secret_manager(secret_manager), persistent_secrets(persistent_secrets), + files(std::move(files_p)) { } unique_ptr DefaultSecretGenerator::CreateDefaultEntryInternal(const Identifier &entry_name) { @@ -770,8 +773,11 @@ unique_ptr DefaultSecretGenerator::CreateDefaultEntryInternal(cons auto &fs = FileSystem::GetLocal(catalog.GetDatabase()); - string base_secret_path = secret_manager.PersistentSecretPath(); - string secret_path = fs.JoinPath(base_secret_path, entry_name + ".duckdb_secret"); + // the file that was found for this secret, as the file name does not always identify the secret + string secret_path = files->Get(entry_name); + if (secret_path.empty()) { + return nullptr; + } // Note each file should contain 1 secret try { @@ -797,6 +803,7 @@ unique_ptr DefaultSecretGenerator::CreateDefaultEntryInternal(cons // Finally: we remove the default entry from the persistent_secrets, otherwise we aren't able to drop it // later persistent_secrets.erase(secret_lu); + files->Set(entry->secret->secret->GetName(), secret_path); return std::move(entry); } diff --git a/src/duckdb/src/main/secret/secret_storage.cpp b/src/duckdb/src/main/secret/secret_storage.cpp index 4b33f8acb..e47c0eee2 100644 --- a/src/duckdb/src/main/secret/secret_storage.cpp +++ b/src/duckdb/src/main/secret/secret_storage.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/local_file_system.hpp" #include "duckdb/main/database_file_opener.hpp" #include "duckdb/common/mutex.hpp" +#include "duckdb/common/serializer/binary_deserializer.hpp" #include "duckdb/common/serializer/binary_serializer.hpp" #include "duckdb/common/serializer/buffered_file_reader.hpp" #include "duckdb/common/types/uuid.hpp" @@ -130,25 +131,27 @@ SecretMatch SecretStorage::SelectBestMatch(SecretEntry &secret_entry, const stri unique_ptr CatalogSetSecretStorage::StoreSecret(unique_ptr secret, OnCreateConflict on_conflict, optional_ptr transaction) { - if (secrets->GetEntry(GetTransactionOrDefault(transaction), secret->GetName())) { + lock_guard guard(store_lock); + auto secret_name = secret->GetName(); + auto existing = secrets->GetEntry(GetTransactionOrDefault(transaction), secret_name); + if (existing) { if (on_conflict == OnCreateConflict::ERROR_ON_CONFLICT) { string persist_string = persistent ? "Persistent" : "Temporary"; string storage_string = persistent ? " in secret storage '" + storage_name + "'" : ""; - throw InvalidInputException("%s secret with name %s already exists%s!", persist_string, secret->GetName(), + throw InvalidInputException("%s secret with name %s already exists%s!", persist_string, secret_name, storage_string); } else if (on_conflict == OnCreateConflict::IGNORE_ON_CONFLICT) { return nullptr; - } else if (on_conflict == OnCreateConflict::ALTER_ON_CONFLICT) { + } else if (on_conflict != OnCreateConflict::REPLACE_ON_CONFLICT) { throw InternalException("unknown OnCreateConflict found while registering secret"); - } else if (on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT) { - secrets->DropEntry(GetTransactionOrDefault(transaction), secret->GetName(), true, true); } } - // Call write function + // the secret is written completely before the catalog changes, so a failed write leaves the catalog as it was WriteSecret(*secret, on_conflict); - - auto secret_name = secret->GetName(); + if (existing) { + secrets->DropEntry(GetTransactionOrDefault(transaction), secret_name, true, true); + } auto secret_entry = make_uniq(std::move(secret), Catalog::GetSystemCatalog(db)); secret_entry->temporary = !persistent; secret_entry->secret->storage_mode = storage_name; @@ -173,6 +176,7 @@ vector CatalogSetSecretStorage::AllSecrets(optional_ptr transaction) { + lock_guard guard(store_lock); auto entry = secrets->GetEntry(GetTransactionOrDefault(transaction), Identifier(name)); if (!entry) { if (on_entry_not_found == OnEntryNotFound::THROW_EXCEPTION) { @@ -219,9 +223,55 @@ unique_ptr CatalogSetSecretStorage::GetSecretByName(const string &n return nullptr; } +void PersistentSecretFiles::Set(const Identifier &secret_name, const string &path) { + lock_guard guard(lock); + paths[secret_name] = path; +} + +void PersistentSecretFiles::Remove(const Identifier &secret_name) { + lock_guard guard(lock); + paths.erase(secret_name); +} + +string PersistentSecretFiles::Get(const Identifier &secret_name) { + lock_guard guard(lock); + auto entry = paths.find(secret_name); + return entry == paths.end() ? string() : entry->second; +} + +bool PersistentSecretFiles::TryGetOtherSecretAt(const string &path, const Identifier &secret_name, + string &other_secret_name) { + lock_guard guard(lock); + for (auto &entry : paths) { + if (entry.second == path && entry.first != secret_name) { + other_secret_name = entry.first.GetIdentifierName(); + return true; + } + } + return false; +} + +//! Reads the name that is stored in a secret file, without loading the secret +static bool TryReadSecretName(FileSystem &fs, const string &path, string &name) { + try { + BufferedFileReader reader(fs, path.c_str()); + if (reader.Finished()) { + return false; + } + BinaryDeserializer deserializer(reader); + deserializer.Begin(); + deserializer.ReadProperty(100, "type"); + deserializer.ReadProperty(101, "provider"); + name = deserializer.ReadProperty(102, "name").GetIdentifierName(); + return true; + } catch (std::exception &) { + return false; + } +} + LocalFileSecretStorage::LocalFileSecretStorage(SecretManager &manager, DatabaseInstance &db_p, const string &name_p, const string &secret_path_p) - : CatalogSetSecretStorage(db_p, name_p, LOCAL_FILE_STORAGE_OFFSET), + : CatalogSetSecretStorage(db_p, name_p, LOCAL_FILE_STORAGE_OFFSET), files(make_shared_ptr()), secret_path(FileSystem::ExpandPath(secret_path_p, nullptr)) { persistent = true; @@ -233,8 +283,15 @@ LocalFileSecretStorage::LocalFileSecretStorage(SecretManager &manager, DatabaseI string full_path = fs.JoinPath(secret_path, fname); if (StringUtil::EndsWith(full_path, ".duckdb_secret")) { - string secret_name = fname.substr(0, fname.size() - 14); // size of file ext + string file_stem = fname.substr(0, fname.size() - 14); // size of file ext + string secret_name = SecretNameFromFileName(file_stem); + if (secret_name != file_stem) { + // the file is either the escaped file of a secret, or a file written before names were + // escaped that is named after a secret that looks escaped: the file tells which + TryReadSecretName(fs, full_path, secret_name); + } persistent_secrets.insert(Identifier(secret_name)); + files->Set(Identifier(secret_name), full_path); } }); } @@ -247,7 +304,7 @@ LocalFileSecretStorage::LocalFileSecretStorage(SecretManager &manager, DatabaseI auto &catalog = Catalog::GetSystemCatalog(db); secrets = make_uniq(Catalog::GetSystemCatalog(db), - make_uniq(catalog, manager, persistent_secrets)); + make_uniq(catalog, manager, persistent_secrets, files)); } void CatalogSetSecretStorage::WriteSecret(const BaseSecret &secret, OnCreateConflict on_conflict) { @@ -268,7 +325,7 @@ static void WriteSecretFileToDisk(FileSystem &fs, const string &path, const Base auto open_flags = FileFlags::FILE_FLAGS_WRITE; // Ensure we are writing to a private file with 600 permission open_flags |= FileFlags::FILE_FLAGS_PRIVATE; - // Ensure we overwrite anything that may have been placed there since our delete above + // Create the file, which must not exist yet open_flags |= FileFlags::FILE_FLAGS_FILE_CREATE_NEW; auto file_writer = BufferedFileWriter(fs, path, open_flags); @@ -278,7 +335,56 @@ static void WriteSecretFileToDisk(FileSystem &fs, const string &path, const Base secret.Serialize(serializer); serializer.End(); - file_writer.Flush(); + // a file system can report a failed write only when the file is synced or closed + file_writer.Sync(); + file_writer.Close(); +} + +struct SecretNameEscape { + char character; + const char *escaped; +}; + +static const SecretNameEscape SECRET_NAME_ESCAPES[] = {{'%', "%25"}, {'/', "%2F"}, {'\\', "%5C"}, + {':', "%3A"}, {'\0', "%00"}, {'.', "%2E"}}; + +string LocalFileSecretStorage::SecretFileName(const string &secret_name) { + string result; + for (idx_t i = 0; i < secret_name.size(); i++) { + auto c = secret_name[i]; + bool escaped = false; + for (auto &escape : SECRET_NAME_ESCAPES) { + // a dot is only escaped at the start of the name, so that the file is never "." or ".." or hidden + if (c == escape.character && (c != '.' || i == 0)) { + result += escape.escaped; + escaped = true; + break; + } + } + if (!escaped) { + result += c; + } + } + return result + ".duckdb_secret"; +} + +string LocalFileSecretStorage::SecretNameFromFileName(const string &file_name) { + string result; + for (idx_t i = 0; i < file_name.size(); i++) { + bool unescaped = false; + for (auto &escape : SECRET_NAME_ESCAPES) { + if (file_name.compare(i, 3, escape.escaped) == 0) { + result += escape.character; + i += 2; + unescaped = true; + break; + } + } + if (!unescaped) { + result += file_name[i]; + } + } + return result; } void LocalFileSecretStorage::WriteSecret(const BaseSecret &secret, OnCreateConflict on_conflict) { @@ -299,22 +405,42 @@ void LocalFileSecretStorage::WriteSecret(const BaseSecret &secret, OnCreateConfl } } - string file_path = fs.JoinPath(secret_path, secret.GetName() + ".duckdb_secret"); + auto &secret_name = secret.GetName(); + // a replaced secret keeps its file, which can predate escaped names, and a new secret gets its escaped name + string file_path = files->Get(secret_name); + if (file_path.empty()) { + file_path = fs.JoinPath(secret_path, SecretFileName(secret_name.GetIdentifierName())); + string other_secret; + if (files->TryGetOtherSecretAt(file_path, secret_name, other_secret)) { + throw IOException( + "Failed to write the file '%s' of the secret \"%s\": the file belongs to the secret \"%s\"", file_path, + secret_name.GetIdentifierName(), other_secret); + } + } string temp_path = file_path + ".tmp-" + UUID::ToString(UUID::GenerateRandomUUID()); - // If persistent file already exists remove - fs.TryRemoveFile(file_path); - // If temporary file already exists remove - fs.TryRemoveFile(temp_path); - - WriteSecretFileToDisk(fs, temp_path, secret); - - fs.MoveFile(temp_path, file_path); + // the complete file is renamed over the secret's file in one step, so a crash leaves the old file or the new one + try { + WriteSecretFileToDisk(fs, temp_path, secret); + fs.MoveFile(temp_path, file_path); + } catch (...) { + // the secret is not stored, so the temporary file goes, and its error cannot replace the one being reported + try { + fs.TryRemoveFile(temp_path); + } catch (...) { // NOLINT + } + throw; + } + files->Set(secret_name, file_path); } void LocalFileSecretStorage::RemoveSecret(const string &secret, OnEntryNotFound on_entry_not_found) { auto &fs = FileSystem::GetLocal(db); - string file = fs.JoinPath(secret_path, secret + ".duckdb_secret"); + string file = files->Get(Identifier(secret)); + if (file.empty()) { + file = fs.JoinPath(secret_path, SecretFileName(secret)); + } + files->Remove(Identifier(secret)); persistent_secrets.erase(Identifier(secret)); try { fs.RemoveFile(file); @@ -395,9 +521,12 @@ optional_ptr GetConnectionState(optional_ptrGetContext(); if (create) { - return context.registered_state->GetOrCreate(CONNECTION_SECRET_STATE_KEY).get(); + return context.GetContext() + .GetRegisteredState() + .GetOrCreate(CONNECTION_SECRET_STATE_KEY) + .get(); } - return context.registered_state->Get(CONNECTION_SECRET_STATE_KEY).get(); + return context.GetContext().GetRegisteredState().Get(CONNECTION_SECRET_STATE_KEY).get(); } } // namespace diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index c33199c63..c5fa71d98 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -312,7 +312,7 @@ void AllowedConfigsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) Value AllowedConfigsSetting::GetSetting(const ClientContext &context) { auto &config = DBConfig::GetConfig(context); vector configs; - for (auto &cfg : config.options.allowed_configs) { + for (auto &cfg : config.GetAllowedConfigs()) { configs.emplace_back(cfg); } return Value::LIST(LogicalType::VARCHAR, std::move(configs)); @@ -496,6 +496,96 @@ void DefaultOrderSetting::OnSet(SettingCallbackInfo &, Value &input) { } } +//! Parse a grammar extension list value: VARCHAR[] without duplicates +static vector ParseGrammarExtensionList(const char *setting_name, const Value &input) { + if (input.type().id() != LogicalTypeId::LIST) { + throw InvalidInputException("'%s' setting value should be of type VARCHAR[], not %s", setting_name, + input.type().ToString()); + } + case_insensitive_set_t distinct_names; + vector names; + for (auto &val : ListValue::GetChildren(input)) { + if (val.IsNull()) { + throw InvalidInputException("'%s' list values cannot be NULL", setting_name); + } + if (val.type().id() != LogicalTypeId::VARCHAR) { + throw InvalidInputException("'%s' list values should be of type VARCHAR, not %s", setting_name, + val.type().ToString()); + } + auto val_str = val.GetValue(); + if (!distinct_names.insert(val_str).second) { + throw InvalidInputException("'%s' list contains duplicate value '%s'", setting_name, val_str); + } + names.emplace_back(std::move(val_str)); + } + return names; +} + +//! Reject names that do not match a registered grammar extension +static void ValidateGrammarExtensionsExist(const char *setting_name, const ExtensionCallbackManager &callback_manager, + const vector &names) { + vector missing; + for (auto &ext : names) { + if (!callback_manager.FindGrammarExtension(ext)) { + missing.push_back(ext); + } + } + if (!missing.empty()) { + throw InvalidInputException("Can't set '%s', the following extensions don't exist: %s", setting_name, + StringUtil::Join(missing, ",")); + } +} + +//===----------------------------------------------------------------------===// +// Default Grammar Extensions +//===----------------------------------------------------------------------===// +void DefaultGrammarExtensionsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { + if (input.IsNull()) { + config.default_grammar_extensions.atomic_store(shared_ptr>()); + return; + } + // a broken database default must never exist: a session whose parser fails to compose cannot + // even parse the SET that would fix it, so the named extensions are validated here, which + // requires a running database (startup configuration cannot LOAD the extensions first anyway) + if (!db) { + throw InvalidConfigurationException( + "'default_grammar_extensions' can only be set on a running database: the named grammar extensions must " + "be registered when the setting is set"); + } + auto names = ParseGrammarExtensionList("default_grammar_extensions", input); + ValidateGrammarExtensionsExist("default_grammar_extensions", config.GetCallbackManager(), names); + if (names.empty()) { + config.default_grammar_extensions.atomic_store(shared_ptr>()); + return; + } + // compose eagerly, like the session setting: a selection that fails to compile errors here and + // leaves the default unchanged, so sessions never meet a default they cannot parse with. The + // result is deliberately discarded, a session compiles the selection on a parser-cache miss: + // this runs under the config lock, and the parser cache's lock is held through the extension + // callbacks, which may themselves read locked configuration from the parse path + vector> selected; + for (auto &name : names) { + selected.emplace_back(*config.GetCallbackManager().FindGrammarExtension(name)); + } + CompiledGrammar::Create(selected); + config.default_grammar_extensions.atomic_store(make_shared_ptr>(std::move(names))); +} + +void DefaultGrammarExtensionsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { + config.default_grammar_extensions.atomic_store(shared_ptr>()); +} + +Value DefaultGrammarExtensionsSetting::GetSetting(const ClientContext &context) { + auto default_extensions = DBConfig::GetConfig(context).default_grammar_extensions.atomic_load(); + vector values; + if (default_extensions) { + for (auto &extension : *default_extensions) { + values.push_back(extension); + } + } + return Value::LIST(LogicalType::VARCHAR, std::move(values)); +} + //===----------------------------------------------------------------------===// // Default Secret Storage //===----------------------------------------------------------------------===// @@ -581,7 +671,8 @@ void DisabledFilesystemsSetting::ResetGlobal(DatabaseInstance *db_p, DBConfig &c } Value DisabledFilesystemsSetting::GetSetting(const ClientContext &context) { - return Value(""); + auto &fs = FileSystem::GetFileSystem(*context.db); + return Value(StringUtil::Join(fs.GetDisabledFileSystems(), ",")); } //===----------------------------------------------------------------------===// @@ -832,7 +923,7 @@ void ForceVariantShredding::ResetGlobal(DatabaseInstance *db, DBConfig &config) Value ForceVariantShredding::GetSetting(const ClientContext &context) { auto &config = DBConfig::GetConfig(context); - return Value(config.options.force_variant_shredding.ToString()); + return Value(config.GetForceVariantShredding().ToString()); } //===----------------------------------------------------------------------===// @@ -1941,6 +2032,14 @@ Value CurrentDialectSetting::GetSetting(const ClientContext &context) { return Value(); } +//! Clear the session selection: the database-wide default (if any) applies again and the grammar is +//! recomposed lazily on the next parse, so clearing always succeeds even when the database default +//! is currently broken (the parse-time error then names the global setting) +static void ClearActiveGrammarExtensions(ClientConfig &client_config) { + client_config.active_grammar_extensions.atomic_store(shared_ptr>()); + client_config.cached_grammar.atomic_store(shared_ptr()); +} + void ActiveGrammarExtensionsSetting::SetLocal(ClientContext &context, const Value &input) { if (!OnLocalSet(context, input)) { return; @@ -1948,54 +2047,22 @@ void ActiveGrammarExtensionsSetting::SetLocal(ClientContext &context, const Valu auto &client_config = ClientConfig::GetConfig(context); if (input.IsNull()) { - client_config.active_grammar_extensions.clear(); - client_config.cached_grammar.reset(); + ClearActiveGrammarExtensions(client_config); return; } auto &config = DatabaseInstance::GetDatabase(context).config; auto &callback_manager = config.GetCallbackManager(); - case_insensitive_set_t distinct_names; - vector selected_extensions; - if (input.type().id() != LogicalTypeId::LIST) { - throw InvalidInputException("'active_grammar_extensions' setting value should be of type VARCHAR[], not %s", - input.type().ToString()); - } - auto &list_input = ListValue::GetChildren(input); - for (auto &val : list_input) { - if (val.type().id() != LogicalTypeId::VARCHAR) { - throw InvalidInputException("'active_grammar_extensions' list values should be of type VARCHAR, not %s", - val.type().ToString()); - } - auto val_str = val.GetValue(); - if (!distinct_names.insert(val_str).second) { - throw InvalidInputException("'active_grammar_extensions' list contains duplicate value '%s'", val_str); - } - selected_extensions.emplace_back(std::move(val_str)); - } - - vector missing; - for (auto &ext : selected_extensions) { - auto extension = callback_manager.FindGrammarExtension(ext); - if (!extension) { - missing.push_back(ext); - } - } - if (!missing.empty()) { - auto missing_list = StringUtil::Join(missing, ","); - throw InvalidInputException("Can't set 'active_grammar_extensions', the following extensions don't exist: %s", - missing_list); - } - if (selected_extensions.empty()) { - client_config.active_grammar_extensions.clear(); - client_config.cached_grammar.reset(); - return; - } - - auto compiled_grammar = - DatabaseInstance::GetDatabase(context).GetParserCache().GetMatcher(context, selected_extensions); - client_config.active_grammar_extensions = std::move(selected_extensions); - client_config.cached_grammar = std::move(compiled_grammar); + auto selected_extensions = ParseGrammarExtensionList("active_grammar_extensions", input); + ValidateGrammarExtensionsExist("active_grammar_extensions", callback_manager, selected_extensions); + // compose eagerly: a grammar that fails to compile errors at SET time, leaving the setting unchanged + auto registry_version = callback_manager.GrammarRegistryVersion(); + auto compiled_grammar = CompiledGrammar::ComposeSessionGrammar(context, selected_extensions); + auto selection = make_shared_ptr>(std::move(selected_extensions)); + auto snapshot = make_shared_ptr( + CachedSessionGrammar {std::move(compiled_grammar), registry_version, selection}); + client_config.active_grammar_extensions.atomic_store(selection); + client_config.cached_grammar.atomic_store(snapshot); } void ActiveGrammarExtensionsSetting::ResetLocal(ClientContext &context) { @@ -2003,8 +2070,7 @@ void ActiveGrammarExtensionsSetting::ResetLocal(ClientContext &context) { return; } auto &client_config = ClientConfig::GetConfig(context); - client_config.active_grammar_extensions.clear(); - client_config.cached_grammar.reset(); + ClearActiveGrammarExtensions(client_config); } bool ActiveGrammarExtensionsSetting::OnLocalSet(ClientContext &context, const Value &input) { @@ -2017,10 +2083,12 @@ bool ActiveGrammarExtensionsSetting::OnLocalReset(ClientContext &context) { Value ActiveGrammarExtensionsSetting::GetSetting(const ClientContext &context) { auto &client_config = ClientConfig::GetConfig(context); - auto &active_extensions = client_config.active_grammar_extensions; + auto active_extensions = client_config.active_grammar_extensions.atomic_load(); vector values; - for (auto &extension : active_extensions) { - values.push_back(extension); + if (active_extensions) { + for (auto &extension : *active_extensions) { + values.push_back(extension); + } } return Value::LIST(LogicalType::VARCHAR, std::move(values)); } diff --git a/src/duckdb/src/main/settings/settings.cpp b/src/duckdb/src/main/settings/settings.cpp index 321555919..64457c027 100644 --- a/src/duckdb/src/main/settings/settings.cpp +++ b/src/duckdb/src/main/settings/settings.cpp @@ -1,6 +1,7 @@ #include "duckdb/main/settings.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { @@ -8,6 +9,10 @@ bool Settings::TryGetSettingInternal(const ClientContext &context, idx_t setting return context.TryGetCurrentUserSetting(setting_index, result); } +bool Settings::TryGetSettingInternal(const Context &context, idx_t setting_index, Value &result) { + return context.TryGetCurrentUserSetting(setting_index, result); +} + bool Settings::TryGetSettingInternal(const DBConfig &config, idx_t setting_index, Value &result) { auto lookup_result = config.TryGetCurrentUserSetting(setting_index, result); return lookup_result; diff --git a/src/duckdb/src/main/user_settings.cpp b/src/duckdb/src/main/user_settings.cpp index e03aff2db..f8c2d42d1 100644 --- a/src/duckdb/src/main/user_settings.cpp +++ b/src/duckdb/src/main/user_settings.cpp @@ -136,6 +136,24 @@ bool GlobalUserSettings::TryGetExtensionOption(const Identifier &name, Extension return true; } +optional_idx GlobalUserSettings::TryGetExtensionSettingIndex(const Identifier &name) const { +#ifndef __MINGW32__ + auto &extension_setting_indexes = GetSettings().extension_setting_indexes; + auto entry = extension_setting_indexes.find(name); + if (entry == extension_setting_indexes.end()) { + return optional_idx(); + } + return entry->second; +#else + lock_guard l(lock); + auto entry = extension_parameters.find(name); + if (entry == extension_parameters.end()) { + return optional_idx(); + } + return entry->second.setting_index; +#endif +} + #ifndef __MINGW32__ CachedGlobalSettings &GlobalUserSettings::GetSettings() const { // Cache of global settings - used to allow lock-free access to global settings in a thread-safe manner @@ -151,7 +169,7 @@ CachedGlobalSettings &GlobalUserSettings::GetSettings() const { current_cache.uuid != uuid || current_cache.version != current_version) { // out-of-date, refresh the cache lock_guard guard(lock); - current_cache = CachedGlobalSettings(*this, settings_version, settings_map); + current_cache = CachedGlobalSettings(*this, settings_version, settings_map, extension_parameters); } return current_cache; #ifdef __MVS__ @@ -167,9 +185,14 @@ CachedGlobalSettings::CachedGlobalSettings() : version(0), uuid(0) { } CachedGlobalSettings::CachedGlobalSettings(const GlobalUserSettings &global_user_settings_p, idx_t version, - UserSettingsMap settings_p) + UserSettingsMap settings_p, + const identifier_map_t &extension_parameters) : global_user_settings(global_user_settings_p), version(version), settings(std::move(settings_p)), uuid(global_user_settings_p.GetUUID()) { + extension_setting_indexes.reserve(extension_parameters.size()); + for (auto &entry : extension_parameters) { + extension_setting_indexes.emplace(entry.first, entry.second.setting_index.GetIndex()); + } } #endif diff --git a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp index 35ad1df26..f4ea11e44 100644 --- a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp +++ b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp @@ -17,9 +17,11 @@ namespace duckdb { void ApplyFunctionalDependencies::VisitLogicalGet(LogicalGet &get) { VisitOperatorChildren(get); + // Table-in/out functions need not preserve the multiplicity of their input keys. + result.clear(); auto table = get.GetTable(); - if (!table || !table->IsDuckTable() || !get.projected_input.empty() || get.GetColumnIds().empty()) { + if (!table || !table->IsDuckTable() || !get.children.empty() || get.GetColumnIds().empty()) { return; } unordered_map column_bindings; diff --git a/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp b/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp index 66a13a9a8..316844711 100644 --- a/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp +++ b/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp @@ -73,6 +73,15 @@ void ColumnLifetimeAnalyzer::VisitOperator(LogicalOperator &op) { analyzer.StandardVisitOperator(op); return; } + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { + ColumnLifetimeAnalyzer producer(optimizer, root); + for (auto &binding : op.children[0]->GetColumnBindings()) { + producer.column_references.insert(binding); + } + producer.VisitOperator(*op.children[0]); + VisitOperator(*op.children[1]); + return; + } case LogicalOperatorType::LOGICAL_ASOF_JOIN: case LogicalOperatorType::LOGICAL_DELIM_JOIN: case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { @@ -114,9 +123,8 @@ void ColumnLifetimeAnalyzer::VisitOperator(LogicalOperator &op) { case LogicalOperatorType::LOGICAL_UNION: case LogicalOperatorType::LOGICAL_EXCEPT: case LogicalOperatorType::LOGICAL_INTERSECT: - case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: - case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { - // for set operations/materialized CTEs we don't remove anything, just recursively visit the children + case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: { + // for set operations/recursive CTEs we don't remove anything, just recursively visit the children // FIXME: for UNION we can remove unreferenced columns as long as everything_referenced is false (i.e. we // encounter a UNION node that is not preceded by a DISTINCT) ColumnLifetimeAnalyzer analyzer(optimizer, root, true); diff --git a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index b8b82fe8f..2fd688281 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -9,8 +9,13 @@ #include "duckdb/common/arena_containers/arena_unordered_map.hpp" #include "duckdb/common/arena_containers/arena_vector.hpp" #include "duckdb/common/unordered_set.hpp" +#include "duckdb/common/limits.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/logical_operator_repeatability.hpp" #include @@ -19,17 +24,19 @@ namespace duckdb { //===--------------------------------------------------------------------===// // Subplan Signature/Info //===--------------------------------------------------------------------===// -static vector GetExpandedColumnBindings(LogicalOperator &op) { +static vector +GetExpandedColumnBindings(LogicalOperator &op, optional_ptr>> scans = nullptr, + optional_ptr>> expression_sources = nullptr) { switch (op.type) { case LogicalOperatorType::LOGICAL_FILTER: case LogicalOperatorType::LOGICAL_ORDER_BY: case LogicalOperatorType::LOGICAL_LIMIT: case LogicalOperatorType::LOGICAL_TOP_N: case LogicalOperatorType::LOGICAL_DISTINCT: - return GetExpandedColumnBindings(*op.children[0]); + return GetExpandedColumnBindings(*op.children[0], scans, expression_sources); case LogicalOperatorType::LOGICAL_WINDOW: case LogicalOperatorType::LOGICAL_UNNEST: { - auto bindings = GetExpandedColumnBindings(*op.children[0]); + auto bindings = GetExpandedColumnBindings(*op.children[0], scans, expression_sources); const auto table_index = op.GetTableIndex()[0]; for (auto col_idx : ProjectionIndex::GetIndexes(op.expressions.size())) { bindings.emplace_back(table_index, col_idx); @@ -40,7 +47,10 @@ static vector GetExpandedColumnBindings(LogicalOperator &op) { case LogicalOperatorType::LOGICAL_ASOF_JOIN: case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { auto &join = op.Cast(); - auto left_bindings = GetExpandedColumnBindings(*op.children[0]); + if (join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI) { + return GetExpandedColumnBindings(*op.children[1], scans, expression_sources); + } + auto left_bindings = GetExpandedColumnBindings(*op.children[0], scans, expression_sources); if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) { return left_bindings; } @@ -48,25 +58,95 @@ static vector GetExpandedColumnBindings(LogicalOperator &op) { left_bindings.emplace_back(join.mark_index, ProjectionIndex(0)); return left_bindings; } - auto right_bindings = GetExpandedColumnBindings(*op.children[1]); - if (join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI) { - return right_bindings; - } + auto right_bindings = GetExpandedColumnBindings(*op.children[1], scans, expression_sources); left_bindings.insert(left_bindings.end(), right_bindings.begin(), right_bindings.end()); return left_bindings; } case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: case LogicalOperatorType::LOGICAL_POSITIONAL_JOIN: { - auto left_bindings = GetExpandedColumnBindings(*op.children[0]); - auto right_bindings = GetExpandedColumnBindings(*op.children[1]); + auto left_bindings = GetExpandedColumnBindings(*op.children[0], scans, expression_sources); + auto right_bindings = GetExpandedColumnBindings(*op.children[1], scans, expression_sources); left_bindings.insert(left_bindings.end(), right_bindings.begin(), right_bindings.end()); return left_bindings; } + case LogicalOperatorType::LOGICAL_GET: + if (scans) { + scans->emplace_back(op.Cast()); + } + return op.GetColumnBindings(); + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + case LogicalOperatorType::LOGICAL_PROJECTION: + if (expression_sources) { + expression_sources->emplace_back(op); + } + return op.GetColumnBindings(); default: return op.GetColumnBindings(); } } +static TableIndex GetExpressionOutputTableIndex(const LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + return op.Cast().aggregate_index; + case LogicalOperatorType::LOGICAL_PROJECTION: + return op.Cast().table_index; + default: + throw InternalException("Operator has no expandable expression outputs"); + } +} + +static bool CanShareSubplanExpression(const Expression &expr) { + if (expr.IsVolatile() || expr.CanThrow() || ExpressionBarrier::Contains(expr)) { + return false; + } + bool unsafe = false; + ExpressionIterator::VisitExpression( + expr, [&](const BoundColumnRefExpression &ref) { unsafe |= ref.Depth() != 0; }); + ExpressionIterator::VisitExpression(expr, [&](const BoundFunctionExpression &function) { + unsafe |= ExpressionFilter::IsOptionalExpression(function); + }); + return !unsafe; +} + +static bool HasFixedSizeState(const LogicalType &type, const AggregateStateField &field) { + switch (field.kind) { + case AggregateFieldKind::PRIMITIVE: + return TypeIsConstantSize(type.InternalType()); + case AggregateFieldKind::OPTIONAL_VALUE: + return field.children.size() == 1 && HasFixedSizeState(type, field.children[0]); + case AggregateFieldKind::STRUCT: { + if (type.id() != LogicalTypeId::STRUCT) { + return false; + } + const auto &types = StructType::GetChildTypes(type); + if (types.size() != field.children.size()) { + return false; + } + for (idx_t i = 0; i < types.size(); i++) { + if (!HasFixedSizeState(types[i].second, field.children[i])) { + return false; + } + } + return true; + } + default: + return false; + } +} + +static bool CanCombineAggregateState(const BoundAggregateExpression &aggregate) { + const auto &function = aggregate.Function(); + if (aggregate.IsDistinct() || aggregate.GetOrderBys() || + aggregate.StateExportMode() != AggregateStateExportMode::NONE || !function.HasGetStateTypeCallback() || + function.HasExportAggregateStateCallback() || function.HasImportAggregateStateCallback()) { + return false; + } + // Combining growing states can use more memory than evaluating the original aggregates separately. + const auto layout = function.GetStateType(aggregate.BindInfo().get()); + return HasFixedSizeState(layout.type, layout.field); +} + enum class ConversionType { TO_CANONICAL, RESTORE_ORIGINAL, @@ -121,6 +201,10 @@ class PlanSignatureTableIndexMap { return table_index_map; } + void AddColumnMapping(TableIndex table_index, ProjectionIndex original, ProjectionIndex canonical) { + table_index_map.at(table_index).Insert(original, canonical); + } + template bool Convert(LogicalOperator &op) { Initialize(op); @@ -571,7 +655,8 @@ class PlanSignature { public: static arena_ptr Create(PlanSignatureCreateState &state, LogicalOperator &op, - vector> &&child_signatures) { + vector> &&child_signatures, + const vector> &positional_inputs = {}) { if (!OperatorIsSupported(op)) { return nullptr; } @@ -581,6 +666,9 @@ class PlanSignature { // Serialize canonical representation of operator const auto offset = state.stream.GetPosition(); state.serializer.Begin(); + state.serializer.WriteProperty(100, "positional_inputs", positional_inputs); + state.serializer.End(); + state.serializer.Begin(); try { // Operators will throw if they cannot serialize, so we need to try/catch here op.Serialize(state.serializer); } catch (std::exception &) { @@ -637,7 +725,7 @@ class PlanSignature { return String(char_ptr_cast(stream.GetData() + offset), NumericCast(length)); } - static bool OperatorIsSupported(const LogicalOperator &op) { + static bool OperatorIsSupported(LogicalOperator &op) { if (!op.SupportSerialization()) { return false; } @@ -665,6 +753,11 @@ class PlanSignature { return true; case LogicalOperatorType::LOGICAL_GET: { auto &get = op.Cast(); + // A function's arguments do not describe hidden state or volatile work performed by its scan. + // Only share scans that explicitly promise repeatable results, or scan an ordinary table. + if (ClassifyLogicalOperatorRepeatability(get) != LogicalOperatorRepeatability::REPEATABLE) { + return false; + } if (get.bind_data && !get.function.HasSerializationCallbacks() && get.parameters.empty()) { // Without serialization callbacks, the serialized form carries only the call parameters // (see LogicalGet::Serialize). A scan without positional parameters - e.g., one created through @@ -784,6 +877,72 @@ class CommonSubplanFinder { } }; + struct SubplanBindings { + struct ExpressionSource { + ExpressionSource(LogicalOperator &op, const vector> &expressions, + SubplanBindings input) + : op(op), expressions(expressions), input(make_uniq(std::move(input))) { + } + + LogicalOperator &op; + const vector> &expressions; + unique_ptr input; + }; + + column_binding_map_t bindings; + unordered_map> scans; + unordered_map> expression_sources; + + bool Contains(const ColumnBinding &binding) const { + auto scan = scans.find(binding.table_index); + if (bindings.find(binding) != bindings.end() || (scan != scans.end() && scan->second)) { + return true; + } + auto expression_source = expression_sources.find(binding.table_index); + if (expression_source == expression_sources.end() || !expression_source->second) { + return false; + } + auto &source = *expression_source->second; + bool available = true; + ExpressionIterator::VisitExpression( + *source.expressions[binding.column_index], + [&](const BoundColumnRefExpression &ref) { available &= source.input->Contains(ref.Binding()); }); + return available; + } + + ColumnBinding Expose(const ColumnBinding &binding) { + auto entry = bindings.find(binding); + if (entry != bindings.end()) { + return entry->second; + } + ColumnBinding result; + auto scan_entry = scans.find(binding.table_index); + if (scan_entry != scans.end() && scan_entry->second) { + auto &scan = *scan_entry->second; + // Appending columns preserves existing filter and expression bindings. + auto column_index = scan.TryGetProjectionIndex(binding.column_index.GetIndex()); + if (!column_index.IsValid()) { + column_index = scan.AddColumnId(binding.column_index.GetIndex()); + } + // Scan projections prune columns; they cannot reorder a full-width scan. + scan.projection_ids.clear(); + result = ColumnBinding(scan.table_index, column_index); + } 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()); + }); + result = ColumnBinding(GetExpressionOutputTableIndex(source.op), + ProjectionIndex(source.op.expressions.size())); + source.op.expressions.push_back(std::move(expression)); + } + bindings.emplace(binding, result); + return result; + } + }; + public: void FindCommonSubplans(reference> root) { // Find first operator with more than 1 child @@ -826,6 +985,7 @@ class CommonSubplanFinder { D_ASSERT(to_canonical_table_index.find(table_index) == to_canonical_table_index.end()); to_canonical_table_index.emplace(table_index, next_canonical_table_index); } + RegisterExpressionBindings(current.op); // Add new subplan SubplanInfo subplan_info(state.allocator, current.op, std::move(canonical_table_indices), @@ -839,6 +999,7 @@ class CommonSubplanFinder { to_canonical_table_index.emplace(current_op_table_index[i], info.canonical_table_indices[i]); } + RegisterExpressionBindings(current.op); // Add subplan to existing info.subplans.push_back({current.op, GetCanonicalBindings(*current.op)}); @@ -878,7 +1039,8 @@ class CommonSubplanFinder { const auto subplan_count = subplan_info.subplans.size() * signature.OperatorCount(); const auto parent_subplan_count = parent_it->second.subplans.size(); const auto parent_count = parent_subplan_count * parent_signature->OperatorCount(); - if (parent_subplan_count != 1 && parent_count >= subplan_count) { + if (parent_subplan_count != 1 && parent_count >= subplan_count && + ShouldMaterialize(parent_it->second)) { to_remove.push_back(signature); // Parent is better, this one is redundant continue; } @@ -918,7 +1080,6 @@ class CommonSubplanFinder { void ConvertSubplansToCTEs(Optimizer &optimizer, unique_ptr &op) { const auto sorted_subplans = GetSortedSubplans(); idx_t index = 1; - bool converted_subplans = false; for (auto &entry : sorted_subplans) { auto &subplan_info = entry.get().second; if (!ShouldMaterialize(subplan_info)) { @@ -956,35 +1117,26 @@ class CommonSubplanFinder { } } - if (required_canonical_bindings.size() != primary_subplan.canonical_bindings.size()) { - // The signature ignores projection maps. If duplicate subplans expose different - // subsets of the same work, widen the materialized producer just enough to make - // every referenced output available, then project each reader back to its original - // schema below. - ClearProjectionMaps(*primary_subplan.op.get()); - primary_subplan.op.get()->ResolveOperatorTypes(); - } - - const auto materialized_bindings = primary_subplan.op.get()->GetColumnBindings(); - const auto materialized_canonical_bindings = GetCanonicalBindings(*primary_subplan.op.get()); - column_binding_map_t materialized_binding_index; - for (idx_t i = 0; i < materialized_canonical_bindings.size(); i++) { - materialized_binding_index.emplace(materialized_canonical_bindings[i], i); - } - - vector types; + auto available_bindings = GetAvailableBindings(*primary_subplan.op.get()); vector materialized_output_bindings; - types.reserve(required_canonical_bindings.size()); materialized_output_bindings.reserve(required_canonical_bindings.size()); column_binding_map_t cte_binding_index; for (idx_t i = 0; i < required_canonical_bindings.size(); i++) { auto &cb = required_canonical_bindings[i]; - const auto entry = materialized_binding_index.find(cb); - D_ASSERT(entry != materialized_binding_index.end()); // guaranteed by FilterSubplans - const auto materialized_col_idx = entry->second; cte_binding_index.emplace(cb, i); - types.push_back(primary_subplan.op.get()->types[materialized_col_idx]); - materialized_output_bindings.push_back(materialized_bindings[materialized_col_idx]); + materialized_output_bindings.push_back(available_bindings.Expose(cb)); + } + ClearProjectionMaps(*primary_subplan.op.get()); + primary_subplan.op.get()->ResolveOperatorTypes(); + + const auto materialized_bindings = primary_subplan.op.get()->GetColumnBindings(); + column_binding_map_t materialized_binding_index; + for (idx_t i = 0; i < materialized_bindings.size(); i++) { + materialized_binding_index.emplace(materialized_bindings[i], i); + } + vector types; + for (auto &binding : materialized_output_bindings) { + types.push_back(primary_subplan.op.get()->types[materialized_binding_index.at(binding)]); } // Get names @@ -1097,17 +1249,77 @@ class CommonSubplanFinder { } break; } - converted_subplans = true; - } - if (converted_subplans) { - // Subplan replacement changes child output bindings under existing positional projection maps. - // Invalidate them here; column lifetime runs again later and rebuilds the maps. - ClearProjectionMaps(*op); } } private: - arena_ptr CreatePlanSignature(const unique_ptr &op) { + bool CanExpandExpressionOutputs(const LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + break; + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = op.Cast(); + if (!aggregate.groups.empty() || !aggregate.grouping_sets.empty() || + !aggregate.grouping_functions.empty()) { + return false; + } + for (const auto &expression : aggregate.expressions) { + if (!CanCombineAggregateState(expression->Cast())) { + return false; + } + } + break; + } + default: + return false; + } + for (const auto &expression : op.expressions) { + if (!CanShareSubplanExpression(*expression)) { + return false; + } + } + unordered_map input_tables; + for (const auto &binding : GetExpandedColumnBindings(*op.children[0])) { + const auto canonical_table_index = to_canonical_table_index.at(binding.table_index); + auto entry = input_tables.emplace(canonical_table_index, binding.table_index); + if (!entry.second && entry.first->second != binding.table_index) { + // Expression matching must distinguish repeated occurrences of the same input. + return false; + } + } + return true; + } + + void RegisterExpressionBindings(unique_ptr &op) { + if (!CanExpandExpressionOutputs(*op)) { + return; + } + const auto output_table_index = GetExpressionOutputTableIndex(*op); + auto &expressions = canonical_expressions[to_canonical_table_index.at(output_table_index)]; + 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()); + }); + idx_t index = 0; + for (; index < expressions.size(); index++) { + if (used_indexes.find(index) == used_indexes.end() && + expression->GetReturnType().EqualsIncludingCollation(expressions[index]->GetReturnType()) && + expression->Equals(*expressions[index])) { + break; + } + } + if (index == expressions.size()) { + expressions.push_back(std::move(expression)); + } + used_indexes.insert(index); + state.table_index_map.AddColumnMapping(output_table_index, ProjectionIndex(i), ProjectionIndex(index)); + } + } + + arena_ptr CreatePlanSignature(unique_ptr &op) { vector> child_signatures; for (auto &child : op->children) { auto it = operator_infos.find(child); @@ -1117,7 +1329,33 @@ class CommonSubplanFinder { } child_signatures.emplace_back(*it->second.signature); } - return PlanSignature::Create(state, *op, std::move(child_signatures)); + vector> positional_inputs; + switch (op->type) { + case LogicalOperatorType::LOGICAL_UNION: + case LogicalOperatorType::LOGICAL_EXCEPT: + case LogicalOperatorType::LOGICAL_INTERSECT: + case LogicalOperatorType::LOGICAL_PIVOT: + case LogicalOperatorType::LOGICAL_GET: + // These operators consume child values by position rather than by bound expressions. + for (auto &child : op->children) { + auto bindings = child->GetColumnBindings(); + for (auto &binding : bindings) { + binding = GetCanonicalBinding(binding); + } + positional_inputs.push_back(std::move(bindings)); + } + break; + default: + break; + } + if (CanExpandExpressionOutputs(*op)) { + // Match the row domain separately from the expandable expression outputs. + auto expressions = std::move(op->expressions); + auto signature = PlanSignature::Create(state, *op, std::move(child_signatures), positional_inputs); + op->expressions = std::move(expressions); + return signature; + } + return PlanSignature::Create(state, *op, std::move(child_signatures), positional_inputs); } arena_vector GetCanonicalBindings(LogicalOperator &op) { @@ -1156,29 +1394,65 @@ class CommonSubplanFinder { return a.get(); } - arena_vector GetCanonicalBindings(const vector &original_bindings) { + ColumnBinding GetCanonicalBinding(const ColumnBinding &binding) { + auto generated_entry = generated_binding_map.find(binding); + if (generated_entry != generated_binding_map.end()) { + return generated_entry->second; + } const auto &table_index_map = state.table_index_map.GetMap(); + const auto canonical_table_index = to_canonical_table_index.at(binding.table_index); + auto &table_map = table_index_map.at(binding.table_index); + auto column_index = table_map.Empty() + ? binding.column_index + : table_map.Get(binding.column_index); + return ColumnBinding(canonical_table_index, column_index); + } + + arena_vector GetCanonicalBindings(const vector &original_bindings) { arena_vector canonical_bindings(state.allocator); for (auto &cb : original_bindings) { - auto generated_entry = generated_binding_map.find(cb); - if (generated_entry != generated_binding_map.end()) { - canonical_bindings.push_back(generated_entry->second); - continue; - } - const auto canonical_table_index = to_canonical_table_index.at(cb.table_index); - auto &table_map = table_index_map.at(cb.table_index); - if (table_map.Empty()) { - canonical_bindings.emplace_back(canonical_table_index, cb.column_index); - } else { - const auto canonical_col_idx = table_map.Get(cb.column_index); - canonical_bindings.emplace_back(canonical_table_index, canonical_col_idx); - } + canonical_bindings.push_back(GetCanonicalBinding(cb)); } return canonical_bindings; } - arena_vector GetExpandedCanonicalBindings(LogicalOperator &op) { - return GetCanonicalBindings(GetExpandedColumnBindings(op)); + SubplanBindings GetAvailableBindings(LogicalOperator &op) { + vector> scans; + vector> expression_sources; + const auto expanded_bindings = GetExpandedColumnBindings(op, scans, expression_sources); + const auto canonical_bindings = GetCanonicalBindings(expanded_bindings); + SubplanBindings result; + for (idx_t i = 0; i < expanded_bindings.size(); i++) { + result.bindings.emplace(canonical_bindings[i], expanded_bindings[i]); + } + for (auto &scan : scans) { + if (!CanExpandScan(scan)) { + continue; + } + const auto table_index = to_canonical_table_index.at(scan.get().table_index); + auto entry = result.scans.emplace(table_index, scan.get()); + if (!entry.second) { + // Multiple occurrences of the same scan do not identify an unambiguous column source. + entry.first->second = nullptr; + } + } + for (auto &op : expression_sources) { + auto table_index = to_canonical_table_index.find(GetExpressionOutputTableIndex(op)); + if (table_index == to_canonical_table_index.end()) { + continue; // Generated CTE reader projections expose only their existing bindings. + } + auto expressions = canonical_expressions.find(table_index->second); + if (expressions == canonical_expressions.end()) { + continue; + } + auto source = make_uniq(op, expressions->second, + GetAvailableBindings(*op.get().children[0])); + auto entry = result.expression_sources.emplace(table_index->second, std::move(source)); + if (!entry.second) { + entry.first->second.reset(); + } + } + return result; } //! Moves a subplan that can expose every binding required by the duplicate occurrences to the front @@ -1192,10 +1466,10 @@ class CommonSubplanFinder { idx_t primary_subplan_binding_count = 0; for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) { auto &subplan = subplan_info.subplans[subplan_idx]; - const auto expanded_bindings = GetExpandedCanonicalBindings(*subplan.op.get()); + const auto available_bindings = GetAvailableBindings(*subplan.op.get()); bool contains_required_bindings = true; for (auto &cb : required_bindings) { - if (std::find(expanded_bindings.begin(), expanded_bindings.end(), cb) == expanded_bindings.end()) { + if (!available_bindings.Contains(cb)) { contains_required_bindings = false; break; } @@ -1241,7 +1515,14 @@ class CommonSubplanFinder { bool ShouldMaterialize(const SubplanInfo &subplan_info) const { auto &subplan = subplan_info.subplans[0].op.get(); - return CTEInlining::EndsInAggregateOrDistinct(*subplan) || IsSelectiveMultiTablePlan(subplan); + return CTEInlining::EndsInAggregateOrDistinct(*subplan) || + (subplan->has_estimated_cardinality && + IsSelectiveMultiTablePlan(*subplan, subplan->estimated_cardinality)); + } + + static bool CanExpandScan(const LogicalGet &get) { + return get.children.empty() && !get.has_pushed_projection && !get.extra_info.sample_options && + !get.dynamic_filters; } static SubplanStats GetSubplanStats(const LogicalOperator &op) { @@ -1258,30 +1539,27 @@ class CommonSubplanFinder { return subplan_stats; } - static bool IsSelectiveMultiTablePlan(unique_ptr &op) { +public: + static bool IsSelectiveMultiTablePlan(const LogicalOperator &op, idx_t cardinality) { static constexpr idx_t CARDINALITY_THRESHOLD = 2048; static constexpr idx_t CARDINALITY_RATIO = 2; - // Must have an estimated cardinality - if (!op->has_estimated_cardinality) { - return false; - } - // Must select more than 1 base table - const auto subplan_stats = GetSubplanStats(*op); + const auto subplan_stats = GetSubplanStats(op); if (subplan_stats.base_table_count < 2) { return false; } // If it has this cardinality or less, just materialize - if (op->estimated_cardinality <= CARDINALITY_THRESHOLD) { + if (cardinality <= CARDINALITY_THRESHOLD) { return true; } // Otherwise, materialize if it is selective enough - return op->estimated_cardinality < subplan_stats.max_base_table_cardinality / CARDINALITY_RATIO; + return cardinality < subplan_stats.max_base_table_cardinality / CARDINALITY_RATIO; } +private: vector> GetSortedSubplans() { // Grab entries from map, and sort by smallest plans first vector> subplan_infos; @@ -1306,10 +1584,250 @@ class CommonSubplanFinder { unordered_map to_canonical_table_index; //! Mapping from generated CTE bindings to canonical bindings column_binding_map_t generated_binding_map; + //! Output expressions in canonical input bindings, indexed by canonical output column. + unordered_map>> canonical_expressions; //! Minimum CTE index created by this optimizer TableIndex min_cte_idx; }; +//===--------------------------------------------------------------------===// +// Filtered join inputs +//===--------------------------------------------------------------------===// +class CommonJoinFilters { + struct Candidate { + explicit Candidate(unique_ptr &op) : op(op) { + } + + reference> op; + vector>> scans; + }; + + struct CandidateGroup { + explicit CandidateGroup(Candidate &candidate) { + candidates.emplace_back(candidate); + } + + bool TryAdd(Candidate &candidate) { + auto &primary = candidates[0].get(); + if (candidate.scans.size() != primary.scans.size()) { + return false; + } + auto varying_scan = differing_scan; + for (idx_t i = 0; i < primary.scans.size(); i++) { + auto &left = primary.scans[i].get()->Cast(); + auto &right = candidate.scans[i].get()->Cast(); + if (left.GetColumnIds() != right.GetColumnIds()) { + return false; + } + if (left.table_filters.Equals(right.table_filters)) { + continue; + } + // One varying input avoids cross-combinations between independent filter disjunctions. + if (varying_scan.IsValid() && varying_scan.GetIndex() != i) { + return false; + } + varying_scan = i; + } + differing_scan = varying_scan; + candidates.emplace_back(candidate); + return true; + } + + vector> candidates; + optional_idx differing_scan; + }; + +public: + explicit CommonJoinFilters(ClientContext &context) : state(context) { + } + + void Normalize(unique_ptr &op) { + FindCandidates(op); + for (auto &entry : candidates) { + vector groups; + for (auto &candidate : entry.second) { + bool added = false; + for (auto &group : groups) { + if (group.TryAdd(candidate)) { + added = true; + break; + } + } + if (!added) { + groups.emplace_back(candidate); + } + } + for (auto &group : groups) { + NormalizeGroup(group); + } + } + } + +private: + static bool IsInnerJoin(const LogicalOperator &op) { + return op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op.Cast().join_type == JoinType::INNER; + } + + optional_ptr Signature(unique_ptr &op, Candidate &candidate, bool movable) { + const bool traverse = movable && (IsInnerJoin(*op) || op->type == LogicalOperatorType::LOGICAL_FILTER); + if (traverse) { + bool safe = true; + LogicalOperatorVisitor::EnumerateExpressions( + *op, [&](unique_ptr *expr) { safe &= CanShareSubplanExpression(**expr); }); + if (!safe) { + return nullptr; + } + } + vector> children; + for (auto &child : op->children) { + auto signature = Signature(child, candidate, traverse); + if (!signature) { + return nullptr; + } + children.emplace_back(*signature); + } + auto create = [&]() { + signatures.push_back(PlanSignature::Create(state, *op, std::move(children))); + return optional_ptr(signatures.back().get()); + }; + if (!movable || op->type != LogicalOperatorType::LOGICAL_GET) { + return create(); + } + auto &get = op->Cast(); + if (!get.children.empty() || get.table_filters.HasMultiColumnFilters() || get.dynamic_filters || + get.extra_info.sample_options || get.has_pushed_projection) { + return create(); + } + for (auto &entry : get.table_filters) { + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "CommonJoinFilters"); + if (!CanShareSubplanExpression(*filter.expr) || ExpressionFilter::IsOptionalFilter(filter)) { + return create(); + } + } + auto filters = std::move(get.table_filters); + auto signature = create(); + get.table_filters = std::move(filters); + candidate.scans.emplace_back(op); + return signature; + } + + void FindCandidates(unique_ptr &op) { + if (IsInnerJoin(*op)) { + Candidate candidate(op); + auto signature = Signature(op, candidate, true); + if (signature) { + candidates[*signature].push_back(std::move(candidate)); + } + return; + } + for (auto &child : op->children) { + FindCandidates(child); + } + } + + static unique_ptr ScanPredicate(LogicalGet &get) { + vector> expressions; + for (auto &entry : get.table_filters) { + const auto index = entry.GetIndex(); + BoundColumnRefExpression column(get.GetColumnType(get.GetColumnIds()[index]), + ColumnBinding(get.table_index, index)); + expressions.push_back(entry.Filter().ToExpression(column)); + } + if (expressions.empty()) { + return make_uniq(Value::BOOLEAN(true)); + } + return BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(expressions)); + } + + static void ExposeFilterColumns(LogicalOperator &op) { + if (IsInnerJoin(op)) { + auto &join = op.Cast(); + join.left_projection_map.clear(); + join.right_projection_map.clear(); + } else if (op.type == LogicalOperatorType::LOGICAL_FILTER) { + op.Cast().projection_map.clear(); + } else { + return; + } + for (auto &child : op.children) { + ExposeFilterColumns(*child); + } + } + + void NormalizeGroup(CandidateGroup &candidate_group) { + auto &group = candidate_group.candidates; + auto differing_scan = candidate_group.differing_scan; + if (group.size() < 2 || !differing_scan.IsValid()) { + return; + } + auto &primary = group[0].get(); + idx_t cardinality = 0; + for (Candidate &candidate : group) { + auto &op = *candidate.op.get(); + if (!op.has_estimated_cardinality || + op.estimated_cardinality > NumericLimits::Maximum() - cardinality) { + return; + } + cardinality += op.estimated_cardinality; + } + if (!CommonSubplanFinder::IsSelectiveMultiTablePlan(*primary.op.get(), cardinality)) { + return; + } + + vector> predicates; + vector table_indexes; + for (Candidate &candidate : group) { + auto &get = candidate.scans[differing_scan.GetIndex()].get()->Cast(); + predicates.push_back(ScanPredicate(get)); + table_indexes.push_back(get.table_index); + } + for (idx_t i = 0; i < group.size(); i++) { + auto &candidate = group[i].get(); + auto &op = candidate.op.get(); + const auto old_cardinality = op->estimated_cardinality; + const auto old_bindings = op->GetColumnBindings(); + auto &scan = candidate.scans[differing_scan.GetIndex()].get(); + auto &get = scan->Cast(); + vector> disjuncts; + for (idx_t j = 0; j < predicates.size(); j++) { + auto predicate = predicates[j]->Copy(); + ColumnBindingReplacer replacer; + for (auto index : ProjectionIndex::GetIndexes(get.GetColumnIds().size())) { + replacer.replacement_bindings.emplace_back(ColumnBinding(table_indexes[j], index), + ColumnBinding(get.table_index, index)); + } + replacer.VisitExpression(&predicate); + disjuncts.push_back(std::move(predicate)); + } + get.table_filters.ClearFilters(); + get.projection_ids.clear(); + auto guard = make_uniq( + BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_OR, std::move(disjuncts))); + guard->children.push_back(std::move(scan)); + scan = std::move(guard); + ExposeFilterColumns(*op); + op->SetEstimatedCardinality(cardinality); + auto new_bindings = op->GetColumnBindings(); + auto residual = make_uniq(predicates[i]->Copy()); + for (auto &binding : old_bindings) { + auto entry = std::find(new_bindings.begin(), new_bindings.end(), binding); + D_ASSERT(entry != new_bindings.end()); + residual->projection_map.emplace_back(NumericCast(entry - new_bindings.begin())); + } + residual->SetEstimatedCardinality(old_cardinality); + residual->children.push_back(std::move(op)); + op = std::move(residual); + } + } + +private: + PlanSignatureCreateState state; + //! Parent signatures and candidate keys reference these objects. + vector> signatures; + unordered_map, vector, PlanSignatureHash, PlanSignatureEquality> candidates; +}; + //===--------------------------------------------------------------------===// // CommonSubplanOptimizer //===--------------------------------------------------------------------===// @@ -1317,6 +1835,8 @@ CommonSubplanOptimizer::CommonSubplanOptimizer(Optimizer &optimizer_p) : optimiz } unique_ptr CommonSubplanOptimizer::Optimize(unique_ptr op) { + CommonJoinFilters join_filters(optimizer.context); + join_filters.Normalize(op); // Bottom-up identification of identical subplans CommonSubplanFinder finder(optimizer.context); finder.FindCommonSubplans(op); diff --git a/src/duckdb/src/optimizer/compressed_materialization/compress_comparison_join.cpp b/src/duckdb/src/optimizer/compressed_materialization/compress_comparison_join.cpp index 1572ddabf..67b09ba6d 100644 --- a/src/duckdb/src/optimizer/compressed_materialization/compress_comparison_join.cpp +++ b/src/duckdb/src/optimizer/compressed_materialization/compress_comparison_join.cpp @@ -197,8 +197,17 @@ void CompressedMaterialization::CompressComparisonJoin(unique_ptrsecond->CanHaveNull(); + const auto rhs_can_have_null = rhs_it->second->CanHaveNull(); lhs_it->second->Merge(merged_stats); rhs_it->second->Merge(merged_stats); + // the compression only depends on the merged values, a side without NULLs still has none + if (!lhs_can_have_null) { + lhs_it->second->Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); + } + if (!rhs_can_have_null) { + rhs_it->second->Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); + } probe_compress_bindings.insert(lhs_colref.Binding()); continue; } diff --git a/src/duckdb/src/optimizer/constant_or_null_simplification.cpp b/src/duckdb/src/optimizer/constant_or_null_simplification.cpp index 7fd87aed7..5581f9b72 100644 --- a/src/duckdb/src/optimizer/constant_or_null_simplification.cpp +++ b/src/duckdb/src/optimizer/constant_or_null_simplification.cpp @@ -1,10 +1,8 @@ #include "duckdb/optimizer/constant_or_null_simplification.hpp" #include "duckdb/function/scalar/generic_common.hpp" -#include "duckdb/optimizer/expression_rewriter.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" -#include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/expression_nullability.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" @@ -104,36 +102,7 @@ unique_ptr ConstantOrNullSimplification::SimplifyExpression(LogicalO return expr; } - if (expr->GetExpressionType() != ExpressionType::OPERATOR_NOT) { - return expr; - } - - // Push NOT into constant_or_null without dropping per-row NULL checks. - auto ¬_expr = expr->Cast(); - D_ASSERT(not_expr.GetChildren().size() == 1); - - auto value = GetBooleanConstant(*not_expr.GetChildren()[0]); - if (value.has_value()) { - return make_uniq(Value::BOOLEAN(!value.value())); - } - - value = GetConstantOrNullBoolean(*not_expr.GetChildren()[0]); - if (!value.has_value()) { - return expr; - } - - auto &func = not_expr.GetChildren()[0]->Cast(); - auto &func_children = func.GetChildrenMutable(); - D_ASSERT(func_children.size() >= 2); - - vector> children; - children.reserve(func_children.size()); - children.push_back(make_uniq(Value::BOOLEAN(!value.value()))); - for (idx_t child_idx = 1; child_idx < func_children.size(); ++child_idx) { - children.push_back(std::move(func_children[child_idx])); - } - - return ExpressionRewriter::ConstantOrNull(this->context, std::move(children), Value::BOOLEAN(!value.value())); + return expr; } unique_ptr ConstantOrNullSimplification::OptimizeFilter(unique_ptr op, diff --git a/src/duckdb/src/optimizer/cse_optimizer.cpp b/src/duckdb/src/optimizer/cse_optimizer.cpp index 162b27c62..387cb942f 100644 --- a/src/duckdb/src/optimizer/cse_optimizer.cpp +++ b/src/duckdb/src/optimizer/cse_optimizer.cpp @@ -1,4 +1,6 @@ #include "duckdb/optimizer/cse_optimizer.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -34,8 +36,26 @@ struct CSEReplacementState { bool short_circuited = false; //! True while visiting the child of a TRY or HAS_ERROR, whose errors must stay inside the capture bool inside_try = false; + //! Whether the root of each aggregate filter stays intact (ungrouped aggregates evaluate their filters directly) + bool keep_aggregate_filters = false; + //! True when visiting the root of a kept filter; its sub-expressions are still extracted + bool at_kept_filter_root = false; + //! The kept filters counted so far; identical filters are evaluated once, so they are counted once + expression_set_t counted_filters; }; +//! Whether child is the filter of an aggregate whose root stays with the aggregate +static bool IsKeptFilterRoot(const CSEReplacementState &state, const Expression &parent, const Expression &child) { + if (!state.keep_aggregate_filters || parent.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + return false; + } + if (parent.Cast().GetFilter().get() != &child) { + return false; + } + // the planner moves volatile filters into the projection, one per aggregate: their sub-expressions are shared + return !child.IsVolatile(); +} + void CommonSubExpressionOptimizer::VisitOperator(LogicalOperator &op) { switch (op.type) { case LogicalOperatorType::LOGICAL_PROJECTION: @@ -49,6 +69,8 @@ void CommonSubExpressionOptimizer::VisitOperator(LogicalOperator &op) { } void CommonSubExpressionOptimizer::CountExpressions(Expression &expr, CSEReplacementState &state) { + const bool kept_filter_root = state.at_kept_filter_root; + state.at_kept_filter_root = false; // we only consider expressions with children for CSE elimination switch (expr.GetExpressionClass()) { case ExpressionClass::BOUND_COLUMN_REF: @@ -60,7 +82,11 @@ void CommonSubExpressionOptimizer::CountExpressions(Expression &expr, CSEReplace default: break; } - if (expr.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE && !expr.IsVolatile() && !state.inside_try) { + if (kept_filter_root && !state.counted_filters.insert(expr).second) { + return; + } + if (expr.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE && !expr.IsVolatile() && !state.inside_try && + !kept_filter_root) { // we can't move aggregates to a projection, so we only consider the children of the aggregate auto node = state.expression_count.find(expr); if (node == state.expression_count.end()) { @@ -101,13 +127,18 @@ void CommonSubExpressionOptimizer::CountExpressions(Expression &expr, CSEReplace } default: // recursively count the children - ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { CountExpressions(child, state); }); + ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { + state.at_kept_filter_root = IsKeptFilterRoot(state, expr, child); + CountExpressions(child, state); + }); break; } } void CommonSubExpressionOptimizer::PerformCSEReplacement(unique_ptr &expr_ptr, CSEReplacementState &state) { Expression &expr = *expr_ptr; + const bool kept_filter_root = state.at_kept_filter_root; + state.at_kept_filter_root = false; if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { auto &bound_column_ref = expr.Cast(); // bound column ref, check if this one has already been recorded in the expression list @@ -126,7 +157,7 @@ void CommonSubExpressionOptimizer::PerformCSEReplacement(unique_ptr return; } // check if this child is eligible for CSE elimination - if (!state.inside_try && state.expression_count.find(expr) != state.expression_count.end()) { + if (!state.inside_try && !kept_filter_root && state.expression_count.find(expr) != state.expression_count.end()) { auto &node = state.expression_count[expr]; if (node.count > 1) { // this expression occurs more than once! push it into the projection @@ -152,8 +183,10 @@ void CommonSubExpressionOptimizer::PerformCSEReplacement(unique_ptr if (expression_type == ExpressionType::OPERATOR_TRY || expression_type == ExpressionType::OPERATOR_HAS_ERROR) { state.inside_try = true; } - ExpressionIterator::EnumerateChildren(expr, - [&](unique_ptr &child) { PerformCSEReplacement(child, state); }); + ExpressionIterator::EnumerateChildren(expr, [&](unique_ptr &child) { + state.at_kept_filter_root = IsKeptFilterRoot(state, expr, *child); + PerformCSEReplacement(child, state); + }); state.inside_try = save_inside_try; } @@ -162,6 +195,10 @@ void CommonSubExpressionOptimizer::ExtractCommonSubExpressions(LogicalOperator & // first we count for each expression with children how many types it occurs CSEReplacementState state; + if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto &aggr = op.Cast(); + state.keep_aggregate_filters = aggr.groups.empty() && aggr.grouping_sets.size() <= 1; + } LogicalOperatorVisitor::EnumerateExpressions( op, [&](unique_ptr *child) { CountExpressions(**child, state); }); // check if there are any expressions to extract diff --git a/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp b/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp new file mode 100644 index 000000000..6c24a023c --- /dev/null +++ b/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp @@ -0,0 +1,146 @@ +#include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" + +#include "duckdb/execution/operator/join/physical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" + +namespace duckdb { + +static bool ContainsRecursiveCTE(const LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + return true; + } + for (auto &child : op.children) { + if (ContainsRecursiveCTE(*child)) { + return true; + } + } + return false; +} + +void JoinFilterPushdownOptimizer::Optimize(LogicalOperator &op) { + if (!ContainsRecursiveCTE(op)) { + CollectCTEFilters(op); + } + VisitOperator(op); +} + +void JoinFilterPushdownOptimizer::CollectCTEFilters(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + CollectCTEFilters(*op.children[1]); + GenerateCTEFilters(op.Cast()); + CollectCTEFilters(*op.children[0]); + return; + } + for (auto &child : op.children) { + CollectCTEFilters(*child); + } +} + +static void CollectCTEConsumers(LogicalOperator &op, TableIndex cte_index, vector> &references, + vector> &joins) { + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + if (ref.cte_index == cte_index) { + references.push_back(ref); + } + } else if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + joins.push_back(op.Cast()); + } + for (auto &child : op.children) { + CollectCTEConsumers(*child, cte_index, references, joins); + } +} + +struct CTEFilterContribution { + LogicalComparisonJoin &join; + idx_t consumer_idx; + JoinFilterPushdownColumn column; +}; + +void JoinFilterPushdownOptimizer::GenerateCTEFilters(LogicalMaterializedCTE &cte) { + vector> references; + vector> joins; + CollectCTEConsumers(*cte.children[1], cte.table_index, references, joins); + if (references.size() < 2 || joins.empty()) { + return; + } + cte.children[0]->ResolveOperatorTypes(); + auto bindings = cte.children[0]->GetColumnBindings(); + unordered_map consumer_indexes; + for (auto &ref : references) { + auto &consumer = ref.get(); + if (consumer.is_recurring || consumer.correlated_columns != 0 || + consumer.chunk_types != cte.children[0]->types || + !consumer_indexes.emplace(consumer.table_index, consumer_indexes.size()).second) { + return; + } + } + + reference_map_t>> contributions; + for (auto &join_ref : joins) { + auto &join = join_ref.get(); + if (!CanGenerateJoinFilters(join)) { + continue; + } + PhysicalComparisonJoin::ReorderConditions(join.conditions); + vector columns; + for (idx_t i = 0; i < join.conditions.size(); i++) { + auto &condition = join.conditions[i]; + JoinFilterPushdownColumn column; + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL || + !JoinFilterPushdownUtil::PushdownJoinFilterExpression(condition.GetLHS(), column)) { + continue; + } + column.join_filter_idx = i; + columns.push_back(std::move(column)); + } + reference_map_t> targets; + GetCTEFilterTargets(*join.children[0], std::move(columns), targets); + for (auto &target : targets) { + auto &ref = target.first.get(); + auto consumer = consumer_indexes.find(ref.table_index); + if (ref.cte_index != cte.table_index || consumer == consumer_indexes.end()) { + continue; + } + for (auto &column : target.second) { + column.probe_column_index = bindings.at(column.probe_column_index.column_index.GetIndex()); + vector scans; + GetPushdownFilterTargets(*cte.children[0], {std::move(column)}, scans); + for (auto &scan : scans) { + for (auto &scan_column : scan.columns) { + auto index = scan_column.probe_column_index.column_index; + contributions[scan.get][index].push_back({join, consumer->second, std::move(scan_column)}); + } + } + } + } + } + for (auto &scan : contributions) { + auto &get = scan.first.get(); + for (auto &entry : scan.second) { + vector covered(references.size(), false); + for (auto &contribution : entry.second) { + covered[contribution.consumer_idx] = true; + } + if (std::find(covered.begin(), covered.end(), false) != covered.end()) { + continue; + } + if (!get.dynamic_filters) { + get.dynamic_filters = make_shared_ptr(); + } + auto alternatives = get.dynamic_filters->AddDisjunction(entry.first, references.size()); + for (auto &contribution : entry.second) { + JoinFilterPushdownFilter filter; + filter.dynamic_filters = alternatives[contribution.consumer_idx]; + filter.columns.push_back(std::move(contribution.column)); + filter.estimated_scan_cardinality = get.has_estimated_cardinality ? get.estimated_cardinality : 0; + cte_filters[contribution.join].push_back(std::move(filter)); + } + } + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/expression_rewriter.cpp b/src/duckdb/src/optimizer/expression_rewriter.cpp index 71b7059df..1e24c9f90 100644 --- a/src/duckdb/src/optimizer/expression_rewriter.cpp +++ b/src/duckdb/src/optimizer/expression_rewriter.cpp @@ -31,6 +31,7 @@ const vector> &ExpressionRewriter::GetRules() { rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); + rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); @@ -60,6 +61,7 @@ const vector> &ExpressionRewriter::GetRules() { rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); rules.push_back(make_uniq(*this)); + rules.push_back(make_uniq(*this)); #ifdef DEBUG for (auto &rule : rules) { diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index bc4870ba8..66317666a 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -343,6 +343,53 @@ static bool SupportedFilterComparison(ExpressionType expression_type) { } } +optional_ptr FilterCombiner::GetComparedExpression(const Expression &filter) { + const auto filter_type = filter.GetExpressionType(); + // BETWEEN and IN compare their first child with the others + const bool compares_first_child = + filter_type == ExpressionType::COMPARE_BETWEEN || filter_type == ExpressionType::COMPARE_IN; + if ((!SupportedFilterComparison(filter_type) && !compares_first_child) || filter.IsVolatile()) { + return nullptr; + } + optional_ptr compared; + bool valid = true; + idx_t child_idx = 0; + ExpressionIterator::EnumerateChildren(filter, [&](const Expression &child) { + if (!child.IsFoldable()) { + valid = valid && !compared && (!compares_first_child || child_idx == 0); + compared = &child; + } + child_idx++; + }); + return valid ? compared : nullptr; +} + +void FilterCombiner::GenerateJoinFilters(const vector &conditions, + const vector> &filters, JoinSide target_side, + const std::function filter)> &callback) { + D_ASSERT(target_side == JoinSide::LEFT || target_side == JoinSide::RIGHT); + for (auto &cond : conditions) { + // a comparison with constants is false for NULL, so NOT DISTINCT FROM acts as equality for it + if (!cond.IsComparison() || (cond.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + continue; + } + auto &source = target_side == JoinSide::LEFT ? cond.GetRHS() : cond.GetLHS(); + auto &target = target_side == JoinSide::LEFT ? cond.GetLHS() : cond.GetRHS(); + // the join evaluates both sides once per row, a generated filter must not evaluate them differently + if (source.IsVolatile() || target.IsVolatile() || target.CanThrow() || source.IsFoldable() || + target.IsFoldable()) { + continue; + } + for (auto &filter : filters) { + auto compared = GetComparedExpression(filter.get()); + if (compared && compared->Equals(source)) { + callback(ExpressionIterator::ReplaceExpression(filter.get(), source, target)); + } + } + } +} + static bool TypeSupportsConstantFilter(const LogicalType &type) { if (TypeIsNumeric(type.InternalType())) { return true; diff --git a/src/duckdb/src/optimizer/filter_pullup.cpp b/src/duckdb/src/optimizer/filter_pullup.cpp index 67c744ce5..b0970b4e8 100644 --- a/src/duckdb/src/optimizer/filter_pullup.cpp +++ b/src/duckdb/src/optimizer/filter_pullup.cpp @@ -1,12 +1,14 @@ #include "duckdb/optimizer/filter_pullup.hpp" #include "duckdb/common/enum_util.hpp" +#include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" #include "duckdb/planner/operator/logical_join.hpp" #include "duckdb/planner/operator/logical_distinct.hpp" +#include "duckdb/planner/operator/logical_window.hpp" namespace duckdb { @@ -28,6 +30,8 @@ unique_ptr FilterPullup::Rewrite(unique_ptr op return PullupSetOperation(std::move(op)); case LogicalOperatorType::LOGICAL_DISTINCT: return PullupDistinct(std::move(op)); + case LogicalOperatorType::LOGICAL_WINDOW: + return PullupWindow(std::move(op)); case LogicalOperatorType::LOGICAL_ORDER_BY: { // we can just pull directly through these operations without any rewriting op->children[0] = Rewrite(std::move(op->children[0])); @@ -52,17 +56,46 @@ unique_ptr FilterPullup::PullupJoin(unique_ptr } else { return PullupInnerJoin(std::move(op)); } + case JoinType::SEMI: + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return PullupSemiJoin(std::move(op)); + } + return PullupFromLeft(std::move(op)); case JoinType::LEFT: case JoinType::ANTI: - case JoinType::SEMI: { return PullupFromLeft(std::move(op)); - } default: // unsupported join type: call children pull up return FinishPullup(std::move(op)); } } +unique_ptr FilterPullup::PullupSemiJoin(unique_ptr op) { + auto &join = op->Cast(); + D_ASSERT(join.join_type == JoinType::SEMI); + FilterPullup left_pullup(true, can_add_column); + FilterPullup right_pullup(true, can_add_column); + op->children[0] = left_pullup.Rewrite(std::move(op->children[0])); + op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); + + auto &left_filters = left_pullup.filters_expr_pullup; + if (!right_pullup.filters_expr_pullup.empty()) { + // a left row with a match passes what the filters on the right imply for the left side + vector> right_filters; + for (auto &filter : right_pullup.filters_expr_pullup) { + right_filters.push_back(*filter); + } + FilterCombiner::GenerateJoinFilters( + join.conditions, right_filters, JoinSide::LEFT, + [&](unique_ptr left_filter) { left_filters.push_back(std::move(left_filter)); }); + op->children[1] = GeneratePullupFilter(std::move(op->children[1]), right_pullup.filters_expr_pullup); + } + if (left_filters.empty()) { + return op; + } + return GeneratePullupFilter(std::move(op), left_filters); +} + unique_ptr FilterPullup::PullupInnerJoin(unique_ptr op) { D_ASSERT(op->Cast().join_type == JoinType::INNER); if (op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN) { @@ -135,6 +168,39 @@ unique_ptr FilterPullup::PullupDistinct(unique_ptr FilterPullup::PullupWindow(unique_ptr op) { + if (!can_pullup) { + return FinishPullup(std::move(op)); + } + // above the window, the window expressions also run for the partitions the filters remove + auto &window = op->Cast(); + if (!FilterPushdown::OnlyRanksWithoutArguments(window)) { + return FinishPullup(std::move(op)); + } + const auto pulled_before_child = filters_expr_pullup.size(); + op->children[0] = Rewrite(std::move(op->children[0])); + + // a filter that compares the partitions with constants keeps or removes whole partitions + // a filter that stays below the window and can throw keeps the filters that guard it there + bool keep_all = false; + for (idx_t i = pulled_before_child; i < filters_expr_pullup.size(); i++) { + keep_all = keep_all || (filters_expr_pullup[i]->CanThrow() && + !FilterPushdown::ComparesWindowPartitions(window, *filters_expr_pullup[i])); + } + vector> kept_filters; + for (idx_t i = pulled_before_child; i < filters_expr_pullup.size(); i++) { + if (keep_all || !FilterPushdown::ComparesWindowPartitions(window, *filters_expr_pullup[i])) { + kept_filters.push_back(std::move(filters_expr_pullup[i])); + filters_expr_pullup.erase_at(i); + i--; + } + } + if (!kept_filters.empty()) { + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), kept_filters); + } + return op; +} + unique_ptr FilterPullup::GeneratePullupFilter(unique_ptr child, vector> &expressions) { unique_ptr filter = make_uniq(); diff --git a/src/duckdb/src/optimizer/in_clause_rewriter.cpp b/src/duckdb/src/optimizer/in_clause_rewriter.cpp index 9f2e7d256..a89ae9c39 100644 --- a/src/duckdb/src/optimizer/in_clause_rewriter.cpp +++ b/src/duckdb/src/optimizer/in_clause_rewriter.cpp @@ -60,6 +60,31 @@ unique_ptr InClauseRewriter::Rewrite(unique_ptr *expression) { + auto &expr = **expression; + const auto expression_type = expr.GetExpressionType(); + if (expression_type == ExpressionType::OPERATOR_TRY || expression_type == ExpressionType::OPERATOR_HAS_ERROR) { + // an IN below an error capture must stay an expression, the mark join would raise outside the capture + return; + } + // in conjunctions, CASE, and COALESCE only the first child evaluates unconditionally, the mark + // join would evaluate a guarded arm's probe for every row (the Select paths run later children + // on a remaining-row selection, so untaken arms never raise) + if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONJUNCTION || + expr.GetExpressionClass() == ExpressionClass::BOUND_CASE || + expression_type == ExpressionType::OPERATOR_COALESCE) { + bool first = true; + ExpressionIterator::EnumerateChildren(expr, [&](unique_ptr &child) { + if (first) { + VisitExpression(&child); + } + first = false; + }); + return; + } + LogicalOperatorVisitor::VisitExpression(expression); +} + unique_ptr InClauseRewriter::VisitReplace(BoundOperatorExpression &expr, unique_ptr *expr_ptr) { if (expr.GetExpressionType() != ExpressionType::COMPARE_IN && expr.GetExpressionType() != ExpressionType::COMPARE_NOT_IN) { diff --git a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp index 751ee831a..401e81099 100644 --- a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp @@ -17,6 +17,7 @@ #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" #include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -26,6 +27,14 @@ namespace duckdb { +struct FilterTarget { + FilterTarget(LogicalOperator &op, vector columns) : op(op), columns(std::move(columns)) { + } + + LogicalOperator &op; + vector columns; +}; + JoinFilterPushdownOptimizer::JoinFilterPushdownOptimizer(Optimizer &optimizer) : optimizer(optimizer) { } @@ -240,7 +249,7 @@ static void CollectJoinFilterEqualities(const LogicalComparisonJoin &join, filte } static void FindScanFilterTargets(LogicalGet &get, vector columns, - vector &targets) { + vector &targets) { if (!get.function.filter_pushdown || get.ordinality_idx.IsValid() || get.extra_info.sample_options) { return; } @@ -290,11 +299,13 @@ static bool OperatorHasVolatileExpressions(const LogicalOperator &op) { class FilterTargetContext { public: - explicit FilterTargetContext(EqualityPropagation equality_propagation) - : equality_propagation(equality_propagation) { + explicit FilterTargetContext(EqualityPropagation equality_propagation, bool cross_secure_views = false) + : equality_propagation(equality_propagation), cross_secure_views(cross_secure_views) { } EqualityPropagation equality_propagation; + bool cross_secure_views; + bool include_cte_references = false; public: const filter_equality_graph_t &GetEqualities(const LogicalOperator &op) { @@ -364,11 +375,11 @@ class FilterTargetContext { enum class FilterColumnExpansion { REQUIRED, COMPLETE }; static void FindFilterTargets(LogicalOperator &op, vector columns, - vector &targets, FilterTargetContext &context, + vector &targets, FilterTargetContext &context, FilterColumnExpansion expansion = FilterColumnExpansion::REQUIRED); static void FindSetOperationFilterTargets(LogicalSetOperation &setop, const vector &columns, - vector &targets, FilterTargetContext &context) { + vector &targets, FilterTargetContext &context) { for (auto &child : setop.children) { vector child_columns; const auto child_bindings = child->GetColumnBindings(); @@ -455,7 +466,7 @@ static vector ExpandEquivalentFilterColumns(const filt } static void FindJoinFilterTargets(LogicalOperator &op, vector columns, - vector &targets, FilterTargetContext &context, + vector &targets, FilterTargetContext &context, FilterColumnExpansion expansion) { if (OperatorHasVolatileExpressions(op)) { return; @@ -475,7 +486,7 @@ static void FindJoinFilterTargets(LogicalOperator &op, vector right_targets; + vector right_targets; FindFilterTargets(*op.children[1], std::move(columns), right_targets, context, child_expansion); // An empty build can skip the probe input, including expressions outside the filtered branch. if (!right_targets.empty() && context.CanSkipSubtree(*op.children[0])) { @@ -486,7 +497,7 @@ static void FindJoinFilterTargets(LogicalOperator &op, vector columns, - vector &targets, FilterTargetContext &context) { + vector &targets, FilterTargetContext &context) { vector partition_columns; for (auto &filter : columns) { bool shared_partition = filter.probe_column_index.table_index != window.window_index; @@ -509,7 +520,7 @@ static void FindWindowFilterTargets(LogicalWindow &window, vector columns, - vector &targets, FilterTargetContext &context, + vector &targets, FilterTargetContext &context, FilterColumnExpansion expansion) { if (columns.empty() || OperatorHasVolatileExpressions(op)) { return; @@ -518,6 +529,33 @@ static void FindFilterTargets(LogicalOperator &op, vector(), std::move(columns), targets); break; + case LogicalOperatorType::LOGICAL_CTE_REF: { + if (!context.include_cte_references) { + break; + } + auto &ref = op.Cast(); + if (ref.is_recurring || ref.correlated_columns != 0) { + break; + } + vector accepted; + for (auto &column : columns) { + if (column.probe_column_index.table_index != ref.table_index || + !column.probe_column_index.column_index.IsValid() || + column.probe_column_index.column_index.GetIndex() >= ref.chunk_types.size()) { + continue; + } + column.storage_type = ref.chunk_types[column.probe_column_index.column_index.GetIndex()]; + if (column.storage_type.id() == LogicalTypeId::VARIANT && column.runtime_filter_casts.empty() && + column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION) { + continue; + } + accepted.push_back(std::move(column)); + } + if (!accepted.empty()) { + targets.emplace_back(ref, std::move(accepted)); + } + break; + } case LogicalOperatorType::LOGICAL_PROJECTION: { vector projected_columns; PushdownProjectionColumns(op.Cast(), columns, projected_columns); @@ -575,6 +613,15 @@ static void FindFilterTargets(LogicalOperator &op, vector columns, vector &targets, - EqualityPropagation equality_propagation) { - FilterTargetContext context(equality_propagation); - FindFilterTargets(op, std::move(columns), targets, context); + EqualityPropagation equality_propagation, + bool cross_secure_views) { + FilterTargetContext context(equality_propagation, cross_secure_views); + vector result; + FindFilterTargets(op, std::move(columns), result, context); + for (auto &target : result) { + targets.emplace_back(target.op.Cast(), std::move(target.columns)); + } +} + +void JoinFilterPushdownOptimizer::GetCTEFilterTargets( + LogicalOperator &op, vector columns, + reference_map_t> &targets) { + FilterTargetContext context(EqualityPropagation::DISABLED); + context.include_cte_references = true; + vector result; + FindFilterTargets(op, std::move(columns), result, context); + for (auto &target : result) { + if (target.op.type != LogicalOperatorType::LOGICAL_CTE_REF) { + continue; + } + auto &cte_columns = targets[target.op.Cast()]; + for (auto &column : target.columns) { + cte_columns.push_back(std::move(column)); + } + } } bool JoinFilterPushdownOptimizer::IsFiltering(const unique_ptr &op) { @@ -636,16 +706,23 @@ static void SimplifyJoinFilterCastChain(ClientContext &context, JoinFilterPushdo } } -void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &join) { +bool JoinFilterPushdownOptimizer::CanGenerateJoinFilters(const LogicalComparisonJoin &join) { if (!JoinFilterPushdownUtil::JoinTypeIsSupported(join.join_type)) { - return; + return false; } - for (auto &cond : join.conditions) { - auto &expr = cond.IsComparison() ? cond.GetLHS() : cond.GetJoinExpression(); - if (expr.IsVolatile()) { - return; + for (auto &condition : join.conditions) { + auto &expression = condition.IsComparison() ? condition.GetLHS() : condition.GetJoinExpression(); + if (expression.IsVolatile()) { + return false; } } + return true; +} + +void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &join) { + if (!CanGenerateJoinFilters(join)) { + return; + } // re-order conditions here - otherwise this will happen later on and invalidate the indexes we generate PhysicalComparisonJoin::ReorderConditions(join.conditions); auto pushdown_info = make_uniq(); @@ -683,8 +760,8 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi } // recurse the query tree to find the LogicalGets in which we can push the filter info vector pushdown_filter_targets; - GetPushdownFilterTargets(*join.children[0], pushdown_columns, pushdown_filter_targets, - EqualityPropagation::ENABLED); + GetPushdownFilterTargets(*join.children[0], pushdown_columns, pushdown_filter_targets, EqualityPropagation::ENABLED, + true); for (auto &target : pushdown_filter_targets) { vector get_columns; for (auto &column : target.columns) { @@ -715,6 +792,21 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi pushdown_info->probe_info.push_back(std::move(get_filter)); } + auto cte_entry = cte_filters.find(join); + if (cte_entry != cte_filters.end()) { + for (auto &filter : cte_entry->second) { + for (auto &column : filter.columns) { + auto condition_idx = column.join_filter_idx; + auto entry = std::find(pushdown_info->join_condition.begin(), pushdown_info->join_condition.end(), + condition_idx); + D_ASSERT(entry != pushdown_info->join_condition.end()); + column.join_filter_idx = NumericCast(entry - pushdown_info->join_condition.begin()); + SimplifyJoinFilterCastChain(optimizer.GetContext(), column, ExpressionType::COMPARE_EQUAL); + } + pushdown_info->probe_info.push_back(std::move(filter)); + } + } + // 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? diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index df1ea7505..7980c815c 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -1,34 +1,14 @@ -#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" -#include "duckdb/common/enums/join_type.hpp" +#include "duckdb/optimizer/join_order/cardinality_estimator.hpp" #include "duckdb/common/limits.hpp" -#include "duckdb/common/optional_idx.hpp" -#include "duckdb/common/printer.hpp" -#include "duckdb/function/table/table_scan.hpp" -#include "duckdb/optimizer/join_order/join_node.hpp" -#include "duckdb/optimizer/join_order/query_graph_manager.hpp" -#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" -#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/optimizer/join_order/join_order_operator.hpp" +#include "duckdb/optimizer/join_order/join_predicate.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" -#include "duckdb/storage/data_table.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" -#include +#include namespace duckdb { -template <> -double CardinalityEstimator::EstimateCardinalityWithSet(JoinRelationSet &new_set); - -struct DenomInfo { -public: - DenomInfo(JoinRelationSet &numerator_relations, double denominator) - : numerator_relations(numerator_relations), denominator(denominator) { - } - -public: - JoinRelationSet &numerator_relations; - double denominator; -}; - struct DomainEstimate { public: DomainEstimate(); @@ -86,7 +66,6 @@ struct RelationsSetToStats { column_binding_set_t equivalent_relations; DomainEstimate domain_estimate; vector> predicates; - vector column_names; }; struct FilterInfoWithTotalDomains { @@ -108,26 +87,14 @@ struct FilterInfoWithTotalDomains { reference domain_estimate; }; -struct Subgraph2Denominator { +struct SelectivitySubgraph { public: - Subgraph2Denominator() : relations(nullptr), numerator_relations(nullptr), denom(1) { + SelectivitySubgraph() : relations(nullptr), selectivity(1) { } public: optional_ptr relations; - optional_ptr numerator_relations; - double denom; -}; - -struct LeftJoinDenomInfo { -public: - LeftJoinDenomInfo(JoinRelationSet &numerator_relations, double denominator) - : numerator_relations(numerator_relations), denominator(denominator) { - } - -public: - JoinRelationSet &numerator_relations; - double denominator; + CardinalityValue selectivity; }; struct CompositeJoinPairStats { @@ -157,27 +124,24 @@ struct CompositeJoinPairStats { bool has_distinct_count = false; }; -struct CardinalityHelper { -public: - CardinalityHelper() : CardinalityHelper(0, true) { - } - CardinalityHelper(double cardinality_before_filters, bool is_empty) - : cardinality_before_filters(cardinality_before_filters), is_empty(is_empty) { +struct LogicalJoinStats { + LogicalJoinStats(const JoinOrderOperator &op, JoinRelationSet &scope, CardinalityValue selectivity) + : op(op), scope(scope), selectivity(selectivity) { } -public: - // Must be a double. Otherwise we can lose significance between different join orders. - double cardinality_before_filters; - //! Structural emptiness is independent of the numerator's zero-to-one substitution. - bool is_empty; - vector table_names_joined; - vector column_names; + reference op; + reference scope; + CardinalityValue selectivity; }; struct CardinalityEstimatorState { vector relation_set_stats; - reference_map_t relation_set_2_cardinality; - vector> or_filters; + vector leaf_cardinalities; + vector> operators; + vector boundaries; + reference_map_t inner_selectivities; + reference_map_t cardinalities; + vector> residual_filters; }; CardinalityEstimator::CardinalityEstimator(JoinRelationSetManager &set_manager, @@ -266,22 +230,23 @@ bool CardinalityEstimator::SingleColumnFilter(const FilterInfo &filter_info) { return true; } -static bool IsJoinOrFilter(const FilterInfo &filter) { - if (filter.join_type == JoinType::SEMI || filter.join_type == JoinType::ANTI) { +static bool IsResidualFilter(const FilterInfo &filter) { + if (filter.join_type != JoinType::INNER || + (filter.set.get().count < 2 && !filter.source_operator_index.IsValid())) { return false; } - return filter.filter && filter.filter->GetExpressionClass() == ExpressionClass::BOUND_CONJUNCTION && - filter.filter->GetExpressionType() == ExpressionType::CONJUNCTION_OR && filter.set.get().count >= 2; + return filter.must_remain_filter || filter.from_residual_predicate || + (filter.filter && filter.filter->GetExpressionType() == ExpressionType::CONJUNCTION_OR); } void CardinalityEstimator::InitEquivalentRelations() { state->relation_set_stats.clear(); - state->or_filters.clear(); + state->residual_filters.clear(); for (auto predicate_ref : predicate_model.GetPredicates()) { auto &filter = predicate_ref.get().GetFilter(); - if (IsJoinOrFilter(filter)) { - state->or_filters.push_back(filter); + if (IsResidualFilter(filter)) { + state->residual_filters.push_back(filter); continue; } if (SingleColumnFilter(filter)) { @@ -317,73 +282,29 @@ void CardinalityEstimator::InitEquivalentRelations() { state->relation_set_stats.emplace_back(domain_group); state->relation_set_stats.back().predicates.push_back(predicate); } - RemoveEmptyTotalDomains(); -} - -void CardinalityEstimator::RemoveEmptyTotalDomains() { - auto remove_start = - std::remove_if(state->relation_set_stats.begin(), state->relation_set_stats.end(), - [](RelationsSetToStats &r_2_tdom) { return r_2_tdom.equivalent_relations.empty(); }); - state->relation_set_stats.erase(remove_start, state->relation_set_stats.end()); } -double CardinalityEstimator::GetNumerator(JoinRelationSet &set) { - double numerator = 1; +CardinalityValue CardinalityEstimator::GetNumerator(JoinRelationSet &set) { + CardinalityValue numerator; for (idx_t i = 0; i < set.count; i++) { - auto &single_node_set = set_manager.GetJoinRelation(set.relations[i]); - auto entry = state->relation_set_2_cardinality.find(single_node_set); - D_ASSERT(entry != state->relation_set_2_cardinality.end()); - if (entry == state->relation_set_2_cardinality.end()) { - continue; - } - auto cardinality = entry->second.cardinality_before_filters; - numerator *= cardinality == 0 ? 1 : cardinality; + auto cardinality = state->leaf_cardinalities.at(set.relations[i].index); + // Logical output handles exact zero separately from the selectivity model. + numerator *= cardinality.IsZero() ? CardinalityValue(1) : cardinality; } return numerator; } -double CardinalityEstimator::GetSubgraphCardinality(const Subgraph2Denominator &subgraph) { - D_ASSERT(subgraph.numerator_relations); - if (subgraph.denom >= NumericLimits::Maximum()) { - return 0; - } - double numerator = 1; - for (idx_t relation_idx = 0; relation_idx < subgraph.numerator_relations->count; relation_idx++) { - auto &relation = set_manager.GetJoinRelation(subgraph.numerator_relations->relations[relation_idx]); - auto entry = state->relation_set_2_cardinality.find(relation); - D_ASSERT(entry != state->relation_set_2_cardinality.end()); - if (entry == state->relation_set_2_cardinality.end()) { - continue; - } - numerator *= entry->second.cardinality_before_filters; +bool CardinalityEstimator::IsFilterApplicable(const FilterInfo &filter, JoinRelationSet &set) const { + if (!filter.set.get().Empty() && !JoinRelationSet::IsSubset(set, filter.set)) { + return false; } - return numerator / (subgraph.denom <= 0 ? 1 : subgraph.denom); -} - -optional CardinalityEstimator::EstimateTopLevelSemiAnti(JoinRelationSet &set) { - for (auto predicate_ref : predicate_model.GetPredicates()) { - auto &predicate = predicate_ref.get(); - if (predicate.GetJoinType() != JoinType::SEMI && predicate.GetJoinType() != JoinType::ANTI) { - continue; - } - auto semantic_left = predicate.GetSemanticLeftSetOptional(); - auto semantic_right = predicate.GetSemanticRightSetOptional(); - if (!semantic_left || !semantic_right) { - continue; - } - auto &operator_set = set_manager.Union(*semantic_left, *semantic_right); - if (!RefersToSameObject(operator_set, set)) { - continue; + if (filter.source_operator_index.IsValid()) { + auto &op = state->operators.at(filter.source_operator_index.GetIndex()).get(); + if (JoinOrderConflictDetector::MustApplyAsOperator(op)) { + return JoinOrderConflictDetector::IsCompletedBy(op, set); } - D_ASSERT(semantic_left->count < set.count && semantic_right->count < set.count); - auto &preserved = GetCardinalityBeforeFilters(*semantic_left); - auto preserved_cardinality = preserved.is_empty ? 0 : preserved.cardinality_before_filters; - auto rhs_cardinality = GetCardinalityBeforeFilters(*semantic_right).is_empty ? 0 : 1; - return RelationStatisticsHelper::EstimateSemiAntiJoinFallback(preserved_cardinality, rhs_cardinality, - predicate.GetJoinType()) - .cardinality; - } - return {}; + } + return true; } vector GetEdges(vector &relations_to_tdom, @@ -393,6 +314,9 @@ vector GetEdges(vector &relatio 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); @@ -404,14 +328,6 @@ vector GetEdges(vector &relatio static optional_ptr GetEdgeEndpoint(FilterInfoWithTotalDomains &edge, JoinRelationSetManager &set_manager, bool left) { - auto join_type = edge.GetPredicate().GetJoinType(); - if (join_type == JoinType::SEMI || join_type == JoinType::ANTI) { - auto semantic_set = - left ? edge.GetPredicate().GetSemanticLeftSetOptional() : edge.GetPredicate().GetSemanticRightSetOptional(); - if (semantic_set) { - return semantic_set; - } - } auto &filter = edge.GetFilter(); if (filter.filter && BoundComparisonExpression::IsComparison(*filter.filter)) { auto &binding = edge.GetPredicate().GetStatsBinding(left); @@ -422,7 +338,7 @@ static optional_ptr GetEdgeEndpoint(FilterInfoWithTotalDomains return left ? edge.GetPredicate().GetLeftSetOptional() : edge.GetPredicate().GetRightSetOptional(); } -bool EdgeConnects(FilterInfoWithTotalDomains &edge, Subgraph2Denominator &subgraph, +bool EdgeConnects(FilterInfoWithTotalDomains &edge, SelectivitySubgraph &subgraph, JoinRelationSetManager &set_manager) { auto left_endpoint = GetEdgeEndpoint(edge, set_manager, true); if (left_endpoint && JoinRelationSet::IsSubset(*subgraph.relations, *left_endpoint)) { @@ -435,7 +351,7 @@ bool EdgeConnects(FilterInfoWithTotalDomains &edge, Subgraph2Denominator &subgra return false; } -vector SubgraphsConnectedByEdge(FilterInfoWithTotalDomains &edge, vector &subgraphs, +vector SubgraphsConnectedByEdge(FilterInfoWithTotalDomains &edge, vector &subgraphs, JoinRelationSetManager &set_manager) { vector res; if (subgraphs.empty()) { @@ -466,134 +382,41 @@ vector SubgraphsConnectedByEdge(FilterInfoWithTotalDomains &edge, vector< return res; } -JoinRelationSet &CardinalityEstimator::UpdateNumeratorRelations(Subgraph2Denominator left, Subgraph2Denominator right, - FilterInfoWithTotalDomains &filter) { - auto &predicate = filter.GetPredicate(); - switch (predicate.GetJoinType()) { - case JoinType::LEFT: { - return CalculateLeftJoinDenomInfo(left, right, filter).numerator_relations; - } - case JoinType::SEMI: - case JoinType::ANTI: { - if (JoinRelationSet::IsSubset(*left.relations, predicate.GetLeftSet()) && - JoinRelationSet::IsSubset(*right.relations, predicate.GetRightSet())) { - return *left.numerator_relations; - } - return *right.numerator_relations; - } - default: - // cross product or inner join - return set_manager.Union(*left.numerator_relations, *right.numerator_relations); - } -} - -// Apply the denominator multiplier for a given comparison type and effective distinct count. -static double ApplyComparisonRatio(double base_denom, ExpressionType comparison_type, double effective_d) { +// Apply the selectivity multiplier for a given comparison type and effective distinct count. +static CardinalityValue ApplyComparisonRatio(CardinalityValue base_selectivity, ExpressionType comparison_type, + double effective_d) { switch (comparison_type) { case ExpressionType::COMPARE_EQUAL: case ExpressionType::COMPARE_NOT_DISTINCT_FROM: - return base_denom * effective_d; + return base_selectivity / CardinalityValue(effective_d); case ExpressionType::COMPARE_NOTEQUAL: case ExpressionType::COMPARE_DISTINCT_FROM: - return effective_d > 1 ? base_denom * (effective_d / (effective_d - 1)) : base_denom; - case ExpressionType::COMPARE_LESSTHANOREQUALTO: + return effective_d > 1 ? base_selectivity * CardinalityValue(effective_d - 1) / CardinalityValue(effective_d) + : base_selectivity; case ExpressionType::COMPARE_LESSTHAN: - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: case ExpressionType::COMPARE_GREATERTHAN: - // Assume this blows up, but use the tdom to bound it a bit. - return base_denom * pow(effective_d, 2.0 / 3.0); + // Model strict comparisons as half the cross product, including at small domains. + return base_selectivity / CardinalityValue(2); + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + return base_selectivity * CardinalityValue(effective_d + 1) / CardinalityValue(2 * effective_d); default: - return base_denom; + return base_selectivity; } } -static double GetEffectiveDenom(double denom) { - return denom <= 0 ? 1 : denom; +static double GetEffectiveDistinctCount(double distinct_count) { + return distinct_count <= 0 ? 1 : distinct_count; } -double CardinalityEstimator::CalculateInnerJoinDenom(double base_denom, FilterInfoWithTotalDomains &filter) { - auto effective_d = GetEffectiveDenom(filter.GetDistinctCount()); +CardinalityValue CardinalityEstimator::CalculateInnerJoinSelectivity(CardinalityValue base_selectivity, + FilterInfoWithTotalDomains &filter) { + auto effective_d = GetEffectiveDistinctCount(filter.GetDistinctCount()); auto comparison_type = filter.GetComparisonType(); if (comparison_type == ExpressionType::INVALID) { - return base_denom * effective_d; - } - return ApplyComparisonRatio(base_denom, comparison_type, effective_d); -} - -LeftJoinDenomInfo CardinalityEstimator::CalculateLeftJoinDenomInfo(Subgraph2Denominator &left, - Subgraph2Denominator &right, - FilterInfoWithTotalDomains &filter) { - auto &predicate = filter.GetPredicate(); - D_ASSERT(left.relations && right.relations); - D_ASSERT(left.numerator_relations && right.numerator_relations); - auto left_is_preserved = JoinRelationSet::IsSubset(*left.relations, predicate.GetLeftSet()) && - JoinRelationSet::IsSubset(*right.relations, predicate.GetRightSet()); - auto &preserved_numerator = left_is_preserved ? *left.numerator_relations : *right.numerator_relations; - auto preserved_denom = GetEffectiveDenom(left_is_preserved ? left.denom : right.denom); - - auto &inner_numerator = set_manager.Union(*left.numerator_relations, *right.numerator_relations); - auto inner_denom = CalculateInnerJoinDenom(GetEffectiveDenom(left.denom) * GetEffectiveDenom(right.denom), filter); - auto composite_pair = predicate.GetCompositeJoinPair(); - if (composite_pair) { - auto cap = GetJoinPairCap(*composite_pair); - CompositeJoinPairStats stats; - stats.RegisterDistinctCount(filter.GetDistinctCount()); - if (stats.CanApplyCap(cap) && filter.GetDistinctCount() > 0 && cap > filter.GetDistinctCount()) { - inner_denom = inner_denom / filter.GetDistinctCount() * cap; - } - } - if (inner_denom <= 0) { - return LeftJoinDenomInfo(preserved_numerator, preserved_denom); - } - auto inner_cardinality = GetNumerator(inner_numerator) / inner_denom; - auto preserved_cardinality = GetNumerator(preserved_numerator) / preserved_denom; - if (inner_cardinality > preserved_cardinality) { - return LeftJoinDenomInfo(inner_numerator, inner_denom); - } - return LeftJoinDenomInfo(preserved_numerator, preserved_denom); -} - -double CardinalityEstimator::CalculateLeftJoinDenom(Subgraph2Denominator &left, Subgraph2Denominator &right, - FilterInfoWithTotalDomains &filter) { - return CalculateLeftJoinDenomInfo(left, right, filter).denominator; -} - -double CardinalityEstimator::CalculateSemiAntiJoinDenom(Subgraph2Denominator &left, Subgraph2Denominator &right, - FilterInfoWithTotalDomains &filter) { - auto &predicate = filter.GetPredicate(); - auto left_is_preserved = JoinRelationSet::IsSubset(*left.relations, predicate.GetLeftSet()) && - JoinRelationSet::IsSubset(*right.relations, predicate.GetRightSet()); - auto &preserved = left_is_preserved ? left : right; - auto &rhs = left_is_preserved ? right : left; - auto preserved_cardinality = GetSubgraphCardinality(preserved); - auto semantic_rhs = predicate.GetSemanticRightSetOptional(); - auto rhs_is_empty = - semantic_rhs ? GetCardinalityBeforeFilters(*semantic_rhs).is_empty : GetSubgraphCardinality(rhs) <= 0; - auto rhs_cardinality = rhs_is_empty ? 0 : 1; - auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinFallback(preserved_cardinality, rhs_cardinality, - predicate.GetJoinType()); - if (estimate.cardinality <= 0) { - return NumericLimits::Maximum(); - } - return preserved.denom * preserved_cardinality / estimate.cardinality; -} - -// Given two subgraphs, compute the updated denominator for the join between them. -double CardinalityEstimator::CalculateUpdatedDenom(Subgraph2Denominator left, Subgraph2Denominator right, - FilterInfoWithTotalDomains &filter) { - double base_denom = GetEffectiveDenom(left.denom) * GetEffectiveDenom(right.denom); - switch (filter.GetPredicate().GetJoinType()) { - case JoinType::LEFT: - return CalculateLeftJoinDenom(left, right, filter); - case JoinType::INNER: - return CalculateInnerJoinDenom(base_denom, filter); - case JoinType::SEMI: - case JoinType::ANTI: - return CalculateSemiAntiJoinDenom(left, right, filter); - default: - // Cross product: no join condition reduces the denominator. - return base_denom; + return base_selectivity / CardinalityValue(effective_d); } + return ApplyComparisonRatio(base_selectivity, comparison_type, effective_d); } static bool GetEqualityEdgeRelations(FilterInfoWithTotalDomains &edge, RelationIndex &left, RelationIndex &right) { @@ -627,7 +450,7 @@ double CardinalityEstimator::GetJoinPairCap(JoinRelationSet &join_pair) { double cap = NumericLimits::Maximum(); for (idx_t relation_index = 0; relation_index < join_pair.count; relation_index++) { auto &single_relation = set_manager.GetJoinRelation(join_pair.relations[relation_index]); - auto cardinality = GetNumerator(single_relation); + auto cardinality = GetNumerator(single_relation).GetDouble(); if (cardinality <= 0) { return 0; } @@ -636,7 +459,7 @@ double CardinalityEstimator::GetJoinPairCap(JoinRelationSet &join_pair) { return cap == NumericLimits::Maximum() ? 0 : cap; } -bool CardinalityEstimator::ApplyJoinPairCap(double &target_denom, JoinRelationSet &join_pair, +bool CardinalityEstimator::ApplyJoinPairCap(CardinalityValue &target_selectivity, JoinRelationSet &join_pair, reference_map_t &join_pair_stats, reference_set_t &capped_join_pairs) { if (capped_join_pairs.find(join_pair) != capped_join_pairs.end()) { @@ -658,15 +481,15 @@ bool CardinalityEstimator::ApplyJoinPairCap(double &target_denom, JoinRelationSe return false; } if (cap > 0 && first_d < cap && first_d > 0) { - // Raise weak same-pair composite evidence to the FK/PK denominator floor. - target_denom = target_denom / first_d * cap; + // Lower weak same-pair composite evidence to the FK/PK cap. + target_selectivity = target_selectivity * CardinalityValue(first_d) / CardinalityValue(cap); first_d = cap; } capped_join_pairs.insert(join_pair); return true; } -bool CardinalityEstimator::ApplyJoinIncrement(double &target_denom, FilterInfoWithTotalDomains &edge, +bool CardinalityEstimator::ApplyJoinIncrement(CardinalityValue &target_selectivity, FilterInfoWithTotalDomains &edge, reference_map_t &join_pair_stats, reference_set_t &capped_join_pairs, JoinRelationSet &scope, optional_ptr join_pair) { @@ -686,20 +509,14 @@ bool CardinalityEstimator::ApplyJoinIncrement(double &target_denom, FilterInfoWi // The composite-key cap already accounts for same-pair equality predicates. return true; } - return ApplyJoinPairCap(target_denom, *target_pair, join_pair_stats, capped_join_pairs); - } - - if (edge.GetPredicate().GetJoinType() == JoinType::LEFT) { - // LEFT joins preserve the LHS cardinality in this estimator. Additional LEFT conditions - // should not reduce the output or add unused-edge penalties. - return true; + return ApplyJoinPairCap(target_selectivity, *target_pair, join_pair_stats, capped_join_pairs); } return false; } bool CardinalityEstimator::ApplyCompositeJoinPairCaps( - double &target_denom, JoinRelationSet &scope, + CardinalityValue &target_selectivity, JoinRelationSet &scope, reference_map_t &join_pair_stats, reference_set_t &capped_join_pairs) { bool applied = false; @@ -714,15 +531,13 @@ bool CardinalityEstimator::ApplyCompositeJoinPairCaps( if (!predicate_model.HasDirectCompositeEquality(join_pair)) { continue; } - applied = ApplyJoinPairCap(target_denom, join_pair, join_pair_stats, capped_join_pairs) || applied; + applied = ApplyJoinPairCap(target_selectivity, join_pair, join_pair_stats, capped_join_pairs) || applied; } return applied; } -enum class DenominatorEdgeKind : uint8_t { +enum class SelectivityEdgeKind : uint8_t { INNER_EQUIVALENCE, - LEFT_JOIN, - SEMI_ANTI_JOIN, NON_EQUALITY_SELECTIVITY, REDUNDANT_TRANSITIVE_EQUALITY, OTHER @@ -733,27 +548,23 @@ static bool EquivalenceGroupApplied(FilterInfoWithTotalDomains &edge, const unor return equality_class_index.IsValid() && applied_groups.count(equality_class_index.GetIndex()) > 0; } -static DenominatorEdgeKind ClassifyDenominatorEdge(FilterInfoWithTotalDomains &edge, +static SelectivityEdgeKind ClassifySelectivityEdge(FilterInfoWithTotalDomains &edge, const unordered_set &applied_groups) { if (EquivalenceGroupApplied(edge, applied_groups)) { - return DenominatorEdgeKind::REDUNDANT_TRANSITIVE_EQUALITY; + return SelectivityEdgeKind::REDUNDANT_TRANSITIVE_EQUALITY; } switch (edge.GetPredicate().GetPredicateClass()) { case JoinPredicateClass::INNER_EQUALITY: - return DenominatorEdgeKind::INNER_EQUIVALENCE; + return SelectivityEdgeKind::INNER_EQUIVALENCE; case JoinPredicateClass::INNER_NON_EQUALITY: - return DenominatorEdgeKind::NON_EQUALITY_SELECTIVITY; - case JoinPredicateClass::LEFT_JOIN: - return DenominatorEdgeKind::LEFT_JOIN; - case JoinPredicateClass::SEMI_ANTI_JOIN: - return DenominatorEdgeKind::SEMI_ANTI_JOIN; + return SelectivityEdgeKind::NON_EQUALITY_SELECTIVITY; default: - return DenominatorEdgeKind::OTHER; + return SelectivityEdgeKind::OTHER; } } -static bool CanIncrementExistingJoin(DenominatorEdgeKind kind) { - return kind == DenominatorEdgeKind::INNER_EQUIVALENCE || kind == DenominatorEdgeKind::LEFT_JOIN; +static bool CanIncrementExistingJoin(SelectivityEdgeKind kind) { + return kind == SelectivityEdgeKind::INNER_EQUIVALENCE; } static void RegisterEqualityJoinPair(FilterInfoWithTotalDomains &edge, JoinRelationSetManager &set_manager, @@ -768,42 +579,31 @@ static void RegisterEqualityJoinPair(FilterInfoWithTotalDomains &edge, JoinRelat join_pair_stats[*join_pair].RegisterDistinctCount(edge.GetDistinctCount()); } -struct DenominatorState { - vector subgraphs; +struct SelectivityState { + vector subgraphs; unordered_set applied_equivalence_groups; reference_map_t join_pair_stats; reference_set_t capped_join_pairs; unordered_set unused_edge_tdoms; - unordered_set applied_semi_anti_operators; - unordered_set applied_semi_anti_predicates; }; -static bool DenominatorSubgraphComplete(DenominatorState &state, JoinRelationSet &set) { +static bool SelectivitySubgraphComplete(SelectivityState &state, JoinRelationSet &set) { return state.subgraphs.size() == 1 && state.subgraphs.at(0).relations && RefersToSameObject(*state.subgraphs.at(0).relations, set); } -void CardinalityEstimator::ProcessDenominatorEdge(FilterInfoWithTotalDomains &edge, JoinRelationSet &requested_set, - DenominatorState &state) { - auto edge_kind = ClassifyDenominatorEdge(edge, state.applied_equivalence_groups); - if (edge_kind == DenominatorEdgeKind::SEMI_ANTI_JOIN) { - auto source_index = edge.GetFilter().source_operator_index; - // Predicates without an operator descriptor have a separate identity namespace. - auto &applied = source_index.IsValid() ? state.applied_semi_anti_operators : state.applied_semi_anti_predicates; - auto identity = source_index.IsValid() ? source_index.GetIndex() : edge.GetPredicate().GetIndex(); - if (!applied.insert(identity).second) { - return; - } - } - if (DenominatorSubgraphComplete(state, requested_set)) { +void CardinalityEstimator::ProcessSelectivityEdge(FilterInfoWithTotalDomains &edge, JoinRelationSet &requested_set, + SelectivityState &state) { + auto edge_kind = ClassifySelectivityEdge(edge, state.applied_equivalence_groups); + if (SelectivitySubgraphComplete(state, requested_set)) { auto &complete_subgraph = state.subgraphs.at(0); - ApplyCompositeJoinPairCaps(complete_subgraph.denom, *complete_subgraph.relations, state.join_pair_stats, + ApplyCompositeJoinPairCaps(complete_subgraph.selectivity, *complete_subgraph.relations, state.join_pair_stats, state.capped_join_pairs); - if (edge_kind == DenominatorEdgeKind::REDUNDANT_TRANSITIVE_EQUALITY) { + if (edge_kind == SelectivityEdgeKind::REDUNDANT_TRANSITIVE_EQUALITY) { return; } if (CanIncrementExistingJoin(edge_kind) && - ApplyJoinIncrement(complete_subgraph.denom, edge, state.join_pair_stats, state.capped_join_pairs, + ApplyJoinIncrement(complete_subgraph.selectivity, edge, state.join_pair_stats, state.capped_join_pairs, *complete_subgraph.relations)) { return; } @@ -827,86 +627,74 @@ void CardinalityEstimator::ProcessDenominatorEdge(FilterInfoWithTotalDomains &ed auto subgraph_connections = SubgraphsConnectedByEdge(edge, state.subgraphs, set_manager); if (subgraph_connections.empty()) { - CreateDenominatorSubgraph(edge, *edge_left_set, *edge_right_set, state); + CreateSelectivitySubgraph(edge, *edge_left_set, *edge_right_set, state); } else if (subgraph_connections.size() == 1) { - ExtendDenominatorSubgraph(subgraph_connections.at(0), edge, *edge_left_set, *edge_right_set, + ExtendSelectivitySubgraph(subgraph_connections.at(0), edge, *edge_left_set, *edge_right_set, CanIncrementExistingJoin(edge_kind), state); } else if (subgraph_connections.size() == 2) { - MergeDenominatorSubgraphs(subgraph_connections, edge, state); + MergeSelectivitySubgraphs(subgraph_connections, edge, state); } } -void CardinalityEstimator::CreateDenominatorSubgraph(FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, - JoinRelationSet &edge_right_set, DenominatorState &state) { - auto left_subgraph = Subgraph2Denominator(); - auto right_subgraph = Subgraph2Denominator(); - left_subgraph.relations = &edge_left_set; - left_subgraph.numerator_relations = &edge_left_set; - right_subgraph.relations = &edge_right_set; - right_subgraph.numerator_relations = &edge_right_set; - auto &numerator_relations = UpdateNumeratorRelations(left_subgraph, right_subgraph, edge); - auto denom = CalculateUpdatedDenom(left_subgraph, right_subgraph, edge); - left_subgraph.numerator_relations = &numerator_relations; +void CardinalityEstimator::CreateSelectivitySubgraph(FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, + JoinRelationSet &edge_right_set, SelectivityState &state) { + auto left_subgraph = SelectivitySubgraph(); + auto selectivity = CalculateInnerJoinSelectivity(CardinalityValue(1), edge); left_subgraph.relations = &set_manager.Union(edge_left_set, edge_right_set); - left_subgraph.denom = denom; - ApplyCompositeJoinPairCaps(left_subgraph.denom, *left_subgraph.relations, state.join_pair_stats, + left_subgraph.selectivity = selectivity; + ApplyCompositeJoinPairCaps(left_subgraph.selectivity, *left_subgraph.relations, state.join_pair_stats, state.capped_join_pairs); state.subgraphs.push_back(left_subgraph); } -void CardinalityEstimator::ExtendDenominatorSubgraph(idx_t subgraph_index, FilterInfoWithTotalDomains &edge, +void CardinalityEstimator::ExtendSelectivitySubgraph(idx_t subgraph_index, FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, JoinRelationSet &edge_right_set, - bool can_increment_existing_join, DenominatorState &state) { + bool can_increment_existing_join, SelectivityState &state) { auto left_subgraph = &state.subgraphs.at(subgraph_index); - auto right_subgraph = Subgraph2Denominator(); + auto right_subgraph = SelectivitySubgraph(); right_subgraph.relations = &edge_right_set; - right_subgraph.numerator_relations = &edge_right_set; if (JoinRelationSet::IsSubset(*left_subgraph->relations, *right_subgraph.relations)) { right_subgraph.relations = &edge_left_set; - right_subgraph.numerator_relations = &edge_left_set; } if (JoinRelationSet::IsSubset(*left_subgraph->relations, edge_left_set) && JoinRelationSet::IsSubset(*left_subgraph->relations, edge_right_set)) { if (can_increment_existing_join) { - ApplyJoinIncrement(left_subgraph->denom, edge, state.join_pair_stats, state.capped_join_pairs, + ApplyJoinIncrement(left_subgraph->selectivity, edge, state.join_pair_stats, state.capped_join_pairs, *left_subgraph->relations); } - ApplyCompositeJoinPairCaps(left_subgraph->denom, *left_subgraph->relations, state.join_pair_stats, + ApplyCompositeJoinPairCaps(left_subgraph->selectivity, *left_subgraph->relations, state.join_pair_stats, state.capped_join_pairs); return; } - auto &numerator_relations = UpdateNumeratorRelations(*left_subgraph, right_subgraph, edge); - auto denom = CalculateUpdatedDenom(*left_subgraph, right_subgraph, edge); - left_subgraph->numerator_relations = &numerator_relations; + auto selectivity = CalculateInnerJoinSelectivity(left_subgraph->selectivity, edge); left_subgraph->relations = &set_manager.Union(*left_subgraph->relations, *right_subgraph.relations); - left_subgraph->denom = denom; - ApplyCompositeJoinPairCaps(left_subgraph->denom, *left_subgraph->relations, state.join_pair_stats, + left_subgraph->selectivity = selectivity; + ApplyCompositeJoinPairCaps(left_subgraph->selectivity, *left_subgraph->relations, state.join_pair_stats, state.capped_join_pairs); } -void CardinalityEstimator::MergeDenominatorSubgraphs(const vector &subgraph_connections, - FilterInfoWithTotalDomains &edge, DenominatorState &state) { +void CardinalityEstimator::MergeSelectivitySubgraphs(const vector &subgraph_connections, + FilterInfoWithTotalDomains &edge, SelectivityState &state) { D_ASSERT(subgraph_connections.size() == 2); D_ASSERT(subgraph_connections.at(0) < subgraph_connections.at(1)); auto subgraph_to_merge_into = &state.subgraphs.at(subgraph_connections.at(0)); auto subgraph_to_delete = &state.subgraphs.at(subgraph_connections.at(1)); - auto &numerator_relations = UpdateNumeratorRelations(*subgraph_to_merge_into, *subgraph_to_delete, edge); - auto denom = CalculateUpdatedDenom(*subgraph_to_merge_into, *subgraph_to_delete, edge); + auto selectivity = + CalculateInnerJoinSelectivity(subgraph_to_merge_into->selectivity * subgraph_to_delete->selectivity, edge); subgraph_to_merge_into->relations = &set_manager.Union(*subgraph_to_merge_into->relations, *subgraph_to_delete->relations); - subgraph_to_merge_into->numerator_relations = &numerator_relations; - subgraph_to_merge_into->denom = denom; - ApplyCompositeJoinPairCaps(subgraph_to_merge_into->denom, *subgraph_to_merge_into->relations, state.join_pair_stats, - state.capped_join_pairs); + subgraph_to_merge_into->selectivity = selectivity; + ApplyCompositeJoinPairCaps(subgraph_to_merge_into->selectivity, *subgraph_to_merge_into->relations, + state.join_pair_stats, state.capped_join_pairs); subgraph_to_delete->relations = nullptr; auto remove_start = std::remove_if(state.subgraphs.begin(), state.subgraphs.end(), - [](Subgraph2Denominator &s) { return !s.relations; }); + [](SelectivitySubgraph &s) { return !s.relations; }); state.subgraphs.erase(remove_start, state.subgraphs.end()); } -void CardinalityEstimator::MergeDisconnectedDenominatorSubgraphs(DenominatorState &state) { +void CardinalityEstimator::MergeDisconnectedSelectivitySubgraphs(SelectivityState &state) { if (state.subgraphs.size() <= 1) { return; } @@ -914,129 +702,224 @@ void CardinalityEstimator::MergeDisconnectedDenominatorSubgraphs(DenominatorStat for (auto merge_with = state.subgraphs.begin() + 1; merge_with != state.subgraphs.end(); merge_with++) { D_ASSERT(final_subgraph.relations && merge_with->relations); final_subgraph.relations = &set_manager.Union(*final_subgraph.relations, *merge_with->relations); - D_ASSERT(final_subgraph.numerator_relations && merge_with->numerator_relations); - final_subgraph.numerator_relations = - &set_manager.Union(*final_subgraph.numerator_relations, *merge_with->numerator_relations); - final_subgraph.denom *= merge_with->denom; + final_subgraph.selectivity *= merge_with->selectivity; } state.subgraphs.clear(); state.subgraphs.push_back(final_subgraph); } -void CardinalityEstimator::AddCrossProductRelations(JoinRelationSet &set, DenominatorState &state) { - if (state.subgraphs.empty()) { - return; - } - auto &returning_subgraph = state.subgraphs.at(0); - if (returning_subgraph.relations->count == set.count) { - return; - } - for (idx_t rel_index = 0; rel_index < set.count; rel_index++) { - auto relation_id = set.relations[rel_index]; - auto &rel = set_manager.GetJoinRelation(relation_id); - if (!JoinRelationSet::IsSubset(*returning_subgraph.relations, rel)) { - returning_subgraph.numerator_relations = &set_manager.Union(*returning_subgraph.numerator_relations, rel); - returning_subgraph.relations = &set_manager.Union(*returning_subgraph.relations, rel); +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())) { + ProcessSelectivityEdge(edge, set, selectivity_state); } } + MergeDisconnectedSelectivitySubgraphs(selectivity_state); + auto result = + selectivity_state.subgraphs.empty() ? CardinalityValue(1) : selectivity_state.subgraphs[0].selectivity; + return result / CardinalityValue(1.0 + static_cast(selectivity_state.unused_edge_tdoms.size())); } -DenomInfo CardinalityEstimator::CreateDenominatorResult(JoinRelationSet &set, DenominatorState &state) { - auto denom_multiplier = 1.0 + static_cast(state.unused_edge_tdoms.size()); - MergeDisconnectedDenominatorSubgraphs(state); - AddCrossProductRelations(set, state); - - if (state.subgraphs.empty() || state.subgraphs.at(0).denom == 0) { - return DenomInfo(set, 1); +CardinalityValue CardinalityEstimator::GetInnerSelectivity(JoinRelationSet &set) { + auto entry = state->inner_selectivities.find(set); + if (entry != state->inner_selectivities.end()) { + return entry->second; } - return DenomInfo(*state.subgraphs.at(0).numerator_relations, state.subgraphs.at(0).denom * denom_multiplier); -} - -DenomInfo CardinalityEstimator::GetDenominator(JoinRelationSet &set) { - DenominatorState state; - auto edges = GetEdges(this->state->relation_set_stats, set); - for (auto &edge : edges) { - ProcessDenominatorEdge(edge, set, state); + auto result = GetSelectivity(set); + for (auto &filter : state->residual_filters) { + if (IsFilterApplicable(filter, set)) { + result *= CardinalityValue(RelationStatisticsHelper::DEFAULT_SELECTIVITY); + } } - return CreateDenominatorResult(set, state); + state->inner_selectivities.emplace(set, result); + return result; } -// Cardinality is calculated using logic based on -// https://blobs.duckdb.org/papers/tom-ebergen-msc-thesis-join-order-optimization-with-almost-no-statistics.pdf -// -// The estimator starts with base relation cardinalities and divides by a denominator assembled from predicate domain -// groups. INNER equality predicates use transitive equality classes, composite same-pair equalities can apply an FK/PK -// cap, disconnected predicate subgraphs are merged by cross product, and LEFT/SEMI/ANTI joins adjust the numerator side -// according to their output semantics. Non-equality predicates still use a heuristic total-domain penalty. -const CardinalityHelper &CardinalityEstimator::GetCardinalityBeforeFilters(JoinRelationSet &new_set) { - auto it = state->relation_set_2_cardinality.find(new_set); - if (it != state->relation_set_2_cardinality.end()) { - return it->second; - } - double result; - bool is_empty; - auto semi_anti_result = EstimateTopLevelSemiAnti(new_set); - if (semi_anti_result) { - result = *semi_anti_result; - is_empty = result <= 0; - } else { - // SEMI/ANTI denominators exclude RHS relations from the numerator. - auto denom = GetDenominator(new_set); - auto numerator = GetNumerator(denom.numerator_relations); - result = denom.denominator >= NumericLimits::Maximum() ? 0 : numerator / denom.denominator; - Subgraph2Denominator subgraph; - subgraph.numerator_relations = &denom.numerator_relations; - subgraph.denom = denom.denominator; - is_empty = GetSubgraphCardinality(subgraph) <= 0; - } - return state->relation_set_2_cardinality.emplace(new_set, CardinalityHelper(result, is_empty)).first->second; +CardinalityValue CardinalityEstimator::GetJoinSelectivity(JoinRelationSet &set, JoinRelationSet &left, + JoinRelationSet &right) { + // Leaf cardinalities cancel because the inputs partition the combined set. + auto combined = GetInnerSelectivity(set); + auto left_domains = GetInnerSelectivity(left); + auto right_domains = GetInnerSelectivity(right); + D_ASSERT(!left_domains.IsZero() && !right_domains.IsZero()); + return MinValue(CardinalityValue(1), combined / left_domains / right_domains); } -template <> -double CardinalityEstimator::EstimateCardinalityWithSet(JoinRelationSet &new_set) { - return ApplyOrFilterSelectivities(new_set, GetCardinalityBeforeFilters(new_set).cardinality_before_filters); +CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) { + D_ASSERT(!state->leaf_cardinalities.empty() && !set.Empty()); + auto entry = state->cardinalities.find(set); + if (entry != state->cardinalities.end()) { + return entry->second; + } + optional_ptr boundary; + optional_ptr region; + for (auto &candidate : state->boundaries) { + if (!JoinOrderConflictDetector::IsCompletedBy(candidate.op, set)) { + continue; + } + auto &projected = set_manager.Intersection(set, candidate.scope); + // Original scopes are nested or disjoint; postorder indexes break ties after projection. + if (!region || projected.count > region->count || + (projected.count == region->count && candidate.op.get().index > boundary->op.get().index)) { + boundary = candidate; + region = projected; + } + } + CardinalityValue result; + if (!boundary) { + result = GetNumerator(set) * GetInnerSelectivity(set); + for (idx_t i = 0; i < set.count; i++) { + if (state->leaf_cardinalities.at(set.relations[i].index).IsZero()) { + result = CardinalityValue(0); + break; + } + } + } else if (region->count < set.count) { + auto &remaining = set_manager.Difference(set, *region); + result = + EstimateCardinality(*region) * EstimateCardinality(remaining) * GetJoinSelectivity(set, *region, remaining); + } else { + auto &op = boundary->op.get(); + auto &left = set_manager.Intersection(set, op.left_relations); + auto &right = set_manager.Intersection(set, op.right_relations); + D_ASSERT(!left.Empty() && !right.Empty() && left.count < set.count && right.count < set.count); + auto left_rows = EstimateCardinality(left); + auto right_rows = EstimateCardinality(right); + if (op.type == JoinOrderOperatorType::LEFT) { + result = MaxValue(left_rows, left_rows * right_rows * boundary->selectivity); + } else { + auto type = op.type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; + result = RelationStatisticsHelper::EstimateSemiAntiJoinFallbackCardinality( + left_rows, right_rows.IsZero() ? 0 : 1, type); + } + // Filters above the boundary see its output, including NULL-extended LEFT rows. + result *= GetJoinSelectivity(set, left, right); + } + state->cardinalities.emplace(set, result); + return result; +} + +static CardinalityValue GetResidualOnSelectivity(const Expression &expression) { + if (expression.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + auto &value = expression.Cast().GetValue(); + return CardinalityValue(!value.IsNull() && value.GetValue() ? 1 : 0); + } + return CardinalityValue(RelationStatisticsHelper::DEFAULT_SELECTIVITY); +} + +CardinalityValue CardinalityEstimator::GetLeftJoinSelectivity(const JoinOrderOperator &join_operator) { + CardinalityValue selectivity; + unordered_set equality_groups; + 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 &entry : pair_selectivities) { + auto cap = GetJoinPairCap(entry.first); + selectivity *= + pair_stats.at(entry.first).CanApplyCap(cap) ? CardinalityValue(1) / CardinalityValue(cap) : entry.second; + } + for (auto index : join_operator.costing_predicate_indices) { + if (!accounted_predicates.count(index)) { + selectivity *= CardinalityValue(RelationStatisticsHelper::DEFAULT_SELECTIVITY); + } + } + for (auto &residual : join_operator.residual_predicates) { + selectivity *= GetResidualOnSelectivity(residual); + } + return selectivity; } -double CardinalityEstimator::ApplyOrFilterSelectivities(JoinRelationSet &new_set, double cardinality) const { - for (auto &filter : state->or_filters) { - if (JoinRelationSet::IsSubset(new_set, filter->set.get())) { - cardinality *= RelationStatisticsHelper::DEFAULT_SELECTIVITY; - } +static bool IsSelectivityComparison(const JoinPredicate &predicate) { + switch (predicate.GetComparisonType()) { + case ExpressionType::COMPARE_NOTEQUAL: + case ExpressionType::COMPARE_DISTINCT_FROM: + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + break; + default: + return false; } - return cardinality; + auto predicate_class = predicate.GetPredicateClass(); + return predicate_class == JoinPredicateClass::INNER_NON_EQUALITY || + predicate_class == JoinPredicateClass::LEFT_JOIN; } -template <> -idx_t CardinalityEstimator::EstimateCardinalityWithSet(JoinRelationSet &new_set) { - auto cardinality_as_double = EstimateCardinalityWithSet(new_set); - auto max = NumericLimits::Maximum(); - if (cardinality_as_double >= (double)max) { - return max; +static bool IsSelectivityOnlyGroup(const RelationsSetToStats &stats) { + if (stats.predicates.empty()) { + return false; + } + for (auto &predicate : stats.predicates) { + if (!IsSelectivityComparison(predicate.get())) { + return false; + } } - return (idx_t)cardinality_as_double; + 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(); } -void CardinalityEstimator::InitCardinalityEstimatorProps(optional_ptr set, RelationStats &stats) { - // Get the join relation set - D_ASSERT(stats.stats_initialized); - auto relation_cardinality = stats.cardinality; - - auto card_helper = CardinalityHelper((double)relation_cardinality, relation_cardinality == 0); - state->relation_set_2_cardinality[*set] = card_helper; - - UpdateTotalDomains(set, stats); - - // sort relations from greatest tdom to lowest tdom. - std::sort(state->relation_set_stats.begin(), state->relation_set_stats.end(), SortTdoms); +void CardinalityEstimator::Initialize(const vector &relations, + const vector> &operators) { + D_ASSERT(state->leaf_cardinalities.empty()); + InitEquivalentRelations(); + for (idx_t i = 0; i < relations.size(); i++) { + auto &stats = relations[i]; + D_ASSERT(stats.stats_initialized); + auto cardinality = CardinalityValue(static_cast(stats.cardinality)); + state->leaf_cardinalities.push_back(cardinality); + state->cardinalities.emplace(set_manager.GetJoinRelation(RelationIndex(i)), cardinality); + UpdateTotalDomains(RelationIndex(i), stats); + } + RestrictFilterDomains(relations); + for (auto &op : operators) { + D_ASSERT(op->index == state->operators.size()); + state->operators.push_back(*op); + if (op->type == JoinOrderOperatorType::INNER || op->type == JoinOrderOperatorType::CROSS_PRODUCT) { + continue; + } + auto selectivity = op->type == JoinOrderOperatorType::LEFT ? GetLeftJoinSelectivity(*op) : CardinalityValue(1); + state->boundaries.emplace_back(*op, set_manager.Union(op->left_relations, op->right_relations), selectivity); + } } -void CardinalityEstimator::UpdateTotalDomains(optional_ptr set, RelationStats &stats) { - D_ASSERT(set->count == 1); - auto relation_id = set->relations[0]; +void CardinalityEstimator::UpdateTotalDomains(RelationIndex relation_id, const RelationStats &stats) { //! 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 @@ -1083,36 +966,4 @@ void CardinalityEstimator::RestrictFilterDomains(const vector &re std::sort(state->relation_set_stats.begin(), state->relation_set_stats.end(), SortTdoms); } -// LCOV_EXCL_START - -void CardinalityEstimator::AddRelationNamesToRelationStats(vector &stats) { -#ifdef DEBUG - for (auto &total_domain : state->relation_set_stats) { - for (auto &binding : total_domain.equivalent_relations) { - D_ASSERT(binding.table_index.index < stats.size()); - string column_name; - if (binding.column_index < stats[binding.table_index.index].columns.size()) { - column_name = stats[binding.table_index.index].columns[binding.column_index].name.GetIdentifierName(); - } else { - column_name = "[unknown]"; - } - total_domain.column_names.push_back(column_name); - } - } -#endif -} - -void CardinalityEstimator::PrintRelationStats() { - for (auto &total_domain : state->relation_set_stats) { - string domain = "Following columns have the same distinct count: "; - for (auto &column_name : total_domain.column_names) { - domain += column_name + ", "; - } - domain += "\n TOTAL DOMAIN = " + to_string(total_domain.domain_estimate.GetDistinctCount()); - Printer::Print(domain); - } -} - -// LCOV_EXCL_STOP - } // 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 821a4edfa..2b28db39f 100644 --- a/src/duckdb/src/optimizer/join_order/cost_model.cpp +++ b/src/duckdb/src/optimizer/join_order/cost_model.cpp @@ -1,50 +1,20 @@ -#include "duckdb/optimizer/join_order/join_node.hpp" -#include "duckdb/optimizer/join_order/join_order_optimizer.hpp" #include "duckdb/optimizer/join_order/cost_model.hpp" - -#include "duckdb/optimizer/join_order/query_graph_manager.hpp" +#include "duckdb/optimizer/join_order/join_order_operator.hpp" namespace duckdb { -CostModel::CostModel(QueryGraphManager &query_graph_manager, CardinalityEstimator &cardinality_estimator) - : query_graph_manager(query_graph_manager), cardinality_estimator(cardinality_estimator) { +CostModel::CostModel(CardinalityEstimator &cardinality_estimator) : cardinality_estimator(cardinality_estimator) { } CardinalityEstimator &CostModel::GetCardinalityEstimator() { return cardinality_estimator; } -static double GetLeftJoinInputCost(CardinalityEstimator &cardinality_estimator, - const vector> &possible_connections) { - double cost = 0; - reference_set_t seen_right_sides; - for (auto &connection : possible_connections) { - for (auto predicate_ref : connection.get().predicates) { - auto &predicate = predicate_ref.get(); - if (predicate.GetJoinType() != JoinType::LEFT) { - continue; - } - D_ASSERT(predicate.GetRightSetOptional()); - if (!seen_right_sides.insert(predicate.GetRightSet()).second) { - continue; - } - cost += cardinality_estimator.EstimateCardinalityWithSet(predicate.GetRightSet()); - } - } - return cost; -} - -// Currently cost of a join mostly factors in the cardinalities. -// LEFT joins need an explicit RHS input component because their output cardinality preserves the LHS, -// which otherwise makes early LEFT joins over large RHS inputs look almost free. -double CostModel::ComputeCost(DPJoinNode &left, DPJoinNode &right, JoinRelationSet &combination, - const vector> &possible_connections) { - auto join_card = cardinality_estimator.EstimateCardinalityWithSet(combination); - auto join_cost = join_card; - if (query_graph_manager.GetPredicateModel().HasLeftJoinPredicates()) { - join_cost += GetLeftJoinInputCost(cardinality_estimator, possible_connections); - } - return join_cost + left.cost + right.cost; +double CostModel::ComputeCost(const DPJoinNode &left, const DPJoinNode &right, + optional_ptr join_operator, double output_rows) { + auto input_cost = + join_operator && join_operator->type == JoinOrderOperatorType::LEFT ? right.cardinality.GetDouble() : 0; + return left.cost + right.cost + input_cost + output_rows; } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_operator.cpp b/src/duckdb/src/optimizer/join_order/join_order_operator.cpp index 2816fa664..c5dca69e6 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_operator.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_operator.cpp @@ -43,20 +43,6 @@ static bool ContainedInUnion(const JoinRelationSet &required, const JoinRelation return true; } -static JoinRelationSet &Intersection(JoinRelationSetManager &set_manager, const JoinRelationSet &left, - const JoinRelationSet &right) { - unordered_set result; - for (idx_t left_idx = 0; left_idx < left.count; left_idx++) { - for (idx_t right_idx = 0; right_idx < right.count; right_idx++) { - if (left.relations[left_idx] == right.relations[right_idx]) { - result.insert(left.relations[left_idx]); - break; - } - } - } - return set_manager.GetJoinRelation(result); -} - bool JoinOrderConflictDetector::IsCommutative(JoinOrderOperatorType type) { return type == JoinOrderOperatorType::INNER || type == JoinOrderOperatorType::CROSS_PRODUCT; } @@ -182,7 +168,7 @@ static void AddConflictRule(JoinOrderOperator &op, JoinRelationSet &trigger, Joi static JoinRelationSet &PredicateIntersectionOrInput(JoinRelationSetManager &set_manager, JoinRelationSet &input, JoinRelationSet &syntactic_set) { - auto &intersection = Intersection(set_manager, input, syntactic_set); + auto &intersection = set_manager.Intersection(input, syntactic_set); return intersection.Empty() ? input : intersection; } @@ -234,8 +220,8 @@ static void SimplifyConflictRules(JoinOrderOperator &op, JoinRelationSetManager } } op.conflict_rules = std::move(remaining_rules); - op.left_total_set = Intersection(set_manager, op.total_set, op.left_relations); - op.right_total_set = Intersection(set_manager, op.total_set, op.right_relations); + op.left_total_set = set_manager.Intersection(op.total_set, op.left_relations); + op.right_total_set = set_manager.Intersection(op.total_set, op.right_relations); } void JoinOrderConflictDetector::Build(vector> &operators, 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 300140649..70900b51b 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp @@ -11,96 +11,6 @@ namespace duckdb { -static optional_ptr GetReorderableColumn(const vector &relation_stats, - const ColumnBinding &binding) { - if (!binding.table_index.IsValid() || !binding.column_index.IsValid() || - binding.table_index.index >= relation_stats.size()) { - return nullptr; - } - auto &relation = relation_stats[binding.table_index.index]; - auto column_index = binding.column_index.GetIndex(); - if (column_index >= relation.columns.size()) { - return nullptr; - } - return relation.columns[column_index]; -} - -static optional CombineReorderableStats(const vector &bindings, - const vector &relation_stats, - const RelationManager &relation_manager, - const JoinPredicateModel &predicate_model, - idx_t root_cardinality) { - RelationStats result; - result.cardinality = root_cardinality; - if (relation_stats.size() == 1) { - result.row_retention = relation_stats[0].row_retention; - } - result.stats_initialized = true; - for (auto &stats : relation_stats) { - if (!stats.stats_initialized) { - return {}; - } - if (!result.table_name.empty()) { - result.table_name = Identifier(result.table_name + " joined with "); - } - result.table_name = Identifier(result.table_name + stats.table_name); - } - - column_binding_map_t equality_bounds; - for (auto &equality_class : predicate_model.GetEqualityClasses()) { - idx_t current_domain = NumericLimits::Maximum(); - bool complete = !equality_class.columns.empty(); - for (auto &binding : equality_class.columns) { - auto column = GetReorderableColumn(relation_stats, binding); - if (!column) { - complete = false; - break; - } - current_domain = MinValue(current_domain, column->current_domain.distinct_count); - } - if (!complete) { - continue; - } - for (auto &binding : equality_class.columns) { - auto entry = equality_bounds.find(binding); - if (entry == equality_bounds.end()) { - equality_bounds.emplace(binding, current_domain); - } else { - entry->second = MinValue(entry->second, current_domain); - } - } - } - - for (auto &binding : bindings) { - ColumnBinding normalized; - if (!relation_manager.TryNormalizeBinding(binding, normalized)) { - return {}; - } - auto source = GetReorderableColumn(relation_stats, normalized); - if (!source) { - return {}; - } - SemiAntiJoinDomainEvidence semi_anti_evidence; - if (relation_stats.size() == 1) { - semi_anti_evidence = source->semi_anti_join_domain_evidence; - } - result.columns.emplace_back(binding, source->total_domain, source->current_domain, source->name, - semi_anti_evidence); - auto &column = result.columns.back(); - auto equality_entry = equality_bounds.find(normalized); - if (equality_entry != equality_bounds.end()) { - column.current_domain = - DistinctCount(MinValue(column.current_domain.distinct_count, equality_entry->second), - DistinctCountSource::CARDINALITY); - } - column.current_domain.distinct_count = - MinValue(column.current_domain.distinct_count, column.total_domain.distinct_count); - } - result.CapCurrentDomainsToCardinality(); - result.Verify(bindings); - return result; -} - JoinOrderOptimizer::JoinOrderOptimizer(ClientContext &context) : context(context), query_graph_manager(context), depth(1) { } @@ -123,21 +33,22 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptr new_logical_plan = nullptr; + RelationStats output_stats; if (reorderable) { // query graph now has filters and relations auto cardinality_estimator = CardinalityEstimator(query_graph_manager.set_manager, query_graph_manager.GetPredicateModel()); - auto cost_model = CostModel(query_graph_manager, cardinality_estimator); + auto cost_model = CostModel(cardinality_estimator); // Initialize a plan enumerator. auto plan_enumerator = @@ -148,34 +59,30 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptrestimated_cardinality = relation_stats.at(0).cardinality; new_logical_plan->has_estimated_cardinality = true; } + if (stats && query_graph_manager.relation_manager.HasCompleteStats()) { + auto combined = query_graph_manager.CombineRelationStats( + new_logical_plan->GetColumnBindings(), relation_stats, new_logical_plan->EstimateCardinality(context)); + if (combined) { + output_stats = std::move(*combined); + } + } } - auto root_cardinality = new_logical_plan->EstimateCardinality(context); - // Propagate up a stats object from the top of the new_logical_plan if stats exist. if (stats) { - auto new_stats = query_graph_manager.relation_manager.HasCompleteStats() - ? CombineReorderableStats(new_logical_plan->GetColumnBindings(), relation_stats, - query_graph_manager.relation_manager, - query_graph_manager.GetPredicateModel(), root_cardinality) - : optional(); - if (new_stats) { - *stats = std::move(*new_stats); - } else { - *stats = RelationStats(); - } + *stats = std::move(output_stats); } if (new_logical_plan->type == LogicalOperatorType::LOGICAL_EXPLAIN) { diff --git a/src/duckdb/src/optimizer/join_order/join_predicate.cpp b/src/duckdb/src/optimizer/join_order/join_predicate.cpp index ca5227033..f3a96bd16 100644 --- a/src/duckdb/src/optimizer/join_order/join_predicate.cpp +++ b/src/duckdb/src/optimizer/join_order/join_predicate.cpp @@ -1,10 +1,28 @@ #include "duckdb/optimizer/join_order/join_predicate.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/common/assert.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" 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(); + } + if (BoundCastExpression::IsCast(expression)) { + auto &cast = expression.Cast(); + if (!BoundCastExpression::IsTryCast(cast) && + BoundCastExpression::CastIsInvertible(BoundCastExpression::SourceType(cast), cast.GetReturnType())) { + return GetEquivalenceBinding(BoundCastExpression::Child(cast)); + } + } + return ColumnBinding(); +} + ExpressionType JoinOrderUtil::GetJoinPredicateComparisonType(const FilterInfo &filter) { if (!filter.filter) { return ExpressionType::INVALID; @@ -238,7 +256,6 @@ void JoinPredicateModel::Clear() { equality_join_predicates.clear(); selectivity_predicates.clear(); graph_predicates.clear(); - has_left_join_predicates = false; equality_classes.clear(); equality_pairs.clear(); } @@ -251,9 +268,6 @@ JoinPredicate &JoinPredicateModel::RegisterPredicate(FilterInfo &filter, JoinPre auto &result = *predicate; predicates.push_back(std::move(predicate)); all_predicates.push_back(result); - if (predicate_class == JoinPredicateClass::LEFT_JOIN) { - has_left_join_predicates = true; - } if (result.HasDisjointJoinEndpoints()) { graph_predicates.push_back(result); } @@ -308,10 +322,6 @@ const vector &JoinPredicateModel::GetEqualityClasses() const return equality_classes; } -bool JoinPredicateModel::HasLeftJoinPredicates() const { - return has_left_join_predicates; -} - bool JoinPredicateModel::HasDirectCompositeEquality(JoinRelationSet &pair) const { auto entry = equality_pairs.find(pair); if (entry == equality_pairs.end()) { diff --git a/src/duckdb/src/optimizer/join_order/join_relation_set.cpp b/src/duckdb/src/optimizer/join_order/join_relation_set.cpp index 7794c423f..d733c0ae8 100644 --- a/src/duckdb/src/optimizer/join_order/join_relation_set.cpp +++ b/src/duckdb/src/optimizer/join_order/join_relation_set.cpp @@ -147,36 +147,37 @@ JoinRelationSet &JoinRelationSetManager::Union(JoinRelationSet &left, JoinRelati return GetJoinRelation(std::move(relations), count); } -// JoinRelationSet *JoinRelationSetManager::Difference(JoinRelationSet *left, JoinRelationSet *right) { -// auto relations = unsafe_unique_array(new idx_t[left->count]); -// idx_t count = 0; -// // move through the left and right relations -// idx_t i = 0, j = 0; -// while (true) { -// if (i == left->count) { -// // exhausted left relation, we are done -// break; -// } else if (j == right->count) { -// // exhausted right relation, add remaining of left -// for (; i < left->count; i++) { -// relations[count++] = left->relations[i]; -// } -// break; -// } else if (left->relations[i] == right->relations[j]) { -// // equivalent, add nothing -// i++; -// j++; -// } else if (left->relations[i] < right->relations[j]) { -// // left is smaller, progress left and add it to the set -// relations[count++] = left->relations[i]; -// i++; -// } else { -// // right is smaller, progress right -// j++; -// } -// } -// return GetJoinRelation(std::move(relations), count); -// } +JoinRelationSet &JoinRelationSetManager::Intersection(const JoinRelationSet &left, const JoinRelationSet &right) { + auto relations = make_unsafe_uniq_array(MinValue(left.count, right.count)); + idx_t count = 0; + idx_t i = 0, j = 0; + while (i < left.count && j < right.count) { + if (left.relations[i] < right.relations[j]) { + i++; + } else if (right.relations[j] < left.relations[i]) { + j++; + } else { + relations[count++] = left.relations[i++]; + j++; + } + } + return GetJoinRelation(std::move(relations), count); +} + +JoinRelationSet &JoinRelationSetManager::Difference(const JoinRelationSet &left, const JoinRelationSet &right) { + auto relations = make_unsafe_uniq_array(left.count); + idx_t count = 0; + idx_t j = 0; + for (idx_t i = 0; i < left.count; i++) { + while (j < right.count && right.relations[j] < left.relations[i]) { + j++; + } + if (j == right.count || left.relations[i] != right.relations[j]) { + relations[count++] = left.relations[i]; + } + } + return GetJoinRelation(std::move(relations), count); +} static string JoinRelationTreeNodeToString(const JoinRelationTreeNode *node) { string result = ""; diff --git a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp index 2f48730e1..fbde2dfd3 100644 --- a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp +++ b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp @@ -182,10 +182,11 @@ unique_ptr PlanEnumerator::CreateJoinTree(JoinRelationSet &set, if (!best_candidate) { return nullptr; } - auto cost = cost_model.ComputeCost(left, right, set, applicable_connections); + auto cardinality = cost_model.GetCardinalityEstimator().EstimateCardinality(set); + 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 = cost_model.GetCardinalityEstimator().EstimateCardinalityWithSet(set); + result->cardinality = cardinality; return result; } @@ -406,6 +407,18 @@ bool PlanEnumerator::SolveJoinOrderExactly() { } bool PlanEnumerator::SolveJoinOrderApproximately() { + // Keep the incoming join order as a candidate for the greedy search. + for (auto &op : query_graph_manager.GetJoinOperators()) { + auto &left = op->left_relations.get(); + auto &right = op->right_relations.get(); + if (plans.find(left) == plans.end() || plans.find(right) == plans.end()) { + continue; + } + auto &connections = GetConnections(left, right); + if (!connections.empty()) { + EmitPair(left, right, connections); + } + } // at this point, we exited the dynamic programming but did not compute the final join order because it took too // long instead, we use a greedy heuristic to obtain a join ordering now we use Greedy Operator Ordering to // construct the result tree first we start out with all the base relations (the to-be-joined relations) @@ -423,12 +436,19 @@ bool PlanEnumerator::SolveJoinOrderApproximately() { double cost; }; vector candidates; - auto EmitCandidate = [&](JoinRelationSet &left, JoinRelationSet &right) { + auto EmitOrientation = [&](JoinRelationSet &left, JoinRelationSet &right) -> optional_ptr { auto &connection = GetConnections(left, right); if (connection.empty()) { - return; + return nullptr; + } + return EmitPair(left, right, connection); + }; + auto EmitCandidate = [&](JoinRelationSet &left, JoinRelationSet &right) { + // non-commutative joins (e.g. LEFT, SEMI, ANTI) are only valid in one orientation + auto node = EmitOrientation(left, right); + if (!node) { + node = EmitOrientation(right, left); } - auto node = EmitPair(left, right, connection); if (node) { candidates.push_back({&left, &right, node->cost}); } @@ -555,27 +575,16 @@ bool PlanEnumerator::PlanUsesCrossProduct(const DPJoinNode &node) const { } void PlanEnumerator::InitLeafPlans() { - // First we initialize each of the single-node plans with themselves and with their cardinalities these are the leaf - // nodes of the join tree NOTE: we can just use pointers to JoinRelationSet* here because the GetJoinRelation - // function ensures that a unique combination of relations will have a unique JoinRelationSet object. - // first initialize equivalent relations based on the filters auto relation_stats = query_graph_manager.relation_manager.GetRelationStats(); - - cost_model.GetCardinalityEstimator().InitEquivalentRelations(); - cost_model.GetCardinalityEstimator().AddRelationNamesToRelationStats(relation_stats); - - // then update the total domains based on the cardinalities of each relation. + auto &estimator = cost_model.GetCardinalityEstimator(); + estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators()); for (idx_t i = 0; i < relation_stats.size(); i++) { - auto stats = relation_stats.at(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 = stats.cardinality; - D_ASSERT(join_node->set.count == 1); + join_node->cardinality = estimator.EstimateCardinality(relation_set); plans[relation_set] = std::move(join_node); - cost_model.GetCardinalityEstimator().InitCardinalityEstimatorProps(&relation_set, stats); } - cost_model.GetCardinalityEstimator().RestrictFilterDomains(relation_stats); } // the plan enumeration is a straight implementation of the paper "Dynamic Programming Strikes Back" by Guido 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 358f4257e..88a21e45d 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/assert.hpp" #include "duckdb/common/enums/join_type.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" @@ -17,8 +18,8 @@ namespace duckdb { GenerateJoinRelation::GenerateJoinRelation(optional_ptr set, unique_ptr op_p, - idx_t cardinality_p) - : set(set), op(std::move(op_p)), cardinality(cardinality_p) { + RelationStats stats_p) + : set(set), op(std::move(op_p)), stats(std::move(stats_p)) { } QueryGraphManager::QueryGraphManager(ClientContext &context) : context(context), relation_manager(context) { @@ -102,10 +103,11 @@ void QueryGraphManager::BuildPredicateModel() { predicate_model.AddDirectEqualityPairClass(pair, equality_class.index, first_binding, second_binding); } } - BuildLeftEqualityPairs(); + BuildLeftJoinPredicates(); } -void QueryGraphManager::BuildLeftEqualityPairs() { +void QueryGraphManager::BuildLeftJoinPredicates() { + idx_t next_left_equality_group = 0; for (auto &op : join_operators) { if (op->type != JoinOrderOperatorType::LEFT) { continue; @@ -113,40 +115,52 @@ void QueryGraphManager::BuildLeftEqualityPairs() { JoinEqualityGroups groups; auto add_equality = [&](ExpressionType type, const Expression &left, const Expression &right) { if (type != ExpressionType::COMPARE_EQUAL && type != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { - return; + return ColumnBinding(); } ColumnBinding left_binding; ColumnBinding right_binding; GetEquivalenceBinding(left, left_binding); GetEquivalenceBinding(right, right_binding); - if (left_binding.table_index.IsValid() && right_binding.table_index.IsValid()) { - groups.AddEquality(left_binding, right_binding); + if (!left_binding.table_index.IsValid() || !right_binding.table_index.IsValid()) { + return ColumnBinding(); } + groups.AddEquality(left_binding, right_binding); + return left_binding; }; - vector> residuals; + vector modeled_equalities; + vector> pending_residuals; + vector, ColumnBinding>> residuals; for (auto &condition : op->conditions) { if (condition.IsComparison()) { - add_equality(condition.GetComparisonType(), condition.GetLHS(), condition.GetRHS()); + auto binding = add_equality(condition.GetComparisonType(), condition.GetLHS(), condition.GetRHS()); + if (binding.table_index.IsValid()) { + modeled_equalities.push_back(binding); + } } else { - residuals.push_back(condition.GetJoinExpression()); + pending_residuals.push_back(condition.GetJoinExpression()); } } // Same-side ON equalities can connect keys even though they are not costing predicates. - while (!residuals.empty()) { - auto &expression = residuals.back().get(); - residuals.pop_back(); + while (!pending_residuals.empty()) { + auto &expression = pending_residuals.back().get(); + pending_residuals.pop_back(); if (expression.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { for (auto &child : expression.Cast().GetChildren()) { - residuals.push_back(*child); + pending_residuals.push_back(*child); } - } else if (BoundComparisonExpression::IsComparison(expression)) { + continue; + } + ColumnBinding binding; + if (BoundComparisonExpression::IsComparison(expression)) { auto &comparison = expression.Cast(); - add_equality(expression.GetExpressionType(), BoundComparisonExpression::Left(comparison), - BoundComparisonExpression::Right(comparison)); + binding = add_equality(expression.GetExpressionType(), BoundComparisonExpression::Left(comparison), + BoundComparisonExpression::Right(comparison)); } + residuals.emplace_back(expression, binding); } reference_map_t summaries; vector, reference>> pairs; + unordered_map group_ids; for (auto predicate_index : op->costing_predicate_indices) { auto &predicate = predicate_model.GetPredicates()[predicate_index].get(); auto type = predicate.GetComparisonType(); @@ -166,7 +180,13 @@ void QueryGraphManager::BuildLeftEqualityPairs() { if (pair.relations[0] != first_relation) { std::swap(first_binding, second_binding); } - summaries[pair].AddEquality(groups.GetGroup(first_binding), first_binding, second_binding); + auto group_root = groups.GetGroup(first_binding); + auto group_entry = group_ids.find(group_root); + if (group_entry == group_ids.end()) { + group_entry = group_ids.insert(make_pair(group_root, next_left_equality_group++)).first; + } + predicate.GetFilter().left_equality_group = optional_idx(group_entry->second); + summaries[pair].AddEquality(group_root, first_binding, second_binding); pairs.emplace_back(predicate, pair); } for (auto &entry : pairs) { @@ -174,6 +194,16 @@ void QueryGraphManager::BuildLeftEqualityPairs() { entry.first.get().SetCompositeJoinPair(entry.second); } } + unordered_set accounted_groups; + for (auto &binding : modeled_equalities) { + accounted_groups.insert(groups.GetGroup(binding)); + } + for (auto &residual : residuals) { + auto &binding = residual.second; + if (!binding.table_index.IsValid() || accounted_groups.insert(groups.GetGroup(binding)).second) { + op->residual_predicates.push_back(residual.first); + } + } } } @@ -226,6 +256,49 @@ bool QueryGraphManager::Build(JoinOrderOptimizer &optimizer, LogicalOperator &op // nothing to optimize/reorder return false; } + PreparePredicateModel(op); + BuildInnerCompanionSets(); + CreateHyperGraphEdges(); + return true; +} + +bool QueryGraphManager::BuildForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op) { + if (!relation_manager.ExtractJoinRelationsForEstimation(extractor, op, filter_operators) || + relation_manager.NumRelations() <= 1) { + return false; + } + for (auto &filter : filter_operators) { + bool valid_bindings = true; + LogicalOperatorVisitor::EnumerateExpressions( + static_cast(filter.get()), [&](optional_ptr> expr) { + ExpressionIterator::VisitExpression( + **expr, [&](const BoundColumnRefExpression &column) { + ColumnBinding normalized; + if (column.Depth() != 0 || + !relation_manager.TryNormalizeBinding(column.Binding(), normalized)) { + valid_bindings = false; + } + }); + for (auto expr_class : {ExpressionClass::BOUND_REF, ExpressionClass::BOUND_SUBQUERY}) { + ExpressionIterator::VisitExpressionClass(**expr, expr_class, + [&](const Expression &) { valid_bindings = false; }); + } + }); + if (!valid_bindings) { + return false; + } + } + PreparePredicateModel(op); + for (auto &filter : filters_and_bindings) { + // Single-relation root filters need to be estimated outside the join region. + if (filter->from_logical_filter && filter->set.get().count < 2) { + return false; + } + } + return true; +} + +void QueryGraphManager::PreparePredicateModel(LogicalOperator &op) { // extract the edges of the hypergraph, creating a list of filters and their associated bindings. auto extraction = relation_manager.ExtractEdges(op, filter_operators, set_manager); filters_and_bindings = std::move(extraction.filters); @@ -253,16 +326,123 @@ bool QueryGraphManager::Build(JoinOrderOptimizer &optimizer, LogicalOperator &op BindFilterEndpoints(); // Build the predicate model after BindFilterEndpoints so that left_binding/right_binding are populated. BuildPredicateModel(); - BuildInnerCompanionSets(); - // Create query_graph hyper edges from the normalized predicate model. - CreateHyperGraphEdges(); - return true; +} + +optional QueryGraphManager::CombineRelationStats(const vector &bindings, + const vector &relation_stats, + idx_t root_cardinality) const { + vector> inputs; + for (auto &stats : relation_stats) { + inputs.push_back(stats); + } + return CombineRelationStats(bindings, inputs, root_cardinality); +} + +static column_binding_map_t +GetEqualityDomainBounds(const vector &equality_classes, + const column_binding_map_t> &source_columns) { + column_binding_map_t equality_bounds; + for (auto &equality_class : equality_classes) { + idx_t current_domain = NumericLimits::Maximum(); + bool complete = !equality_class.columns.empty(); + for (auto &binding : equality_class.columns) { + auto column = source_columns.find(binding); + if (column == source_columns.end()) { + complete = false; + break; + } + current_domain = MinValue(current_domain, column->second.get().current_domain.distinct_count); + } + if (!complete) { + continue; + } + for (auto &binding : equality_class.columns) { + auto entry = equality_bounds.find(binding); + if (entry == equality_bounds.end()) { + equality_bounds.emplace(binding, current_domain); + } else { + entry->second = MinValue(entry->second, current_domain); + } + } + } + return equality_bounds; +} + +static RelationColumnStats CombineColumnStats(const ColumnBinding &binding, const ColumnBinding &normalized, + const RelationColumnStats &source, + const column_binding_map_t &equality_bounds, + bool preserve_semi_anti_evidence) { + SemiAntiJoinDomainEvidence semi_anti_evidence; + if (preserve_semi_anti_evidence) { + semi_anti_evidence = source.semi_anti_join_domain_evidence; + } + RelationColumnStats column(binding, source.total_domain, source.current_domain, source.name, semi_anti_evidence); + auto equality_entry = equality_bounds.find(normalized); + if (equality_entry != equality_bounds.end()) { + column.current_domain = DistinctCount(MinValue(column.current_domain.distinct_count, equality_entry->second), + DistinctCountSource::CARDINALITY); + } + column.current_domain.distinct_count = + MinValue(column.current_domain.distinct_count, column.total_domain.distinct_count); + return column; +} + +optional QueryGraphManager::CombineRelationStats(const vector &bindings, + const vector> &inputs, + idx_t root_cardinality) const { + RelationStats result; + result.cardinality = root_cardinality; + if (inputs.size() == 1) { + result.row_retention = inputs[0].get().row_retention; + } + result.stats_initialized = true; + column_binding_map_t> source_columns; + for (auto &input : inputs) { + auto &stats = input.get(); + if (!stats.stats_initialized) { + return {}; + } +#ifdef DEBUG + if (!result.table_name.empty()) { + result.table_name = Identifier(result.table_name + " joined with "); + } + result.table_name = Identifier(result.table_name + stats.table_name); +#endif + for (auto &column : stats.columns) { + ColumnBinding normalized; + if (!relation_manager.TryNormalizeBinding(column.binding, normalized)) { + return {}; + } + source_columns.emplace(normalized, column); + } + } + + auto equality_bounds = GetEqualityDomainBounds(predicate_model.GetEqualityClasses(), source_columns); + for (auto &binding : bindings) { + ColumnBinding normalized; + if (!relation_manager.TryNormalizeBinding(binding, normalized)) { + return {}; + } + auto source_entry = source_columns.find(normalized); + if (source_entry == source_columns.end()) { + return {}; + } + result.columns.push_back( + CombineColumnStats(binding, normalized, source_entry->second.get(), equality_bounds, inputs.size() == 1)); + } + result.CapCurrentDomainsToCardinality(); + result.Verify(bindings); + return result; } const JoinPredicateModel &QueryGraphManager::GetPredicateModel() const { return predicate_model; } +const vector> &QueryGraphManager::GetJoinOperators() const { + return join_operators; +} + void QueryGraphManager::GetColumnBinding(const Expression &root_expr, ColumnBinding &binding) { ExpressionIterator::VisitExpression( root_expr, [&](const BoundColumnRefExpression &colref) { @@ -278,34 +458,11 @@ void QueryGraphManager::GetColumnBinding(const Expression &root_expr, ColumnBind } void QueryGraphManager::GetEquivalenceBinding(const Expression &expression, ColumnBinding &binding) { - switch (expression.GetExpressionClass()) { - case ExpressionClass::BOUND_COLUMN_REF: { - auto &colref = expression.Cast(); - D_ASSERT(colref.Depth() == 0); - if (!colref.Binding().table_index.IsValid()) { - return; - } - auto normalized = relation_manager.TryNormalizeBinding(colref.Binding(), binding); + auto source = JoinOrderUtil::GetEquivalenceBinding(expression); + if (source.table_index.IsValid()) { + auto normalized = relation_manager.TryNormalizeBinding(source, binding); D_ASSERT(normalized); - if (!normalized) { - return; - } - return; - } - case ExpressionClass::BOUND_FUNCTION: { - if (!BoundCastExpression::IsCast(expression)) { - return; - } - auto &cast = expression.Cast(); - if (BoundCastExpression::IsTryCast(cast) || - !BoundCastExpression::CastIsInvertible(BoundCastExpression::SourceType(cast), cast.GetReturnType())) { - return; - } - GetEquivalenceBinding(BoundCastExpression::Child(cast), binding); - return; - } - default: - return; + (void)normalized; } } @@ -501,10 +658,27 @@ void QueryGraphManager::ClearExtractedExpressions() { } } -unique_ptr QueryGraphManager::Reconstruct(unique_ptr plan, - const vector &relation_stats) { +GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr plan, + const vector &relation_stats) { // now we have to rewrite the plan bool root_is_join = plan->children.size() > 1; + // find the operator whose child is replaced by the new join tree + optional_ptr> parent; + vector old_child_bindings; + vector> ancestors; + if (!root_is_join) { + D_ASSERT(plan->children.size() == 1); + parent = &plan; + ancestors.push_back(**parent); + while ((*parent)->children[0]->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT && + (*parent)->children[0]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + (*parent)->children[0]->type != LogicalOperatorType::LOGICAL_ASOF_JOIN) { + D_ASSERT((*parent)->children[0]->children.size() == 1); + parent = &(*parent)->children[0]; + ancestors.push_back(**parent); + } + old_child_bindings = (*parent)->children[0]->GetColumnBindings(); + } ClearExtractedExpressions(); unordered_set bindings; @@ -544,27 +718,29 @@ unique_ptr QueryGraphManager::Reconstruct(unique_ptrfilter)); } } - join_tree.op->SetEstimatedCardinality(join_tree.cardinality); + join_tree.op->SetEstimatedCardinality(join_tree.stats.cardinality); // find the first join in the relation to know where to place this node if (root_is_join) { // first node is the join, return it immediately - return std::move(join_tree.op); - } - D_ASSERT(plan->children.size() == 1); - // have to move up through the relations - auto op = plan.get(); - auto parent = plan.get(); - while (op->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT && - op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - op->type != LogicalOperatorType::LOGICAL_ASOF_JOIN) { - D_ASSERT(op->children.size() == 1); - parent = op; - op = op->children[0].get(); + return join_tree; } // have to replace at this node - parent->children[0] = std::move(join_tree.op); - return plan; + (*parent)->children[0] = std::move(join_tree.op); + // the new join tree can emit its columns in a different order: preserve the parent's output layout + ColumnBindingRewrite::ApplyToChild(*parent, 0, std::move(old_child_bindings), BindingReplacementGraph()); + for (auto ancestor = ancestors.rbegin(); ancestor != ancestors.rend(); ++ancestor) { + vector> input {join_tree.stats}; + auto output_stats = RelationStatisticsHelper::ExtractOperatorStats(ancestor->get(), context, input); + if (!output_stats) { + join_tree.stats = RelationStats(); + break; + } + join_tree.stats = std::move(*output_stats); + ancestor->get().SetEstimatedCardinality(join_tree.stats.cardinality); + } + join_tree.op = std::move(plan); + return join_tree; } static JoinCondition MaybeInvertConditions(unique_ptr condition, bool invert) { @@ -617,112 +793,6 @@ static JoinType GetJoinType(JoinOrderOperatorType type) { } } -static bool ContainsRelation(const JoinRelationSet &set, const ColumnBinding &binding) { - if (!binding.table_index.IsValid()) { - return false; - } - for (idx_t set_idx = 0; set_idx < set.count; set_idx++) { - if (set.relations[set_idx].index == binding.table_index.index) { - return true; - } - } - return false; -} - -static optional_ptr GetSelectedJoinColumn(const vector &relation_stats, - const ColumnBinding &binding) { - if (!binding.table_index.IsValid() || !binding.column_index.IsValid() || - binding.table_index.index >= relation_stats.size()) { - return nullptr; - } - auto &relation = relation_stats[binding.table_index.index]; - auto column_index = binding.column_index.GetIndex(); - if (column_index >= relation.columns.size()) { - return nullptr; - } - return relation.columns[column_index]; -} - -static optional -EstimateSelectedSemiAntiJoin(const JoinOrderOperator &join_operator, const GenerateJoinRelation &left, - const GenerateJoinRelation &right, const JoinPredicateModel &predicate_model, - const vector &relation_stats) { - if (join_operator.type != JoinOrderOperatorType::SEMI && join_operator.type != JoinOrderOperatorType::ANTI) { - return {}; - } - if (!RelationSetsEqual(*left.set, join_operator.left_total_set) || - !RelationSetsEqual(*right.set, join_operator.right_total_set)) { - return {}; - } - auto join_type = GetJoinType(join_operator.type); - if (right.set->count != 1) { - return {}; - } - - vector domains; - for (auto predicate_index : join_operator.costing_predicate_indices) { - auto predicate = predicate_model.GetPredicateByFilterIndex(predicate_index); - if (!predicate || predicate->GetJoinType() != join_type || !predicate->HasValidEqualityBindings() || - (predicate->GetComparisonType() != ExpressionType::COMPARE_EQUAL && - predicate->GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { - return {}; - } - auto semantic_left = predicate->GetSemanticLeftSetOptional(); - auto semantic_right = predicate->GetSemanticRightSetOptional(); - if (!semantic_left || !semantic_right || !RelationSetsEqual(*semantic_left, join_operator.left_total_set) || - !RelationSetsEqual(*semantic_right, join_operator.right_total_set)) { - return {}; - } - - auto preserved_binding = predicate->GetEqualityBinding(true); - auto rhs_binding = predicate->GetEqualityBinding(false); - auto lhs_is_rhs = ContainsRelation(*right.set, preserved_binding); - auto rhs_is_rhs = ContainsRelation(*right.set, rhs_binding); - if (lhs_is_rhs == rhs_is_rhs) { - return {}; - } - if (lhs_is_rhs) { - std::swap(preserved_binding, rhs_binding); - } - if (!ContainsRelation(*left.set, preserved_binding)) { - return {}; - } - auto preserved_column = GetSelectedJoinColumn(relation_stats, preserved_binding); - auto rhs_column = GetSelectedJoinColumn(relation_stats, rhs_binding); - if (!preserved_column || !rhs_column) { - return {}; - } - auto rhs_current_domain = rhs_column->GetSupportedSemiAntiDomainSize(); - auto total_domain = - RelationStatisticsHelper::SelectTotalDomain({preserved_column->total_domain, rhs_column->total_domain}); - if (!rhs_current_domain.IsValid() || !total_domain || total_domain->distinct_count == 0) { - return {}; - } - bool seen_domain = false; - for (auto &domain : domains) { - if (domain.preserved_binding == preserved_binding && domain.rhs_binding == rhs_binding) { - seen_domain = true; - break; - } - } - if (!seen_domain) { - domains.push_back( - {total_domain->distinct_count, rhs_current_domain.GetIndex(), preserved_binding, rhs_binding}); - } - } - if (domains.empty()) { - return {}; - } - - auto rhs_relation_index = right.set->relations[0].index; - if (rhs_relation_index >= relation_stats.size()) { - return {}; - } - return RelationStatisticsHelper::EstimateSemiAntiJoinCardinality( - static_cast(left.cardinality), right.cardinality, relation_stats[rhs_relation_index].row_retention, - join_type, domains, false); -} - static void OrientInnerConditions(RelationManager &relation_manager, JoinRelationSetManager &set_manager, vector &conditions, const JoinRelationSet &left, const JoinRelationSet &right) { @@ -752,13 +822,14 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vector right_node; optional_ptr result_relation; unique_ptr result_operator; + optional result_stats; auto dp_entry = plans->find(set); if (dp_entry == plans->end()) { throw InternalException("Join Order Optimizer Error: No full plan was created"); } auto &node = dp_entry->second; - auto result_cardinality = node->cardinality; + auto result_cardinality = node->cardinality.GetIndex(); if (!dp_entry->second->is_leaf) { // generate the left and right children auto left = GenerateJoins(extracted_relations, node->left_set, relation_stats); @@ -789,12 +860,6 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorindex).second) { throw InternalException("Operator occurrence %llu was reconstructed more than once", descriptor->index); } - auto semi_anti_estimate = - EstimateSelectedSemiAntiJoin(*descriptor, left, right, predicate_model, relation_stats); - if (semi_anti_estimate && semi_anti_estimate->used_domain_evidence) { - result_cardinality = LossyNumericCast(semi_anti_estimate->cardinality); - } - for (auto predicate_index : descriptor->costing_predicate_indices) { auto &filter = filters_and_bindings.at(predicate_index); if (!filter->filter) { @@ -871,12 +936,25 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vector> child_stats {left.stats, right.stats}; + if (result_operator->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + (result_operator->Cast().join_type == JoinType::SEMI || + result_operator->Cast().join_type == JoinType::ANTI)) { + result_stats = RelationStatisticsHelper::ExtractOperatorStats(*result_operator, context, child_stats); + if (result_stats) { + result_cardinality = result_stats->cardinality; + } + } else { + result_stats = CombineRelationStats(result_operator->GetColumnBindings(), child_stats, result_cardinality); + } } else { // base node, get the entry from the list of extracted relations D_ASSERT(node->set.count == 1); D_ASSERT(extracted_relations[node->set.relations[0].index]); result_relation = &node->set; result_operator = std::move(extracted_relations[result_relation->relations[0].index]); + vector> inputs {relation_stats[result_relation->relations[0].index]}; + result_stats = CombineRelationStats(result_operator->GetColumnBindings(), inputs, result_cardinality); } // TODO: this is where estimated properties start coming into play. // when creating the result operator, we should ask the cost model and cardinality estimator what @@ -1016,8 +1094,13 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorSetEstimatedCardinality(result_cardinality); - auto result = GenerateJoinRelation(result_relation, std::move(result_operator), result_cardinality); - return result; + RelationStats output_stats; + if (result_stats) { + output_stats = std::move(*result_stats); + output_stats.Verify(result_operator->GetColumnBindings()); + } + output_stats.cardinality = result_cardinality; + return GenerateJoinRelation(result_relation, std::move(result_operator), std::move(output_stats)); } const QueryGraphEdges &QueryGraphManager::GetQueryGraphEdges() const { diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 02a71d943..4e3394065 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -6,6 +6,8 @@ #include "duckdb/optimizer/join_order/join_order_optimizer.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/expression/list.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -61,15 +63,25 @@ idx_t RelationManager::NumRelations() { bool RelationManager::AddRelation(LogicalOperator &op, optional_ptr parent, const RelationStats &stats) { - // if parent is null, then this is a root relation - // if parent is not null, it should have multiple children - D_ASSERT(!parent || parent->children.size() >= 2); auto aligned_stats = AlignStatsWithRelationRoot(op, stats); if (!aligned_stats) { stats_complete = false; return false; } - auto relation = make_uniq(op, parent, std::move(*aligned_stats)); + if (!RegisterRelation(op, parent, std::move(*aligned_stats))) { + return false; + } + op.SetEstimatedCardinality(relations.back()->stats.cardinality); + return true; +} + +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())) { + stats_complete = false; + return false; + } + auto relation = make_uniq(op, parent, std::move(stats)); RelationIndex relation_id(relations.size()); unordered_set relation_bindings; @@ -94,12 +106,66 @@ bool RelationManager::AddRelation(LogicalOperator &op, optional_ptrstats); operator_relations[op] = relation_id; - op.estimated_cardinality = relation->stats.cardinality; - op.has_estimated_cardinality = true; relations.push_back(std::move(relation)); return true; } +static bool HasVisibleEstimationInputs(LogicalOperator &op) { + column_binding_map_t input_bindings; + for (idx_t child_idx = 0; child_idx < op.children.size(); child_idx++) { + for (auto &binding : op.children[child_idx]->GetColumnBindings()) { + auto entry = input_bindings.emplace(binding, child_idx); + if (!entry.second && entry.first->second != child_idx) { + return false; + } + } + } + bool valid_bindings = true; + unordered_set referenced_children; + LogicalOperatorVisitor::EnumerateExpressions(static_cast(op), + [&](optional_ptr> expr) { + ExpressionIterator::VisitExpression( + **expr, [&](const BoundColumnRefExpression &column) { + auto input = input_bindings.find(column.Binding()); + if (column.Depth() != 0 || input == input_bindings.end()) { + valid_bindings = false; + } else { + referenced_children.insert(input->second); + } + }); + }); + // Conflict preparation needs both INNER inputs; the join's output maps do not hide its predicate inputs. + return valid_bindings && + (op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN || referenced_children.size() == 2); +} + +bool RelationManager::ExtractJoinRelationsForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op, + vector> &filter_operators, + optional_ptr parent) { + // Filters within a region remain part of their leaf's statistics. Root filters can supply join predicates. + if (!parent && op.type == LogicalOperatorType::LOGICAL_FILTER) { + if (!HasVisibleEstimationInputs(op)) { + return false; + } + filter_operators.push_back(op); + return ExtractJoinRelationsForEstimation(extractor, *op.children[0], filter_operators); + } + auto is_inner = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op.Cast().join_type == JoinType::INNER; + if (is_inner || op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + if (!HasVisibleEstimationInputs(op)) { + return false; + } + if (is_inner) { + filter_operators.push_back(op); + } + return ExtractJoinRelationsForEstimation(extractor, *op.children[0], filter_operators, op) && + ExtractJoinRelationsForEstimation(extractor, *op.children[1], filter_operators, op); + } + auto stats = extractor.Extract(op); + return stats && RegisterRelation(op, parent, *stats); +} + optional RelationManager::AlignStatsWithRelationRoot(LogicalOperator &op, const RelationStats &stats) { auto projected = RelationStatisticsHelper::ProjectOutputStats(stats, op); if (projected && (op.children.size() != 1 || CanReuseAlignedStats(op))) { @@ -135,7 +201,8 @@ void RelationManager::RegisterRelationBindings(LogicalOperator &op, RelationInde if (entry == normalized_bindings.end()) { normalized_bindings.emplace(bindings[column_idx], normalized); } else { - D_ASSERT(entry->second == normalized); + // Repeated output bindings share the first slot within this relation. + D_ASSERT(entry->second.table_index == normalized.table_index); } } } @@ -160,6 +227,7 @@ static bool OperatorNeedsRelation(LogicalOperatorType op_type) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: case LogicalOperatorType::LOGICAL_WINDOW: case LogicalOperatorType::LOGICAL_SAMPLE: + case LogicalOperatorType::LOGICAL_SECURE_VIEW: return true; default: return false; @@ -361,31 +429,63 @@ bool RelationManager::AddRelationWithChildren(JoinOrderOptimizer &optimizer, Log bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, LogicalOperator &input_op, vector> &filter_operators, optional_ptr parent) { + // 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}}; + bool can_reorder = true; + while (!pending_relations.empty()) { + auto relation = pending_relations.back(); + pending_relations.pop_back(); + can_reorder &= ExtractJoinRelation(optimizer, relation, filter_operators, pending_relations); + } + return can_reorder; +} + +bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, PendingRelation relation, + vector> &filter_operators, + vector &pending_relations) { + if (relation.optimize_as_leaf) { + // This job follows the left subtree, preserving relation numbering and the RHS boundary. + auto &join = *relation.parent; + RelationStats child_stats; + auto child_optimizer = optimizer.CreateChildOptimizer(); + join.children[1] = child_optimizer.Optimize(std::move(join.children[1]), &child_stats); + if (!AddRelation(*join.children[1], join, child_stats)) { + return false; + } + for (auto &binding : join.children[1]->GetColumnBindings()) { + relation_mapping[binding.table_index] = RelationIndex(relations.size() - 1); + } + return true; + } + auto &input_op = relation.op; + auto parent = relation.parent; optional_ptr op = &input_op; + vector> unary_filters; // pass through single child operators (but never past a non-reorderable op such as a DML node, which // must be preserved as its own relation rather than skipped over and dropped during reconstruction) - auto filter_chain_start = filter_operators.size(); while (op->children.size() == 1 && !OperatorNeedsRelation(op->type) && !OperatorIsNonReorderable(*op)) { if (op->type == LogicalOperatorType::LOGICAL_FILTER) { - filter_operators.push_back(*op); + unary_filters.push_back(*op); } op = op->children[0].get(); } // stacked filters are re-applied in this order: keep the lower (earlier evaluated) filters first - std::reverse(filter_operators.begin() + NumericCast(filter_chain_start), filter_operators.end()); + std::reverse(unary_filters.begin(), unary_filters.end()); bool non_reorderable_operation = false; if (OperatorIsNonReorderable(*op)) { // set operation, optimize separately in children non_reorderable_operation = true; } - if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - if (JoinIsReorderable(*op)) { - // extract join conditions from inner join + // Filters inside a leaf are already priced by its statistics and stay with that relation. + if (JoinIsReorderable(*op)) { + filter_operators.insert(filter_operators.end(), unary_filters.begin(), unary_filters.end()); + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { filter_operators.push_back(*op); - } else { - non_reorderable_operation = true; } + } else if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + non_reorderable_operation = true; } if (non_reorderable_operation) { // we encountered a non-reordable operation (setop or non-inner join) @@ -443,6 +543,36 @@ bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, Logica window.SetEstimatedCardinality(operator_stats->cardinality); return AddRelation(input_op, parent, *operator_stats); } + case LogicalOperatorType::LOGICAL_SECURE_VIEW: { + // the view is one relation: its contents are optimized on their own, and only what the view reports crosses + // the boundary - its own estimate, and the domains of its columns only if it may propagate statistics + RelationStats child_stats; + auto child_optimizer = optimizer.CreateChildOptimizer(); + op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats); + auto &secure_view = op->Cast(); + RelationStats stats; + stats.cardinality = secure_view.EstimateCardinality(context); + secure_view.SetEstimatedCardinality(stats.cardinality); + stats.table_name = Identifier(secure_view.view_name); + stats.stats_initialized = true; + if (secure_view.propagate_statistics) { + stats.row_retention = child_stats.row_retention; + } + RelationColumnStatsLookup child_columns(child_stats); + for (auto &binding : secure_view.GetColumnBindings()) { + auto child_column = child_columns.Find(binding); + auto name = child_column ? child_column->name : Identifier(); + if (child_column && secure_view.propagate_statistics) { + stats.columns.emplace_back(binding, child_column->total_domain, child_column->current_domain, + std::move(name), child_column->semi_anti_join_domain_evidence); + } else { + DistinctCount domain(MaxValue(stats.cardinality, 1), DistinctCountSource::CARDINALITY); + stats.columns.emplace_back(binding, domain, std::move(name)); + } + } + stats.CapCurrentDomainsToCardinality(); + return AddRelation(input_op, parent, stats); + } case LogicalOperatorType::LOGICAL_UNNEST: { // optimize children of unnest RelationStats child_stats; @@ -450,40 +580,18 @@ bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, Logica } case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { auto &join = op->Cast(); - // Adding relations of the left side to the current join order optimizer - bool can_reorder_left = ExtractJoinRelations(optimizer, *op->children[0], filter_operators, op); - bool can_reorder_right = true; - // For semi & anti joins, you only reorder relations in the left side of the join. - // We do not want to reorder a relation A into the right side because then all column bindings A from A will be - // lost after the semi or anti join - - // We cannot reorder a relation B out of the right side because any filter/join in the right side - // between a relation B and another RHS relation will be invalid. The semi join will remove - // all right column bindings, - - // So we treat the right side of left join as its own relation so no relations - // are pushed into the right side, or taken out of the right side. - if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || join.join_type == JoinType::LEFT) { - RelationStats child_stats; - // optimize the child and copy the stats - auto child_optimizer = optimizer.CreateChildOptimizer(); - op->children[1] = child_optimizer.Optimize(std::move(op->children[1]), &child_stats); - if (!AddRelation(*op->children[1], op, child_stats)) { - return false; - } - auto right_child_bindings = op->children[1]->GetColumnBindings(); - for (auto &bindings : right_child_bindings) { - relation_mapping[bindings.table_index] = RelationIndex(relations.size() - 1); - } - } else { - can_reorder_right = ExtractJoinRelations(optimizer, *op->children[1], filter_operators, op); - } - return can_reorder_left && can_reorder_right; + // SEMI/ANTI and LEFT RHS subtrees stay independent relations. Process the left subtree first, + // then optimize/register the RHS, just as for the recursive traversal. + auto separate_rhs = + join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || join.join_type == JoinType::LEFT; + pending_relations.push_back({*op->children[1], op, separate_rhs}); + pending_relations.push_back({*op->children[0], op, false}); + return true; } case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { - bool can_reorder_left = ExtractJoinRelations(optimizer, *op->children[0], filter_operators, op); - bool can_reorder_right = ExtractJoinRelations(optimizer, *op->children[1], filter_operators, op); - return can_reorder_left && can_reorder_right; + pending_relations.push_back({*op->children[1], op, false}); + pending_relations.push_back({*op->children[0], op, false}); + return true; } case LogicalOperatorType::LOGICAL_DUMMY_SCAN: { auto &dummy_scan = op->Cast(); @@ -672,9 +780,7 @@ bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, Logica if (delim_join.join_type == JoinType::SEMI || delim_join.join_type == JoinType::ANTI || delim_join.join_type == JoinType::RIGHT_SEMI || delim_join.join_type == JoinType::RIGHT_ANTI) { - auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(delim_join, lhs_stats, rhs_stats); - auto cardinality = LossyNumericCast(estimate.cardinality); - RelationStatisticsHelper::ApplyCardinality(dj_stats, cardinality); + RelationStatisticsHelper::ApplySemiAntiJoinStats(delim_join, lhs_stats, rhs_stats, dj_stats); } else { for (auto &column : dj_stats.columns) { column.semi_anti_join_domain_evidence.Invalidate(); @@ -1033,7 +1139,9 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, if (current.children.size() == 1) { return extract_operator_tree(*current.children[0]); } - if (current.children.size() != 2 || !JoinIsReorderable(current)) { + // The preceding extraction owns the region boundary, including read-only estimation. + if (current.children.size() != 2 || + (current.type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT && !operator_conditions.count(current))) { throw InternalException("Could not map operator %s into the extracted join-order tree", EnumUtil::ToChars(current.type)); } diff --git a/src/duckdb/src/optimizer/matcher/expression_matcher.cpp b/src/duckdb/src/optimizer/matcher/expression_matcher.cpp index c15ea00c7..03f9f6f65 100644 --- a/src/duckdb/src/optimizer/matcher/expression_matcher.cpp +++ b/src/duckdb/src/optimizer/matcher/expression_matcher.cpp @@ -59,6 +59,20 @@ bool CastExpressionMatcher::Match(Expression &expr_p, vectorMatch(*BoundCastExpression::ChildMutable(expr), bindings); } +bool NotExpressionMatcher::Match(Expression &expr_p, vector> &bindings) { + if (!ExpressionMatcher::Match(expr_p, bindings)) { + return false; + } + auto &children = expr_p.Cast().GetChildrenMutable(); + if (children.size() != 1) { + return false; + } + if (!child) { + return true; + } + return child->Match(*children[0], bindings); +} + bool InClauseExpressionMatcher::Match(Expression &expr_p, vector> &bindings) { if (!ExpressionMatcher::Match(expr_p, bindings)) { return false; diff --git a/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp b/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp index ff8524f89..21fab9393 100644 --- a/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp +++ b/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp @@ -86,18 +86,35 @@ static bool ArgumentsEqualIncludingCollation(const BoundAggregateExpression &lhs return true; } -static void AddOrderExpressions(DistinctAggregateSet &set, const BoundAggregateExpression &aggregate) { +//! ORDER BY expressions that are not arguments become extra deduplication keys of the distinct branch. +static vector> GetOrderExpressions(const BoundAggregateExpression &aggregate) { + vector> result; if (!aggregate.GetOrderBys()) { - return; + return result; } for (auto &order : aggregate.GetOrderBys()->orders) { if (FindExpression(aggregate.GetChildren(), *order.expression).IsValid()) { continue; } - if (!FindExpression(set.order_expressions, *order.expression).IsValid()) { - set.order_expressions.push_back(order.expression->Copy()); + if (!FindExpression(result, *order.expression).IsValid()) { + result.push_back(order.expression->Copy()); } } + return result; +} + +//! Extra deduplication keys change which rows are duplicates, so aggregates sharing a branch must agree on them. +static bool OrderExpressionsEqual(const vector> &lhs, + const vector> &rhs) { + if (lhs.size() != rhs.size()) { + return false; + } + for (auto &expr : lhs) { + if (!FindExpression(rhs, *expr).IsValid()) { + return false; + } + } + return true; } static unique_ptr CreateFinalAggregate(const BoundAggregateExpression &source, @@ -743,20 +760,21 @@ bool MultiStageAggregateRewriter::TryRewrite(unique_ptr &op) { } keys.push_back(std::move(key)); } + auto order_expressions = GetOrderExpressions(aggregate); bool found_match = false; for (auto &set : distinct_sets) { auto &other = aggr.expressions[set.source_index]->Cast(); if (ArgumentsEqualIncludingCollation(aggregate, other) && Expression::ListEquals(keys, set.keys) && - Expression::Equals(aggregate.GetFilter(), other.GetFilter())) { + Expression::Equals(aggregate.GetFilter(), other.GetFilter()) && + OrderExpressionsEqual(order_expressions, set.order_expressions)) { set.aggregate_indices.push_back(aggregate_idx); - AddOrderExpressions(set, aggregate); found_match = true; break; } } if (!found_match) { distinct_sets.emplace_back(aggregate_idx, std::move(keys)); - AddOrderExpressions(distinct_sets.back(), aggregate); + distinct_sets.back().order_expressions = std::move(order_expressions); } } if (distinct_sets.empty() && rewrite_sets.empty()) { diff --git a/src/duckdb/src/optimizer/optimizer.cpp b/src/duckdb/src/optimizer/optimizer.cpp index fffd9de47..b65d87f6a 100644 --- a/src/duckdb/src/optimizer/optimizer.cpp +++ b/src/duckdb/src/optimizer/optimizer.cpp @@ -32,7 +32,9 @@ #include "duckdb/optimizer/remove_unused_columns.hpp" #include "duckdb/optimizer/row_group_pruner.hpp" #include "duckdb/optimizer/sampling_pushdown.hpp" +#include "duckdb/optimizer/scalar_aggregate_merger.hpp" #include "duckdb/optimizer/scalar_fn_pushdown.hpp" +#include "duckdb/optimizer/self_join_aggregate.hpp" #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/optimizer/aggregate_function_rewriter.hpp" #include "duckdb/optimizer/aggregate_reuse.hpp" @@ -218,6 +220,20 @@ void Optimizer::RunBuiltInOptimizers() { plan = cte_inlining.Optimize(std::move(plan)); }); + // Rewrites a self-join on equal keys and one inequality, read only through its keys by a parent that ignores + // duplicates, into GROUP BY keys HAVING min(x) <> max(x) over one scan. Runs before filter pushdown, which + // would move the join's filters into the scans and hide the pattern + RunOptimizer(OptimizerType::SELF_JOIN_AGGREGATE, [&]() { + SelfJoinAggregate self_join_aggregate(*this); + plan = self_join_aggregate.Optimize(std::move(plan)); + }); + + // computes sibling scalar aggregates over the same table(s) in one pass, while their predicates are still filters + RunOptimizer(OptimizerType::SCALAR_AGGREGATE_MERGE, [&]() { + ScalarAggregateMerger scalar_aggregate_merger(*this); + scalar_aggregate_merger.Optimize(plan); + }); + // Rewrites AVG(x) -> SUM(x)/COUNT(x) and SUM(x+C) -> SUM(x) + C*COUNT(x) RunOptimizer(OptimizerType::AGGREGATE_FUNCTION_REWRITER, [&]() { AggregateFunctionRewriter aggregate_function_rewriter(*this); @@ -501,10 +517,10 @@ void Optimizer::RunBuiltInOptimizers() { partitioned_execution.Optimize(plan); }); - // perform join filter pushdown after the dust has settled + // Generate join filters before row-number and scan-expression rewrites. RunOptimizer(OptimizerType::JOIN_FILTER_PUSHDOWN, [&]() { JoinFilterPushdownOptimizer join_filter_pushdown(*this); - join_filter_pushdown.VisitOperator(*plan); + join_filter_pushdown.Optimize(*plan); }); // Rewrite ROW_NUMBER() OVER() window functions to use the row_number virtual column diff --git a/src/duckdb/src/optimizer/projection_pullup.cpp b/src/duckdb/src/optimizer/projection_pullup.cpp index f09b5bafb..1883c4b17 100644 --- a/src/duckdb/src/optimizer/projection_pullup.cpp +++ b/src/duckdb/src/optimizer/projection_pullup.cpp @@ -178,6 +178,10 @@ void ProjectionPullup::PullUpNonColrefProjection(unique_ptr &op } } } + + // The caller's traversal no longer reaches the subtree left behind by the moved projection. + ProjectionPullup next(optimizer, root); + next.Optimize(op); } static bool HasJoinBelow(const LogicalOperator &op) { diff --git a/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp b/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp index c2014de7d..8c6ccb2e5 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp @@ -7,7 +7,8 @@ namespace duckdb { unique_ptr FilterPullup::PullupFromLeft(unique_ptr op) { D_ASSERT(op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || op->type == LogicalOperatorType::LOGICAL_ASOF_JOIN || op->type == LogicalOperatorType::LOGICAL_ANY_JOIN || - op->type == LogicalOperatorType::LOGICAL_EXCEPT || op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN); + op->type == LogicalOperatorType::LOGICAL_EXCEPT || op->type == LogicalOperatorType::LOGICAL_INTERSECT || + op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN); FilterPullup left_pullup(true, can_add_column); FilterPullup right_pullup(false, can_add_column); diff --git a/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp b/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp index 83515d4c9..26afade5c 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp @@ -20,12 +20,8 @@ unique_ptr FilterPullup::PullupSetOperation(unique_ptrtype == LogicalOperatorType::LOGICAL_INTERSECT || op->type == LogicalOperatorType::LOGICAL_EXCEPT); can_add_column = false; can_pullup = true; - if (op->type == LogicalOperatorType::LOGICAL_INTERSECT) { - op = PullupBothSide(std::move(op)); - } else { - // EXCEPT only pull ups from LHS - op = PullupFromLeft(std::move(op)); - } + // EXCEPT and INTERSECT return rows of the left child, so a filter of the right child does not apply to them + op = PullupFromLeft(std::move(op)); if (op->type == LogicalOperatorType::LOGICAL_FILTER) { auto &filter = op->Cast(); auto &setop = filter.children[0]->Cast(); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp index 21009431e..d09711663 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp @@ -12,9 +12,20 @@ using Filter = FilterPushdown::Filter; unique_ptr FilterPushdown::PushdownSemiAntiJoin(unique_ptr op) { auto &join = op->Cast(); + FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && !filters.empty()) { + // a right row that matches a left row passes what the filters imply for the right side + vector> left_filters; + for (auto &filter : filters) { + left_filters.push_back(*filter->filter); + } + FilterCombiner::GenerateJoinFilters( + op->Cast().conditions, left_filters, JoinSide::RIGHT, + [&](unique_ptr right_filter) { right_pushdown.AddFilter(std::move(right_filter)); }); + right_pushdown.GenerateFilters(); + } // push all current filters down the left side op->children[0] = Rewrite(std::move(op->children[0])); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); bool left_empty = op->children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT; @@ -23,8 +34,6 @@ unique_ptr FilterPushdown::PushdownSemiAntiJoin(unique_ptr(std::move(op)); } - // TODO: if semi/anti join is created from a intersect/except statement, then we can - // push filters down into both children. // filter pushdown happens before join order optimization, so right_anti and right_semi are not possible yet here if (left_empty) { // left child is empty result diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp index 134df56fb..f550e5667 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp @@ -29,10 +29,16 @@ unique_ptr FilterPushdown::PushdownSetOperation(unique_ptrtype == LogicalOperatorType::LOGICAL_INTERSECT); auto &setop = op->Cast(); - for (auto &child : op->children) { + for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { + auto &child = op->children[child_idx]; auto child_bindings = child->GetColumnBindings(); FilterPushdown child_pushdown(optimizer, convert_mark_joins, projection_mode); + // a filter on the result of EXCEPT and INTERSECT only applies to their left child + if (child_idx > 0 && op->type != LogicalOperatorType::LOGICAL_UNION) { + child = child_pushdown.Rewrite(std::move(child)); + continue; + } for (auto &original_filter : filters) { // first create a copy of the filter auto filter = make_uniq(); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp index ddfb40889..dd5a6a894 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/function/window_function.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -111,8 +112,51 @@ unique_ptr CreateAuxiliaryFilter(const Expression &partition, const Filt return aux_filter; } +bool IsPartition(const Expression &partition, const Expression &expr) { + if (partition.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + return partition.Cast().Binding() == expr.Cast().Binding(); + } + return partition.Equals(expr); +} + } // namespace +bool FilterPushdown::ComparesWindowPartitions(const LogicalWindow &window, const Expression &filter) { + auto compared = FilterCombiner::GetComparedExpression(filter); + if (!compared || window.expressions.empty()) { + return false; + } + for (auto &expr : window.expressions) { + if (expr->GetExpressionClass() != ExpressionClass::BOUND_WINDOW) { + return false; + } + bool partitions_by_compared = false; + for (auto &partition : expr->Cast().Partitions()) { + partitions_by_compared = partitions_by_compared || IsPartition(*partition, *compared); + } + if (!partitions_by_compared) { + return false; + } + } + return true; +} + +bool FilterPushdown::OnlyRanksWithoutArguments(const LogicalWindow &window) { + for (auto &expr : window.expressions) { + if (expr->GetExpressionClass() != ExpressionClass::BOUND_WINDOW || expr->IsVolatile() || expr->CanThrow()) { + return false; + } + auto &window_expr = expr->Cast(); + if (!window_expr.WindowFunction() || !window_expr.WindowFunction()->IsRanking() || + window_expr.AggregateFunction() || !window_expr.GetChildren().empty() || window_expr.Filter() || + window_expr.StartExpr() || window_expr.EndExpr()) { + return false; + } + } + return true; +} + unique_ptr FilterPushdown::PushdownWindow(unique_ptr op) { D_ASSERT(op->type == LogicalOperatorType::LOGICAL_WINDOW); auto &window = op->Cast(); @@ -168,12 +212,17 @@ unique_ptr FilterPushdown::PushdownWindow(unique_ptr> leftover_filters; for (idx_t i = 0; i < filters.size(); i++) { // If a filter is on a partition in every window expression it can be pushed down. vector bindings; ExtractFilterBindings(*filters.at(i)->filter, bindings); - if (CanPushdownFilter(window_exprs_partition_bindings, bindings) && !filters.at(i)->filter->IsVolatile()) { + // Also a filter that compares a partition expression of every window expression with constants, when the + // window expressions can run for fewer partitions. + if ((CanPushdownFilter(window_exprs_partition_bindings, bindings) || + (only_ranks && ComparesWindowPartitions(window, *filters.at(i)->filter))) && + !filters.at(i)->filter->IsVolatile()) { pushdown.filters.push_back(std::move(filters.at(i))); continue; } 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 48411609e..c3563e809 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp @@ -2,6 +2,9 @@ #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" #include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" namespace duckdb { @@ -37,6 +40,16 @@ idx_t RelationStatsExtractor::ExtractedOperatorCount() const { return extracted_operator_count; } +static bool IsInnerJoinRegion(LogicalOperator &op) { + optional_ptr root = op; + while (root->type == LogicalOperatorType::LOGICAL_FILTER) { + root = *root->children[0]; + } + return root->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT || + (root->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + root->Cast().join_type == JoinType::INNER); +} + optional RelationStatsExtractor::ExtractInternal(LogicalOperator &op) { if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { return ExtractCTERef(op.Cast()); @@ -45,6 +58,13 @@ optional RelationStatsExtractor::ExtractInternal(LogicalOperator return RelationStatisticsHelper::ExtractExplainStats(op); } + if (IsInnerJoinRegion(op)) { + auto stats = ExtractJoinStats(op); + if (stats) { + return stats; + } + } + vector> child_stats; child_stats.reserve(op.children.size()); for (auto &child : op.children) { @@ -54,9 +74,32 @@ optional RelationStatsExtractor::ExtractInternal(LogicalOperator } child_stats.push_back(*stats); } + if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY && child_stats.size() == 1) { + return RelationStatisticsHelper::ExtractAggregationStats(op.Cast(), child_stats[0], *this); + } return RelationStatisticsHelper::ExtractOperatorStats(op, context, child_stats); } +optional RelationStatsExtractor::ExtractJoinStats(LogicalOperator &op) { + QueryGraphManager graph(context); + if (!graph.BuildForEstimation(*this, op)) { + return {}; + } + auto relation_stats = graph.relation_manager.GetRelationStats(); + CardinalityEstimator estimator(graph.set_manager, graph.GetPredicateModel()); + estimator.Initialize(relation_stats, graph.GetJoinOperators()); + unordered_set relations; + for (idx_t i = 0; i < relation_stats.size(); i++) { + relations.insert(RelationIndex(i)); + } + auto &set = graph.set_manager.GetJoinRelation(relations); + auto estimate = estimator.EstimateCardinality(set); + if (estimate.GetDouble() >= static_cast(NumericLimits::Maximum())) { + return {}; + } + return graph.CombineRelationStats(op.GetColumnBindings(), relation_stats, estimate.GetIndex()); +} + optional RelationStatsExtractor::ExtractCTERef(LogicalCTERef &cte_ref) { if (cte_ref.is_recurring || !cte_callback) { 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 e2dfe1bf2..2cfc06c0a 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -46,6 +46,16 @@ optional RelationStatisticsHelper::SelectTotalDomain(const vector return fallback; } +idx_t RelationStatisticsHelper::CardinalityFromDouble(double cardinality) { + if (!(cardinality > 0)) { + return 0; + } + if (cardinality >= static_cast(NumericLimits::Maximum())) { + return NumericLimits::Maximum(); + } + return LossyNumericCast(cardinality); +} + static bool MatchesTargetColumn(const Expression &expression, optional target_binding) { if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { return !target_binding || expression.Cast().Binding() == *target_binding; @@ -222,7 +232,7 @@ idx_t RelationStatisticsHelper::EstimateDistinctCardinality(const vector(distinct_counts.size() - 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 = LossyNumericCast(MinValue(estimate, static_cast(input_cardinality))); + auto result = MinValue(CardinalityFromDouble(estimate), input_cardinality); return input_cardinality > 0 ? MaxValue(result, 1) : 0; } @@ -240,7 +250,7 @@ DistinctCount RelationStatisticsHelper::EstimateCurrentDomain(const DistinctCoun const auto multiplicity = static_cast(input_cardinality) / static_cast(count); const auto retained_fraction = -expm1(multiplicity * log1p(-row_survival)); const auto estimate = round(static_cast(count) * retained_fraction); - auto result = LossyNumericCast(MinValue(estimate, static_cast(output_cardinality))); + auto result = MinValue(CardinalityFromDouble(estimate), output_cardinality); result = MinValue(result, count); return DistinctCount(MaxValue(result, 1), DistinctCountSource::CARDINALITY); } @@ -272,14 +282,7 @@ static double RoundSemiAntiCardinality(double preserved_cardinality, double sele SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinFallback(double preserved_cardinality, idx_t rhs_cardinality, JoinType join_type) { - auto is_anti = join_type == JoinType::ANTI || join_type == JoinType::RIGHT_ANTI; - if (rhs_cardinality == 0) { - return {is_anti ? MaxValue(0.0, preserved_cardinality) : 0, false}; - } - // Keep fractional estimates while composing costs. Rounding a small preserved input - // can otherwise make equivalent selectivities depend on where the SEMI/ANTI is placed. - auto estimate = MinValue(preserved_cardinality, MaxValue(1.0, preserved_cardinality * DEFAULT_SELECTIVITY)); - return {MaxValue(0.0, estimate), false}; + return {EstimateSemiAntiJoinFallbackCardinality(preserved_cardinality, rhs_cardinality, join_type), false}; } static constexpr double MAX_BASE_CARDINALITY_TO_DOMAIN_RATIO = 8; @@ -327,8 +330,7 @@ SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCa } static optional_idx EstimateUnionGroups(LogicalOperator &input, vector groups, idx_t maximum, - ClientContext &context) { - RelationStatsExtractor extractor(context); + RelationStatsExtractor &extractor, bool use_cached_cardinality) { vector, vector>> pending; pending.emplace_back(input, std::move(groups)); idx_t result = 0; @@ -373,7 +375,8 @@ static optional_idx EstimateUnionGroups(LogicalOperator &input, vector gr if (!stats) { return {}; } - auto cardinality = op.has_estimated_cardinality ? op.estimated_cardinality : stats->cardinality; + auto cardinality = + use_cached_cardinality && op.has_estimated_cardinality ? op.estimated_cardinality : stats->cardinality; auto estimate = MinValue(cardinality, 1); for (auto index : entry.second) { auto domain = MaxValue(stats->columns[index].current_domain.distinct_count, 1); @@ -388,9 +391,10 @@ static optional_idx EstimateUnionGroups(LogicalOperator &input, vector gr return optional_idx(result); } -optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, - const RelationStats &child_stats, - ClientContext &context) { +static optional ExtractAggregationStatsInternal(LogicalAggregate &aggregate, + const RelationStats &child_stats, + RelationStatsExtractor &extractor, + bool use_cached_cardinality) { RelationColumnStatsLookup child_columns(child_stats); vector cardinality_counts; for (auto &grouping_set : aggregate.grouping_sets) { @@ -415,7 +419,9 @@ optional RelationStatisticsHelper::ExtractAggregationStats(Logica RelationStats result; result.cardinality = - aggregate.groups.empty() ? 1 : EstimateDistinctCardinality(cardinality_counts, child_stats.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(); @@ -427,8 +433,8 @@ optional RelationStatisticsHelper::ExtractAggregationStats(Logica 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, context); + 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()); @@ -476,6 +482,20 @@ optional RelationStatisticsHelper::ExtractAggregationStats(Logica return result; } +optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, + const RelationStats &child_stats, + ClientContext &context) { + // Join reconstruction has already published the selected input cardinalities. + RelationStatsExtractor extractor(context); + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor, true); +} + +optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, + const RelationStats &child_stats, + RelationStatsExtractor &extractor) { + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor, false); +} + optional RelationStatisticsHelper::ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats) { RelationStats result; @@ -573,33 +593,6 @@ optional RelationStatisticsHelper::ExtractDistinctStats(LogicalDi return result; } -optional RelationStatisticsHelper::ExtractFilterStats(LogicalFilter &filter, - const RelationStats &child_stats) { - auto result = ProjectOutputStats(child_stats, filter); - if (!result) { - return {}; - } - auto cardinality = child_stats.cardinality; - if (cardinality > 0) { - cardinality = MaxValue(LossyNumericCast(double(cardinality) * DEFAULT_SELECTIVITY), 1); - } - ApplyCardinality(*result, cardinality); - for (auto &column : result->columns) { - for (auto &expression : filter.expressions) { - auto direct_bound = - EstimateDirectFilterDomain(*expression, column.binding, column.total_domain.distinct_count); - if (!direct_bound.IsValid()) { - continue; - } - column.current_domain = - DistinctCount(MinValue(column.current_domain.distinct_count, direct_bound.GetIndex()), - DistinctCountSource::CARDINALITY); - column.semi_anti_join_domain_evidence.TightenFilterDomainBound(direct_bound.GetIndex()); - } - } - return result; -} - optional RelationStatisticsHelper::ExtractLimitStats(LogicalLimit &limit, const RelationStats &child_stats) { auto result = ProjectOutputStats(child_stats, limit); diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp index 4bd4c2d7c..3d601a7e3 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" +#include "duckdb/optimizer/join_order/join_predicate.hpp" #include "duckdb/planner/operator/list.hpp" namespace duckdb { @@ -44,20 +45,15 @@ static idx_t JoinCardinality(LogicalComparisonJoin &join, const RelationStats &l } static optional_ptr GetJoinColumn(const Expression &expression, const RelationStats &stats) { - if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return nullptr; - } - return stats.GetColumnStats(expression.Cast().Binding()); + auto binding = JoinOrderUtil::GetEquivalenceBinding(expression); + return binding.table_index.IsValid() ? stats.GetColumnStats(binding) : nullptr; } -SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(LogicalComparisonJoin &join, - const RelationStats &left, - const RelationStats &right) { - auto preserve_right = join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI; - auto &preserved = preserve_right ? right : left; - auto &rhs = preserve_right ? left : right; +static vector ExtractSemiAntiJoinDomains(LogicalComparisonJoin &join, + const RelationStats &preserved, const RelationStats &rhs, + bool &has_residual) { vector domains; - bool has_residual = false; + has_residual = false; for (auto &condition : join.conditions) { if (!condition.IsComparison() || (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { @@ -89,7 +85,8 @@ SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCa has_residual = true; continue; } - auto total_domain = SelectTotalDomain({lhs_preserved->total_domain, rhs_column->total_domain}); + auto total_domain = + RelationStatisticsHelper::SelectTotalDomain({lhs_preserved->total_domain, rhs_column->total_domain}); if (!total_domain || total_domain->distinct_count == 0) { has_residual = true; continue; @@ -97,10 +94,54 @@ SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCa domains.push_back( {total_domain->distinct_count, rhs_current_domain.GetIndex(), lhs_preserved->binding, rhs_column->binding}); } + return domains; +} + +SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(LogicalComparisonJoin &join, + const RelationStats &left, + const RelationStats &right) { + auto preserve_right = join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI; + auto &preserved = preserve_right ? right : left; + auto &rhs = preserve_right ? left : right; + bool has_residual; + auto domains = ExtractSemiAntiJoinDomains(join, preserved, rhs, has_residual); return EstimateSemiAntiJoinCardinality(static_cast(preserved.cardinality), rhs.cardinality, rhs.row_retention, join.join_type, domains, has_residual); } +void RelationStatisticsHelper::ApplySemiAntiJoinStats(LogicalComparisonJoin &join, const RelationStats &left, + const RelationStats &right, RelationStats &result) { + auto preserve_right = join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI; + auto &preserved = preserve_right ? right : left; + auto &rhs = preserve_right ? left : right; + D_ASSERT(join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || + join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI); + D_ASSERT(result.cardinality == preserved.cardinality); + bool has_residual; + auto domains = ExtractSemiAntiJoinDomains(join, preserved, rhs, has_residual); + auto estimate = EstimateSemiAntiJoinCardinality(static_cast(preserved.cardinality), rhs.cardinality, + rhs.row_retention, join.join_type, domains, has_residual); + result.row_retention = preserved.row_retention; + // Keep exact empty-input results and the original integer upper limit across double conversion. + auto cardinality = MinValue(preserved.cardinality, CardinalityFromDouble(estimate.cardinality)); + if (rhs.cardinality == 0 && (join.join_type == JoinType::ANTI || join.join_type == JoinType::RIGHT_ANTI)) { + cardinality = preserved.cardinality; + } + ApplyCardinality(result, cardinality); + if (join.join_type == JoinType::SEMI || join.join_type == JoinType::RIGHT_SEMI) { + for (auto &domain : domains) { + auto column_index = result.FindColumn(domain.preserved_binding); + if (!column_index.IsValid()) { + continue; + } + auto &column = result.columns[column_index.GetIndex()]; + column.current_domain = + DistinctCount(MinValue(column.current_domain.distinct_count, domain.rhs_current_domain), + DistinctCountSource::CARDINALITY); + } + } +} + static optional ExtractGetWithChildStats(LogicalGet &get, ClientContext &context, const RelationStats &child_stats) { auto result = RelationStatisticsHelper::ExtractGetStats(get, context); @@ -158,10 +199,7 @@ static optional ExtractComparisonJoinStats(LogicalComparisonJoin if (!result) { return {}; } - result->row_retention = preserved.row_retention; - auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(join, child_stats[0], child_stats[1]); - auto cardinality = LossyNumericCast(estimate.cardinality); - RelationStatisticsHelper::ApplyCardinality(*result, cardinality); + RelationStatisticsHelper::ApplySemiAntiJoinStats(join, child_stats[0], child_stats[1], *result); result->Verify(join.GetColumnBindings()); return result; } @@ -340,6 +378,8 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex } return ExtractFilterStats(op.Cast(), child_stats[0].get()); } + case LogicalOperatorType::LOGICAL_ORDER_BY: + return child_stats.size() == 1 ? ProjectOutputStats(child_stats[0].get(), op) : optional(); case LogicalOperatorType::LOGICAL_UNNEST: return ExtractUnnestStats(op, child_stats[0].get()); case LogicalOperatorType::LOGICAL_LIMIT: { diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp index 929c809e5..e1b9f51ec 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp @@ -5,12 +5,17 @@ #include "duckdb/common/operator/subtract.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/function/table/table_scan.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/operator/logical_delim_get.hpp" #include "duckdb/planner/operator/logical_column_data_get.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/storage/statistics/numeric_stats.hpp" @@ -110,6 +115,263 @@ static DistinctCount GetDistinctCountFromStats(BaseStatistics &base_stats, idx_t return DistinctCount(0, DistinctCountSource::CARDINALITY); } +struct FilterEstimate { + idx_t cardinality; + bool supported; + + void Combine(const FilterEstimate &other) { + cardinality = MinValue(cardinality, other.cardinality); + supported &= other.supported; + } +}; + +static idx_t FilterFraction(idx_t cardinality, double fraction) { + if (cardinality == 0) { + return 0; + } + return MinValue(cardinality, MaxValue(1, RelationStatisticsHelper::CardinalityFromDouble( + double(cardinality) * fraction))); +} + +class IntegerRangeEstimate { +public: + explicit IntegerRangeEstimate(const BaseStatistics &statistics) : statistics(statistics) { + } + + bool AddBound(ExpressionType comparison, const Value &constant) { + if (constant.IsNull() || !constant.type().EqualsIncludingCollation(statistics.GetType()) || + statistics.GetStatsType() != StatisticsType::NUMERIC_STATS || !NumericStats::HasMinMax(statistics)) { + return false; + } + switch (constant.type().id()) { + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + case LogicalTypeId::UBIGINT: + break; + default: + return false; + } + if (!has_bounds) { + lower = NumericStats::Min(statistics).GetValue(); + upper = NumericStats::Max(statistics).GetValue(); + if (lower > upper) { + return false; + } + // Widen before endpoint arithmetic: a complete 64-bit interval has 2^64 values. + count = upper - lower + 1; + has_bounds = true; + } + auto value = constant.GetValue(); + switch (comparison) { + case ExpressionType::COMPARE_LESSTHAN: + upper = MinValue(upper, value - 1); + break; + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + upper = MinValue(upper, value); + break; + case ExpressionType::COMPARE_GREATERTHAN: + lower = MaxValue(lower, value + 1); + break; + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + lower = MaxValue(lower, value); + break; + default: + throw InternalException("Expected a range comparison"); + } + return true; + } + + optional Fraction() const { + if (!has_bounds) { + return {}; + } + auto matching = MaxValue(hugeint_t(0), upper - lower + 1); + return Hugeint::Cast(matching) / Hugeint::Cast(count); + } + +private: + const BaseStatistics &statistics; + hugeint_t lower; + hugeint_t upper; + hugeint_t count; + bool has_bounds = false; +}; + +static optional_ptr FilterColumn(const Expression &expr, + const RelationColumnStatsLookup &columns, + const vector &positional_bindings) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &ref = expr.Cast(); + return ref.Depth() == 0 ? columns.Find(ref.Binding()) : nullptr; + } + if (expr.GetExpressionClass() == ExpressionClass::BOUND_REF) { + auto index = expr.Cast().Index(); + if (index < positional_bindings.size()) { + return columns.Find(positional_bindings[index]); + } + } + return nullptr; +} + +static FilterEstimate EstimateNullCheckRows(idx_t cardinality, const BoundOperatorExpression &expr, + const RelationColumnStatsLookup &columns, + const vector &positional_bindings) { + auto &children = expr.GetChildren(); + if (children.size() != 1 || !FilterColumn(*children[0], columns, positional_bindings)) { + return {cardinality, false}; + } + const auto selectivity = RelationStatisticsHelper::DEFAULT_SELECTIVITY; + return {FilterFraction(cardinality, expr.GetExpressionType() == ExpressionType::OPERATOR_IS_NULL ? selectivity + : 1 - selectivity), + true}; +} + +static FilterEstimate EstimateEqualityRows(idx_t cardinality, ExpressionType type, const RelationColumnStats &column) { + const auto selectivity = RelationStatisticsHelper::DEFAULT_SELECTIVITY; + bool equal = type == ExpressionType::COMPARE_EQUAL || type == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + if (cardinality == 0) { + return {0, true}; + } + if (column.total_domain.source == DistinctCountSource::CARDINALITY) { + return {FilterFraction(cardinality, equal ? selectivity : 1 - selectivity), true}; + } + auto domain = MinValue(cardinality, column.current_domain.distinct_count); + if (domain == 0) { + return {cardinality, false}; + } + return {equal ? cardinality / domain + (cardinality % domain != 0) + : FilterFraction(cardinality, 1 - 1.0 / double(domain)), + true}; +} + +static FilterEstimate EstimateComparisonRows(idx_t cardinality, const BoundFunctionExpression &comparison, + const RelationColumnStatsLookup &columns, + const vector &positional_bindings, + FilterPropagateResult pruning, optional_ptr range) { + const auto selectivity = RelationStatisticsHelper::DEFAULT_SELECTIVITY; + auto &children = comparison.GetChildren(); + auto type = comparison.GetExpressionType(); + auto column = FilterColumn(*children[0], columns, positional_bindings); + optional_ptr value = *children[1]; + if (!column) { + column = FilterColumn(*children[1], columns, positional_bindings); + value = *children[0]; + type = FlipComparisonExpression(type); + } + if (!column || (value->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT && + value->GetExpressionClass() != ExpressionClass::BOUND_PARAMETER)) { + return {cardinality, false}; + } + if (value->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && + value->Cast().GetValue().IsNull()) { + if (type == ExpressionType::COMPARE_NOT_DISTINCT_FROM || type == ExpressionType::COMPARE_DISTINCT_FROM) { + return {FilterFraction(cardinality, + type == ExpressionType::COMPARE_NOT_DISTINCT_FROM ? selectivity : 1 - selectivity), + true}; + } + return {0, true}; + } + if (pruning == FilterPropagateResult::FILTER_TRUE_OR_NULL && type != ExpressionType::COMPARE_DISTINCT_FROM && + type != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return {FilterFraction(cardinality, 1 - selectivity), true}; + } + switch (type) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOTEQUAL: + case ExpressionType::COMPARE_DISTINCT_FROM: + case ExpressionType::COMPARE_NOT_DISTINCT_FROM: + return EstimateEqualityRows(cardinality, type, *column); + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + if (range && value->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && + range->AddBound(type, value->Cast().GetValue())) { + return {cardinality, true}; + } + return {FilterFraction(cardinality, selectivity), true}; + default: + return {cardinality, false}; + } +} + +static FilterEstimate EstimateFilterRows(idx_t cardinality, const Expression &expr, + const RelationColumnStatsLookup &columns, + const vector &positional_bindings, + optional_ptr context = nullptr, + optional_ptr scan_statistics = nullptr, + optional_ptr range = nullptr) { + if (ExpressionFilter::IsRootOptionalExpression(expr)) { + return {cardinality, true}; + } + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + FilterEstimate result {cardinality, true}; + for (auto &child : expr.Cast().GetChildren()) { + result.Combine( + EstimateFilterRows(cardinality, *child, columns, positional_bindings, context, scan_statistics, range)); + } + return result; + } + auto pruning = FilterPropagateResult::NO_PRUNING_POSSIBLE; + if (scan_statistics && !expr.HasParameter()) { + pruning = ExpressionFilter::CheckExpressionStatistics(context, expr, *scan_statistics); + if (pruning == FilterPropagateResult::FILTER_ALWAYS_TRUE) { + return {cardinality, true}; + } + if (pruning == FilterPropagateResult::FILTER_ALWAYS_FALSE || + pruning == FilterPropagateResult::FILTER_FALSE_OR_NULL) { + return {0, true}; + } + } + if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && expr.GetReturnType() == LogicalType::BOOLEAN) { + auto &value = expr.Cast().GetValue(); + return {value.IsNull() || !BooleanValue::Get(value) ? 0 : cardinality, true}; + } + // Preserve the existing scan-specific non-null NOT LIKE estimate. + if (scan_statistics && expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION && + expr.Cast().Function().GetName() == "!~~" && !scan_statistics->CanHaveNull()) { + return {FilterFraction(cardinality, 1 - RelationStatisticsHelper::DEFAULT_SELECTIVITY), true}; + } + if (expr.GetExpressionType() == ExpressionType::OPERATOR_IS_NULL || + expr.GetExpressionType() == ExpressionType::OPERATOR_IS_NOT_NULL) { + return EstimateNullCheckRows(cardinality, expr.Cast(), columns, positional_bindings); + } + if (BoundComparisonExpression::IsComparison(expr)) { + return EstimateComparisonRows(cardinality, expr.Cast(), columns, positional_bindings, + pruning, range); + } + return {cardinality, false}; +} + +static void ApplyFilterEstimate(RelationStats &stats, FilterEstimate estimate) { + if (!estimate.supported) { + // An unsupported conjunct retains its fallback even when another conjunct has a weaker estimate. + estimate.cardinality = MinValue( + estimate.cardinality, FilterFraction(stats.cardinality, RelationStatisticsHelper::DEFAULT_SELECTIVITY)); + } + RelationStatisticsHelper::ApplyCardinality(stats, estimate.cardinality); +} + +static void ApplyFilterDomainCap(RelationColumnStats &column, optional_idx cap) { + if (!cap.IsValid()) { + return; + } + column.current_domain = + DistinctCount(MinValue(column.current_domain.distinct_count, cap.GetIndex()), DistinctCountSource::CARDINALITY); + column.semi_anti_join_domain_evidence.TightenFilterDomainBound(cap.GetIndex()); +} + +static void ApplyDirectFilterDomain(RelationColumnStats &column, const Expression &expression, + optional binding) { + ApplyFilterDomainCap(column, RelationStatisticsHelper::EstimateDirectFilterDomain( + expression, binding, column.total_domain.distinct_count)); +} + unique_ptr RelationStatisticsHelper::GetColumnStatistics(LogicalGet &get, ClientContext &context, const ColumnIndex &column_id) { if (!get.bind_data || (!get.function.statistics && !get.function.statistics_extended)) { @@ -125,45 +387,14 @@ unique_ptr RelationStatisticsHelper::GetColumnStatistics(Logical RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientContext &context) { RelationStats result; auto base_table_cardinality = get.EstimateSourceCardinality(context); - auto cardinality_after_filters = base_table_cardinality; + 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()); - if (get.table_filters.HasFilters()) { - bool has_non_optional_filters = false; - for (auto &entry : get.table_filters) { - auto &column_index = get.GetColumnIndex(entry.GetIndex()); - auto column_statistics = GetColumnStatistics(get, context, column_index); - if (column_statistics) { - auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "ExtractGetStats"); - if (filter.column_indexes.size() <= 1 && - filter.CheckStatistics(context, *column_statistics) == FilterPropagateResult::FILTER_ALWAYS_TRUE) { - continue; - } - cardinality_after_filters = - MinValue(cardinality_after_filters, - InspectTableFilter(base_table_cardinality, entry.Filter(), *column_statistics)); - } - if (!ExpressionFilter::IsOptionalFilter(entry.Filter())) { - has_non_optional_filters = true; - } - } - if (cardinality_after_filters == base_table_cardinality && has_non_optional_filters) { - cardinality_after_filters = - MaxValue(LossyNumericCast(double(base_table_cardinality) * DEFAULT_SELECTIVITY), 1); - } - if (base_table_cardinality == 0) { - cardinality_after_filters = 0; - } - } - - result.cardinality = cardinality_after_filters; - result.row_retention = base_table_cardinality == 0 - ? 0 - : MinValue(1.0, double(cardinality_after_filters) / double(base_table_cardinality)); - for (auto &binding : get.GetColumnBindings()) { - if (binding.table_index != get.table_index) { - continue; - } + // Include hidden filter columns, and acquire each scanned column's provider statistics once. + vector scan_statistics; + for (idx_t i = 0; i < MaxValue(1, get.GetColumnIds().size()); i++) { + ColumnBinding binding(get.table_index, ProjectionIndex(i)); ColumnIndex fallback_column(get.GetAnyColumn()); auto column_id = get.GetColumnIds().empty() ? fallback_column : get.GetColumnIndex(binding); auto column_statistics = GetColumnStatistics(get, context, column_id); @@ -172,28 +403,72 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC if (total_domain.distinct_count == 0) { total_domain = DistinctCount(base_table_cardinality, DistinctCountSource::CARDINALITY); } - auto current_domain = EstimateCurrentDomain(total_domain, base_table_cardinality, cardinality_after_filters); - SemiAntiJoinDomainEvidence semi_anti_join_domain_evidence; + result.columns.emplace_back(binding, total_domain, + Identifier(get.GetName() + "." + get.GetColumnName(column_id))); + if (column_statistics && column_statistics->GetType().EqualsIncludingCollation(get.GetColumnType(column_id))) { + scan_statistics.push_back(std::move(*column_statistics)); + } else { + scan_statistics.push_back(BaseStatistics::CreateUnknown(get.GetColumnType(column_id))); + } + } + RelationColumnStatsLookup columns(result); + FilterEstimate estimate {base_table_cardinality, true}; + for (auto &entry : get.table_filters) { + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "ExtractGetStats"); + vector bindings {ColumnBinding(get.table_index, entry.GetIndex())}; + D_ASSERT(filter.column_indexes.size() <= 1); + auto &statistics = scan_statistics[entry.GetIndex().GetIndex()]; + IntegerRangeEstimate range(statistics); + estimate.Combine( + EstimateFilterRows(base_table_cardinality, *filter.expr, columns, bindings, context, statistics, range)); + auto fraction = range.Fraction(); + if (fraction) { + // Intersect same-column bounds before applying the default-selectivity floor. + auto range_cardinality = + *fraction == 0 ? 0 : FilterFraction(base_table_cardinality, MaxValue(DEFAULT_SELECTIVITY, *fraction)); + estimate.Combine({range_cardinality, true}); + } + } + ApplyFilterEstimate(result, estimate); + for (auto &column : result.columns) { for (auto &entry : get.table_filters) { - if (ExpressionFilter::IsOptionalFilter(entry.Filter()) || - get.GetColumnIndex(entry.GetIndex()) != column_id) { + if (ExpressionFilter::IsOptionalFilter(entry.Filter()) || entry.GetIndex() != column.binding.column_index) { continue; } - auto &filter = - ExpressionFilter::GetExpressionFilter(entry.Filter(), "RelationStatisticsHelper::ExtractGetStats"); - auto direct_bound = EstimateDirectFilterDomain(*filter.expr, {}, total_domain.distinct_count); - if (direct_bound.IsValid()) { - current_domain = DistinctCount(MinValue(current_domain.distinct_count, direct_bound.GetIndex()), - DistinctCountSource::CARDINALITY); - semi_anti_join_domain_evidence.TightenFilterDomainBound(direct_bound.GetIndex()); - } + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "ExtractGetStats"); + ApplyDirectFilterDomain(column, *filter.expr, {}); + } + } + vector output_columns; + for (auto binding : get.GetColumnBindings()) { + if (binding.table_index == get.table_index) { + output_columns.push_back(result.columns[binding.column_index.GetIndex()]); } - result.columns.emplace_back(binding, total_domain, current_domain, - Identifier(get.GetName() + "." + get.GetColumnName(column_id)), - semi_anti_join_domain_evidence); } + result.columns = std::move(output_columns); result.stats_initialized = true; - D_ASSERT(base_table_cardinality >= cardinality_after_filters); + D_ASSERT(base_table_cardinality >= result.cardinality); + return result; +} + +optional RelationStatisticsHelper::ExtractFilterStats(LogicalFilter &filter, + const RelationStats &child_stats) { + auto result = ProjectOutputStats(child_stats, filter); + if (!result) { + return {}; + } + RelationColumnStatsLookup columns(child_stats); + auto bindings = filter.children[0]->GetColumnBindings(); + FilterEstimate estimate {child_stats.cardinality, true}; + for (auto &expression : filter.expressions) { + estimate.Combine(EstimateFilterRows(child_stats.cardinality, *expression, columns, bindings)); + } + ApplyFilterEstimate(*result, estimate); + for (auto &column : result->columns) { + for (auto &expression : filter.expressions) { + ApplyDirectFilterDomain(column, *expression, column.binding); + } + } return result; } @@ -206,6 +481,7 @@ RelationStats RelationStatisticsHelper::ExtractDelimGetStats(LogicalDelimGet &de result.columns.emplace_back(binding, DistinctCount(1, DistinctCountSource::CARDINALITY), Identifier("column" + to_string(binding.column_index))); } + result.CapCurrentDomainsToCardinality(); result.Verify(delim_get.GetColumnBindings()); return result; } @@ -251,42 +527,4 @@ RelationStats RelationStatisticsHelper::ExtractColumnDataGetStats(LogicalColumnD return result; } -idx_t RelationStatisticsHelper::InspectTableFilter(idx_t cardinality, const TableFilter &filter, - BaseStatistics &base_stats) { - auto cardinality_after_filters = cardinality; - auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "RelationStatisticsHelper::InspectTableFilter"); - auto &expr = *expr_filter.expr; - if (expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { - auto &function = expr.Cast(); - if (function.Function().GetName() == "!~~" && !base_stats.CanHaveNull()) { - if (cardinality == 0) { - return 0; - } - return MaxValue( - LossyNumericCast(static_cast(cardinality) * (1.0 - DEFAULT_SELECTIVITY)), 1); - } - } - if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { - auto &conjunction = expr.Cast(); - for (auto &child : conjunction.GetChildren()) { - ExpressionFilter child_filter(child->Copy()); - cardinality_after_filters = - MinValue(cardinality_after_filters, InspectTableFilter(cardinality, child_filter, base_stats)); - } - return cardinality_after_filters; - } - if (!BoundComparisonExpression::IsComparison(expr)) { - return cardinality_after_filters; - } - auto &comparison = expr.Cast(); - if (comparison.GetExpressionType() != ExpressionType::COMPARE_EQUAL) { - return cardinality_after_filters; - } - auto column_count = GetDistinctCountFromStats(base_stats, cardinality).distinct_count; - if (column_count > 0) { - cardinality_after_filters = (cardinality + column_count - 1) / column_count; - } - return cardinality_after_filters; -} - } // namespace duckdb diff --git a/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp index 06faf929f..8c02ad5ff 100644 --- a/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp @@ -165,24 +165,18 @@ CatalogPushdownResult RemotePushdownOptimizer::ResolveRemoteCatalog(const Identi CatalogPushdownResult RemotePushdownOptimizer::Merge(CatalogPushdownResult a, CatalogPushdownResult b) { if (a.reference_type == CatalogReferenceType::NO_CATALOG_REFERENCED && b.reference_type == CatalogReferenceType::NO_CATALOG_REFERENCED) { - // both sides refer to no catalog - result is no catalog reference, but with unified references - auto result = CatalogPushdownResult::NoCatalogReference(); - result.used_expressions.insert(result.used_expressions.end(), a.used_expressions.begin(), - a.used_expressions.end()); - result.used_expressions.insert(result.used_expressions.end(), b.used_expressions.begin(), - b.used_expressions.end()); - result.used_table_constructs.insert(result.used_table_constructs.end(), a.used_table_constructs.begin(), - a.used_table_constructs.end()); - result.used_table_constructs.insert(result.used_table_constructs.end(), b.used_table_constructs.begin(), - b.used_table_constructs.end()); - result.used_nodes.insert(result.used_nodes.end(), a.used_nodes.begin(), a.used_nodes.end()); - result.used_nodes.insert(result.used_nodes.end(), b.used_nodes.begin(), b.used_nodes.end()); - return result; + // both sides refer to no catalog - append the references of "b" to "a" in-place, so that folding + // many results into an accumulator stays linear + a.used_expressions.insert(a.used_expressions.end(), b.used_expressions.begin(), b.used_expressions.end()); + a.used_table_constructs.insert(a.used_table_constructs.end(), b.used_table_constructs.begin(), + b.used_table_constructs.end()); + a.used_nodes.insert(a.used_nodes.end(), b.used_nodes.begin(), b.used_nodes.end()); + return a; } if (a.reference_type == CatalogReferenceType::SINGLE_REMOTE_CATALOG && b.reference_type == CatalogReferenceType::NO_CATALOG_REFERENCED) { // swap "a" and "b" so the merge happens below - return Merge(b, a); + return Merge(std::move(b), std::move(a)); } if (a.reference_type == CatalogReferenceType::NO_CATALOG_REFERENCED && b.reference_type == CatalogReferenceType::SINGLE_REMOTE_CATALOG) { @@ -272,7 +266,7 @@ CatalogPushdownResult RemotePushdownOptimizer::Rewrite(QueryNode &node) { cte_result = CatalogPushdownResult::Unknown(); } for (auto &key : cte_info.key_targets) { - cte_result = Merge(cte_result, Rewrite(key)); + cte_result = Merge(std::move(cte_result), Rewrite(key)); } cte_results[cte_name] = cte_result; } @@ -308,7 +302,7 @@ CatalogPushdownResult RemotePushdownOptimizer::Rewrite(QueryNode &node) { for (auto &cte_pair : node.cte_map.map) { auto it = cte_results.find(cte_pair.first); if (it != cte_results.end()) { - result = Merge(result, it->second); + result = Merge(std::move(result), it->second); } } if (result.reference_type == CatalogReferenceType::SINGLE_REMOTE_CATALOG) { @@ -334,9 +328,9 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(RecursiveCTENode &nod RemotePushdownOptimizer right_optimizer(&recursive_optimizer); CatalogPushdownResult right_result = right_optimizer.Rewrite(*node.right); - auto result = Merge(left_result, right_result); + auto result = Merge(std::move(left_result), std::move(right_result)); for (auto &key : node.key_targets) { - result = Merge(result, Rewrite(key)); + result = Merge(std::move(result), Rewrite(key)); } for (auto &modifier : node.modifiers) { switch (modifier->type) { @@ -345,17 +339,17 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(RecursiveCTENode &nod for (auto &order : order_mod.orders) { // ORDER BY entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(order.expression, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(order.expression, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); } break; } case ResultModifierType::LIMIT_MODIFIER: { auto &limit_mod = modifier->Cast(); if (limit_mod.limit) { - result = Merge(result, Rewrite(limit_mod.limit)); + result = Merge(std::move(result), Rewrite(limit_mod.limit)); } if (limit_mod.offset) { - result = Merge(result, Rewrite(limit_mod.offset)); + result = Merge(std::move(result), Rewrite(limit_mod.offset)); } break; } @@ -364,7 +358,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(RecursiveCTENode &nod for (auto &expr : distinct_mod.distinct_on_targets) { // DISTINCT ON entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); } break; } @@ -384,21 +378,21 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SelectNode &node) { // Merge from_table result with all expressions to determine if the whole node can be pushed CatalogPushdownResult result = from_result; for (auto &expr : node.select_list) { - result = Merge(result, Rewrite(expr)); + result = Merge(std::move(result), Rewrite(expr)); } if (node.where_clause) { - result = Merge(result, Rewrite(node.where_clause)); + result = Merge(std::move(result), Rewrite(node.where_clause)); } for (auto &expr : node.groups.group_expressions) { // GROUP BY entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); } if (node.having) { - result = Merge(result, Rewrite(node.having)); + result = Merge(std::move(result), Rewrite(node.having)); } if (node.qualify) { - result = Merge(result, Rewrite(node.qualify)); + result = Merge(std::move(result), Rewrite(node.qualify)); } for (auto &modifier : node.modifiers) { switch (modifier->type) { @@ -407,17 +401,17 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SelectNode &node) { for (auto &order : order_mod.orders) { // ORDER BY entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(order.expression, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(order.expression, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); } break; } case ResultModifierType::LIMIT_MODIFIER: { auto &limit_mod = modifier->Cast(); if (limit_mod.limit) { - result = Merge(result, Rewrite(limit_mod.limit)); + result = Merge(std::move(result), Rewrite(limit_mod.limit)); } if (limit_mod.offset) { - result = Merge(result, Rewrite(limit_mod.offset)); + result = Merge(std::move(result), Rewrite(limit_mod.offset)); } break; } @@ -426,7 +420,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SelectNode &node) { for (auto &expr : distinct_mod.distinct_on_targets) { // DISTINCT ON entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); } break; } @@ -447,7 +441,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(InsertQueryNode &node if (node.select_statement) { RemotePushdownOptimizer select_optimizer(this); auto select_result = select_optimizer.Rewrite(*node.select_statement->node); - result = Merge(result, select_result); + result = Merge(std::move(result), select_result); if (select_result.reference_type == CatalogReferenceType::SINGLE_REMOTE_CATALOG) { bool push_select_only = result.reference_type != CatalogReferenceType::SINGLE_REMOTE_CATALOG; if (!push_select_only && !result.catalog->SupportsPushdown(node)) { @@ -462,22 +456,22 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(InsertQueryNode &node if (node.on_conflict_info) { if (node.on_conflict_info->condition) { auto condition_result = Rewrite(node.on_conflict_info->condition); - result = Merge(result, condition_result); + result = Merge(std::move(result), condition_result); } if (node.on_conflict_info->set_info) { if (node.on_conflict_info->set_info->condition) { auto condition_result = Rewrite(node.on_conflict_info->set_info->condition); - result = Merge(result, condition_result); + result = Merge(std::move(result), condition_result); } for (auto &expr : node.on_conflict_info->set_info->expressions) { auto expr_result = Rewrite(expr); - result = Merge(result, expr_result); + result = Merge(std::move(result), expr_result); } } } for (auto &expr : node.returning_list) { auto expr_result = Rewrite(expr); - result = Merge(result, expr_result); + result = Merge(std::move(result), expr_result); } return result; } @@ -488,16 +482,16 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(DeleteQueryNode &node for (auto &using_clause : node.using_clauses) { auto using_result = Rewrite(using_clause); using_results.push_back(using_result); - result = Merge(result, using_result); + result = Merge(std::move(result), using_result); } if (node.condition) { auto condition_result = Rewrite(node.condition); - result = Merge(result, condition_result); + result = Merge(std::move(result), condition_result); } for (auto &expr : node.returning_list) { auto expr_result = Rewrite(expr); - result = Merge(result, expr_result); + result = Merge(std::move(result), expr_result); } return result; } @@ -507,23 +501,23 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(UpdateQueryNode &node auto from_result = CatalogPushdownResult::NoCatalogReference(); if (node.from_table) { from_result = Rewrite(node.from_table); - result = Merge(result, from_result); + result = Merge(std::move(result), from_result); } if (node.set_info) { if (node.set_info->condition) { auto condition_result = Rewrite(node.set_info->condition); - result = Merge(result, condition_result); + result = Merge(std::move(result), condition_result); } for (auto &expr : node.set_info->expressions) { auto expr_result = Rewrite(expr); - result = Merge(result, expr_result); + result = Merge(std::move(result), expr_result); } } for (auto &expr : node.returning_list) { auto expr_result = Rewrite(expr); - result = Merge(result, expr_result); + result = Merge(std::move(result), expr_result); } return result; } @@ -532,30 +526,30 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(MergeQueryNode &node) // the target and the source form a join - like UPDATE ... FROM they are analyzed in the same scope, // so a local table on either side is tracked for the action expressions below auto result = Rewrite(node.target); - result = Merge(result, Rewrite(node.source)); + result = Merge(std::move(result), Rewrite(node.source)); if (node.join_condition) { - result = Merge(result, Rewrite(node.join_condition)); + result = Merge(std::move(result), Rewrite(node.join_condition)); } for (auto &entry : node.actions) { for (auto &action : entry.second) { if (action->condition) { - result = Merge(result, Rewrite(action->condition)); + result = Merge(std::move(result), Rewrite(action->condition)); } if (action->update_info) { if (action->update_info->condition) { - result = Merge(result, Rewrite(action->update_info->condition)); + result = Merge(std::move(result), Rewrite(action->update_info->condition)); } for (auto &expr : action->update_info->expressions) { - result = Merge(result, Rewrite(expr)); + result = Merge(std::move(result), Rewrite(expr)); } } for (auto &expr : action->expressions) { - result = Merge(result, Rewrite(expr)); + result = Merge(std::move(result), Rewrite(expr)); } } } for (auto &expr : node.returning_list) { - result = Merge(result, Rewrite(expr)); + result = Merge(std::move(result), Rewrite(expr)); } return result; } @@ -568,7 +562,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SetOperationNode &nod for (auto &child : node.children) { RemotePushdownOptimizer child_optimizer(this); auto child_result = child_optimizer.Rewrite(*child); - result = Merge(result, child_result); + result = Merge(std::move(result), child_result); child_results.push_back(child_result); } @@ -581,7 +575,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SetOperationNode &nod for (auto &order : order_mod.orders) { // ORDER BY entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(order.expression, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(order.expression, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); has_expression_modifiers = true; } break; @@ -589,11 +583,11 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SetOperationNode &nod case ResultModifierType::LIMIT_MODIFIER: { auto &limit_mod = modifier->Cast(); if (limit_mod.limit) { - result = Merge(result, Rewrite(limit_mod.limit)); + result = Merge(std::move(result), Rewrite(limit_mod.limit)); has_expression_modifiers = true; } if (limit_mod.offset) { - result = Merge(result, Rewrite(limit_mod.offset)); + result = Merge(std::move(result), Rewrite(limit_mod.offset)); has_expression_modifiers = true; } break; @@ -603,7 +597,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteNode(SetOperationNode &nod for (auto &expr : distinct_mod.distinct_on_targets) { // DISTINCT ON entries cannot be constant-folded - a bare integer literal is a // positional reference there - result = Merge(result, Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); + result = Merge(std::move(result), Rewrite(expr, ExpressionFoldingMode::FOLD_CHILDREN_ONLY)); has_expression_modifiers = true; } break; @@ -840,7 +834,7 @@ CatalogPushdownResult RemotePushdownOptimizer::Rewrite(ExpressionListRef &ref) { auto result = CatalogPushdownResult::NoCatalogReference(); for (auto &row : ref.values) { for (auto &expr : row) { - result = Merge(result, Rewrite(expr)); + result = Merge(std::move(result), Rewrite(expr)); } } return result; @@ -905,7 +899,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteTableFunctionOnly(TableFun // the generic TableRef dispatch records the function so a remote catalog can veto it auto result = CatalogPushdownResult::NoCatalogReference(); for (auto &arg : func_expr.GetArgumentsMutable()) { - result = Merge(result, RewriteTableFunctionArgument(arg.GetExpressionMutable())); + result = Merge(std::move(result), RewriteTableFunctionArgument(arg.GetExpressionMutable())); } return result; } @@ -945,7 +939,7 @@ CatalogPushdownResult RemotePushdownOptimizer::Rewrite(TableFunctionRef &ref) { // recurse into the function arguments auto &func_expr = ref.function->Cast(); for (auto &arg : func_expr.GetArgumentsMutable()) { - result = Merge(result, RewriteTableFunctionArgument(arg.GetExpressionMutable())); + result = Merge(std::move(result), RewriteTableFunctionArgument(arg.GetExpressionMutable())); } return result; } @@ -957,11 +951,11 @@ CatalogPushdownResult RemotePushdownOptimizer::Rewrite(JoinRef &ref) { RemotePushdownOptimizer child_optimizer(this); auto right_result = child_optimizer.Rewrite(ref.right); - auto result = Merge(left_result, right_result); + auto result = Merge(std::move(left_result), std::move(right_result)); // Also analyze the join condition - it may contain subqueries or local macro calls // that affect whether the join can be pushed as a whole. if (ref.condition) { - result = Merge(result, Rewrite(ref.condition)); + result = Merge(std::move(result), Rewrite(ref.condition)); } return result; } diff --git a/src/duckdb/src/optimizer/remove_unused_columns.cpp b/src/duckdb/src/optimizer/remove_unused_columns.cpp index 0ef4132e0..e55dbbb59 100644 --- a/src/duckdb/src/optimizer/remove_unused_columns.cpp +++ b/src/duckdb/src/optimizer/remove_unused_columns.cpp @@ -934,6 +934,7 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { } } + cte.column_count = expressions.size(); auto projection = make_uniq(binder.GenerateTableIndex(), std::move(expressions)); projection->children.push_back(std::move(cte.children[0])); cte.children[0] = std::move(projection); 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 3ce4cd9a5..8b91ea949 100644 --- a/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp +++ b/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp @@ -50,6 +50,14 @@ unique_ptr ContainsToInClauseRule::Apply(LogicalOperator &op, vector // No non-NULL elements: never contains any value. if (non_null_elements.empty()) { + if (ListValue::GetChildren(list_val).empty()) { + // An empty list never contains anything, not even NULL - but keep volatile/throwing probes. + if (probe_arg->IsVolatile() || probe_arg->CanThrow()) { + return nullptr; + } + changes_made = true; + return make_uniq(Value::BOOLEAN(false)); + } changes_made = true; return ExpressionRewriter::ConstantOrNull(GetContext(), probe_arg->Copy(), Value::BOOLEAN(false)); } diff --git a/src/duckdb/src/optimizer/rule/not_comparison_simplification.cpp b/src/duckdb/src/optimizer/rule/not_comparison_simplification.cpp index 3194601b5..8996fcbd6 100644 --- a/src/duckdb/src/optimizer/rule/not_comparison_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/not_comparison_simplification.cpp @@ -7,9 +7,7 @@ namespace duckdb { NotComparisonSimplificationRule::NotComparisonSimplificationRule(ExpressionRewriter &rewriter) : Rule(rewriter) { - auto op = make_uniq(ExpressionClass::BOUND_OPERATOR); - op->expr_type = make_uniq(ExpressionType::OPERATOR_NOT); - root = std::move(op); + root = make_uniq(); } unique_ptr NotComparisonSimplificationRule::Apply(LogicalOperator &op, diff --git a/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp b/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp index 279afb830..76206aaf4 100644 --- a/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/not_conjunction_simplification.cpp @@ -6,9 +6,7 @@ namespace duckdb { NotConjunctionSimplificationRule::NotConjunctionSimplificationRule(ExpressionRewriter &rewriter) : Rule(rewriter) { - auto op = make_uniq(ExpressionClass::BOUND_OPERATOR); - op->expr_type = make_uniq(ExpressionType::OPERATOR_NOT); - root = std::move(op); + root = make_uniq(); } unique_ptr NotConjunctionSimplificationRule::Apply(LogicalOperator &op, diff --git a/src/duckdb/src/optimizer/rule/not_constant_or_null_simplification.cpp b/src/duckdb/src/optimizer/rule/not_constant_or_null_simplification.cpp new file mode 100644 index 000000000..9bb2a2421 --- /dev/null +++ b/src/duckdb/src/optimizer/rule/not_constant_or_null_simplification.cpp @@ -0,0 +1,53 @@ +#include "duckdb/optimizer/rule/not_constant_or_null_simplification.hpp" + +#include "duckdb/function/scalar/generic_functions.hpp" +#include "duckdb/optimizer/expression_rewriter.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" + +namespace duckdb { + +NotConstantOrNullSimplificationRule::NotConstantOrNullSimplificationRule(ExpressionRewriter &rewriter) + : Rule(rewriter) { + // the operand is a BOOLEAN constant_or_null(, ) + auto cornull = make_uniq(); + cornull->type = make_uniq(LogicalType::BOOLEAN); + cornull->function = make_uniq(Identifier(ConstantOrNullFun::Name)); + cornull->policy = SetMatcher::Policy::SOME_ORDERED; + cornull->matchers.push_back(make_uniq()); // the leading value argument + + auto not_matcher = make_uniq(); + not_matcher->child = std::move(cornull); + root = std::move(not_matcher); +} + +// NOT(constant_or_null(v, e)) => constant_or_null(!v, e) +// the NULL check on e is preserved, only the constant is negated +unique_ptr NotConstantOrNullSimplificationRule::Apply(LogicalOperator &op, + vector> &bindings, + bool &changes_made, bool is_root) { + auto ¬_expr = bindings[0].get().Cast(); + auto &func = bindings[1].get().Cast(); + auto &value_expr = bindings[2].get().Cast(); + D_ASSERT(not_expr.GetExpressionType() == ExpressionType::OPERATOR_NOT); + + auto value = value_expr.GetValue(); + if (value.IsNull()) { + return nullptr; + } + + // the first child is the constant value; the remaining children carry the NULL check + auto &func_children = func.GetChildrenMutable(); + D_ASSERT(func_children.size() >= 2); + vector> children; + children.reserve(func_children.size() - 1); + for (idx_t child_idx = 1; child_idx < func_children.size(); ++child_idx) { + children.push_back(std::move(func_children[child_idx])); + } + + changes_made = true; + return rewriter.ConstantOrNull(GetContext(), std::move(children), Value::BOOLEAN(!value.GetValue())); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/rule/or_range_merge.cpp b/src/duckdb/src/optimizer/rule/or_range_merge.cpp new file mode 100644 index 000000000..e57455512 --- /dev/null +++ b/src/duckdb/src/optimizer/rule/or_range_merge.cpp @@ -0,0 +1,398 @@ +#include "duckdb/optimizer/rule/or_range_merge.hpp" + +#include "duckdb/planner/expression/bound_between_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_lambda_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/common/algorithm.hpp" + +namespace duckdb { + +namespace { + +//! One side of a range; a side that is not present leaves the range open on that side +struct RangeBound { + bool present = false; + Value value; + bool inclusive = false; +}; + +//! A child of the OR that restricts one expression to a range with constant bounds +struct RangePredicate { + RangePredicate(idx_t child_idx, Expression &input, RangeBound lower, RangeBound upper) + : child_idx(child_idx), input(input), lower(std::move(lower)), upper(std::move(upper)) { + } + + //! The position of the child in the OR + idx_t child_idx; + //! The expression the range restricts + reference input; + RangeBound lower; + RangeBound upper; + //! Whether the predicate has been assigned to a group of predicates on the same input + bool grouped = false; +}; + +//! Types whose constants compare the same way through Value as through the comparison operators +bool SupportsRangeMerge(const LogicalType &type) { + switch (type.InternalType()) { + case PhysicalType::INT8: + case PhysicalType::INT16: + case PhysicalType::INT32: + case PhysicalType::INT64: + case PhysicalType::INT128: + case PhysicalType::UINT8: + case PhysicalType::UINT16: + case PhysicalType::UINT32: + case PhysicalType::UINT64: + case PhysicalType::UINT128: + case PhysicalType::FLOAT: + case PhysicalType::DOUBLE: + case PhysicalType::VARCHAR: + case PhysicalType::INTERVAL: + return true; + default: + return false; + } +} + +//! Whether the expression holds a constant anywhere in its tree; a lambda body is not a child of its function, so it +//! is walked explicitly +bool HasConstant(const Expression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + return true; + } + bool found = false; + if (expr.GetExpressionClass() == ExpressionClass::BOUND_LAMBDA) { + auto &lambda = expr.Cast(); + found = HasConstant(*lambda.LambdaExpr()); + for (auto &capture : lambda.Captures()) { + found = found || HasConstant(*capture); + } + } + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { found = found || HasConstant(child); }); + return found; +} + +//! Whether equal inputs compute the same value: constants compare by value, so an input that holds one may only +//! look the same (v + INTERVAL '1 month' and v + INTERVAL '30 days', atan2(x, 0.0) and atan2(x, -0.0)) +bool IsMergeableInput(const Expression &input) { + return !input.IsVolatile() && !HasConstant(input); +} + +//! A constant bound: a non-NULL BoundConstantExpression with the type of the input +bool TryGetBound(const Expression &expr, const LogicalType &input_type, bool inclusive, RangeBound &bound) { + if (expr.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + return false; + } + auto &value = expr.Cast().GetValue(); + if (value.IsNull() || value.type() != input_type) { + return false; + } + bound.present = true; + bound.value = value; + bound.inclusive = inclusive; + return true; +} + +//! x > a, x >= a, x < b, x <= b with a constant on either side: a range that is open on one side +bool TryGetComparisonRange(Expression &expr, optional_ptr &input, RangeBound &lower, RangeBound &upper) { + auto comparison_type = expr.GetExpressionType(); + switch (comparison_type) { + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + break; + default: + return false; + } + if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { + return false; + } + auto &comparison = expr.Cast(); + auto &left = BoundComparisonExpression::LeftMutable(comparison); + auto &right = BoundComparisonExpression::RightMutable(comparison); + optional_ptr constant; + if (right->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + input = left.get(); + constant = right.get(); + } else if (left->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + // a > x is x < a + input = right.get(); + constant = left.get(); + comparison_type = FlipComparisonExpression(comparison_type); + } else { + return false; + } + bool inclusive = comparison_type == ExpressionType::COMPARE_LESSTHANOREQUALTO || + comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO; + bool is_upper = comparison_type == ExpressionType::COMPARE_LESSTHAN || + comparison_type == ExpressionType::COMPARE_LESSTHANOREQUALTO; + return TryGetBound(*constant, input->GetReturnType(), inclusive, is_upper ? upper : lower); +} + +//! A child of the OR that is a range on one expression with constant bounds: BETWEEN, a single comparison, or an AND +//! of a lower and an upper comparison on the same expression (how the binder plans BETWEEN on a column) +bool TryGetRange(Expression &expr, optional_ptr &input, RangeBound &lower, RangeBound &upper) { + switch (expr.GetExpressionType()) { + case ExpressionType::COMPARE_BETWEEN: { + if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { + return false; + } + auto &between = expr.Cast(); + if (!BoundBetweenExpression::HasValidBindData(between)) { + return false; + } + input = BoundBetweenExpression::InputMutable(between).get(); + auto &input_type = input->GetReturnType(); + return TryGetBound(BoundBetweenExpression::LowerBound(between), input_type, + BoundBetweenExpression::LowerInclusive(between), lower) && + TryGetBound(BoundBetweenExpression::UpperBound(between), input_type, + BoundBetweenExpression::UpperInclusive(between), upper); + } + case ExpressionType::CONJUNCTION_AND: { + auto &conjunction = expr.Cast(); + auto &children = conjunction.GetChildrenMutable(); + if (children.size() != 2) { + return false; + } + optional_ptr second_input; + if (!TryGetComparisonRange(*children[0], input, lower, upper) || + !TryGetComparisonRange(*children[1], second_input, lower, upper)) { + return false; + } + // one lower and one upper bound on the same expression + return lower.present && upper.present && input->Equals(*second_input) && IsMergeableInput(*input); + } + default: + return TryGetComparisonRange(expr, input, lower, upper); + } +} + +//! Whether the range is non-empty, which the merge relies on when it extends an earlier range over this one +bool IsNonEmptyRange(const RangeBound &lower, const RangeBound &upper) { + if (!lower.present || !upper.present) { + return true; + } + if (lower.value < upper.value) { + return true; + } + return lower.value == upper.value && lower.inclusive && upper.inclusive; +} + +//! Orders ranges by their lower bound: open first, then by value, with inclusive before exclusive on a tie +bool LowerBoundLessThan(const RangeBound &left, const RangeBound &right) { + if (!left.present || !right.present) { + return !left.present && right.present; + } + if (left.value == right.value) { + return left.inclusive && !right.inclusive; + } + return left.value < right.value; +} + +template +bool IsSuccessor(const Value &upper, const Value &lower) { + // lower > upper, so subtracting one from lower cannot underflow + return lower.GetValueUnsafe() - T(1) == upper.GetValueUnsafe(); +} + +//! Whether lower is the integer that follows upper, e.g. x <= 20 and x >= 21 cover every integer from 1 to 40 +bool IsAdjacentInteger(const Value &upper, const Value &lower) { + auto &type = upper.type(); + if (!type.IsIntegral()) { + return false; + } + switch (type.InternalType()) { + case PhysicalType::INT8: + return IsSuccessor(upper, lower); + case PhysicalType::INT16: + return IsSuccessor(upper, lower); + case PhysicalType::INT32: + return IsSuccessor(upper, lower); + case PhysicalType::INT64: + return IsSuccessor(upper, lower); + case PhysicalType::INT128: + return IsSuccessor(upper, lower); + case PhysicalType::UINT8: + return IsSuccessor(upper, lower); + case PhysicalType::UINT16: + return IsSuccessor(upper, lower); + case PhysicalType::UINT32: + return IsSuccessor(upper, lower); + case PhysicalType::UINT64: + return IsSuccessor(upper, lower); + case PhysicalType::UINT128: + return IsSuccessor(upper, lower); + default: + return false; + } +} + +//! Whether a range that starts at lower continues the range that ends at upper, i.e. their union has no hole +bool Connects(const RangeBound &upper, const RangeBound &lower) { + if (!upper.present || !lower.present) { + return true; + } + if (lower.value < upper.value) { + return true; + } + if (lower.value == upper.value) { + // [1, 20] and (20, 40] both cover 20 together, [1, 20) and (20, 40] leave it out + return upper.inclusive || lower.inclusive; + } + return upper.inclusive && lower.inclusive && IsAdjacentInteger(upper.value, lower.value); +} + +//! Extends the upper bound of a range to the upper bound of a range it connects to, when that one reaches further +void ExtendUpperBound(RangeBound &upper, const RangeBound &other) { + if (!upper.present) { + return; + } + if (!other.present || upper.value < other.value) { + upper = other; + } else if (upper.value == other.value) { + upper.inclusive = upper.inclusive || other.inclusive; + } +} + +unique_ptr MakeComparison(ExpressionType type, const Expression &input, const RangeBound &bound) { + return BoundComparisonExpression::Create(type, input.Copy(), make_uniq(bound.value)); +} + +//! The merged range: a BETWEEN when both bounds are present, otherwise a single comparison +unique_ptr MakeRange(const Expression &input, const RangeBound &lower, const RangeBound &upper) { + auto lower_type = + lower.inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; + auto upper_type = upper.inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN; + if (!lower.present) { + return MakeComparison(upper_type, input, upper); + } + if (!upper.present) { + return MakeComparison(lower_type, input, lower); + } + if (input.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + // like the binder: a column reference is cheap to copy and two comparisons are what the pushdown works with + return make_uniq(ExpressionType::CONJUNCTION_AND, + MakeComparison(lower_type, input, lower), + MakeComparison(upper_type, input, upper)); + } + return BoundBetweenExpression::Create(input.Copy(), make_uniq(lower.value), + make_uniq(upper.value), lower.inclusive, + upper.inclusive); +} + +} // namespace + +OrRangeMergeRule::OrRangeMergeRule(ExpressionRewriter &rewriter) : Rule(rewriter) { + // match on an OR expression + root = make_uniq(); + root->expr_type = make_uniq(ExpressionType::CONJUNCTION_OR); +} + +unique_ptr OrRangeMergeRule::Apply(LogicalOperator &op, vector> &bindings, + bool &changes_made, bool is_root) { + auto &disjunction = bindings[0].get().Cast(); + auto &children = disjunction.GetChildrenMutable(); + + // collect the children that are ranges with constant bounds + vector ranges; + for (idx_t child_idx = 0; child_idx < children.size(); child_idx++) { + optional_ptr input; + RangeBound lower; + RangeBound upper; + if (!TryGetRange(*children[child_idx], input, lower, upper)) { + continue; + } + if (!SupportsRangeMerge(input->GetReturnType()) || !IsMergeableInput(*input) || + !IsNonEmptyRange(lower, upper)) { + continue; + } + ranges.emplace_back(child_idx, *input, std::move(lower), std::move(upper)); + } + if (ranges.size() < 2) { + return nullptr; + } + + // merge the ranges on the same input: sorted by lower bound, every range that connects to the running range + // extends it; the merged range replaces the first of its members, the other members are dropped + vector> replacements(children.size()); + vector dropped(children.size(), false); + bool merged_any = false; + for (idx_t i = 0; i < ranges.size(); i++) { + if (ranges[i].grouped) { + continue; + } + vector group; + for (idx_t j = i; j < ranges.size(); j++) { + if (!ranges[j].grouped && ranges[j].input.get().Equals(ranges[i].input.get())) { + ranges[j].grouped = true; + group.push_back(j); + } + } + if (group.size() < 2) { + continue; + } + std::sort(group.begin(), group.end(), + [&](idx_t a, idx_t b) { return LowerBoundLessThan(ranges[a].lower, ranges[b].lower); }); + + vector members; + RangeBound lower; + RangeBound upper; + auto flush = [&]() { + if (members.size() < 2) { + return; + } + merged_any = true; + idx_t first = *std::min_element(members.begin(), members.end()); + replacements[first] = MakeRange(ranges[group[0]].input.get(), lower, upper); + for (auto member : members) { + dropped[member] = member != first; + } + }; + for (auto range_idx : group) { + auto &range = ranges[range_idx]; + // a range that is open on both sides is not a range anymore: start over instead + bool connects = !members.empty() && Connects(upper, range.lower) && (lower.present || range.upper.present); + if (!connects) { + flush(); + members.clear(); + lower = range.lower; + upper = range.upper; + } else { + ExtendUpperBound(upper, range.upper); + } + members.push_back(range.child_idx); + } + flush(); + } + if (!merged_any) { + return nullptr; + } + + vector> new_children; + for (idx_t child_idx = 0; child_idx < children.size(); child_idx++) { + if (dropped[child_idx]) { + continue; + } + if (replacements[child_idx]) { + new_children.push_back(std::move(replacements[child_idx])); + } else { + new_children.push_back(std::move(children[child_idx])); + } + } + if (new_children.size() == 1) { + return std::move(new_children[0]); + } + auto result = make_uniq(ExpressionType::CONJUNCTION_OR); + for (auto &child : new_children) { + result->GetChildrenMutable().push_back(std::move(child)); + } + return std::move(result); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/rule/string_prefix.cpp b/src/duckdb/src/optimizer/rule/string_prefix.cpp index a2a85f962..115ddac80 100644 --- a/src/duckdb/src/optimizer/rule/string_prefix.cpp +++ b/src/duckdb/src/optimizer/rule/string_prefix.cpp @@ -178,6 +178,10 @@ unique_ptr InstrPrefixRule::Apply(LogicalOperator &op, vector() != 1) { return nullptr; } + // prefix with a NULL needle binds to a NULL constant, not to a function + if (needle.GetValue().IsNull()) { + return nullptr; + } auto &children = func.GetChildrenMutable(); D_ASSERT(children.size() == 2); diff --git a/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp b/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp index b74ae83fc..ab71037ed 100644 --- a/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp +++ b/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp @@ -36,7 +36,10 @@ unique_ptr StructExtractStructPackFoldingRule::Apply(LogicalOperator } // struct_extract(struct_pack(e0, .., en), ki) is equivalent to ei auto result = std::move(packed_children[extract_data.index]); - return BoundCastExpression::AddCastToType(GetContext(), std::move(result), extract.Function().GetReturnType()); + auto &return_type = extract.GetReturnType(); + // AddCastToType skips the cast when only the collation differs - keep the collation of the extract + auto cast = BoundCastExpression::AddCastToType(GetContext(), std::move(result), return_type); + return Expression::PreserveReturnType(return_type, std::move(cast)); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/sampling_pushdown.cpp b/src/duckdb/src/optimizer/sampling_pushdown.cpp index 0c934242b..592922de1 100644 --- a/src/duckdb/src/optimizer/sampling_pushdown.cpp +++ b/src/duckdb/src/optimizer/sampling_pushdown.cpp @@ -22,7 +22,7 @@ unique_ptr SamplingPushdown::Optimize(unique_ptrseed.IsValid()) { auto &random_engine = RandomEngine::Get(context); - sample_op.sample_options->SetSeed(random_engine.NextRandomInteger()); + sample_op.sample_options->SetSeed(random_engine.NextSeed32()); } // For row-count sampling, calculate the sampling rate based on estimated cardinality. // Use EstimateCardinality which can query table function stats if has_estimated_cardinality is not set. diff --git a/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp b/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp new file mode 100644 index 000000000..514867158 --- /dev/null +++ b/src/duckdb/src/optimizer/scalar_aggregate_merger.cpp @@ -0,0 +1,667 @@ +#include "duckdb/optimizer/scalar_aggregate_merger.hpp" + +#include "duckdb/common/set.hpp" +#include "duckdb/main/settings.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_cross_product.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +//===--------------------------------------------------------------------===// +// Branch: [projection ->] ungrouped aggregate -> filters -> plain scan(s) +//===--------------------------------------------------------------------===// +//! One leaf of a cross-product tree that can be merged with its siblings +struct ScalarAggregateMerger::Branch { + //! The leaf's slot in the cross-product tree + reference> leaf; + //! The projection over the aggregate, if any + optional_ptr projection; + reference aggregate; + //! The slot under the filters: the scan, or the cross product of scans of different tables (a FROM list) + reference> relation; + vector> scans; + //! The filters' predicates, with ANDs split into their conjuncts + vector> conjuncts; +}; + +//! One of the first branch's scans, which the merged leaf keeps, and the columns it gains for the other branches +struct ScalarAggregateMerger::MergeTarget { + reference scan; + //! A column the scan gains, and the binding that column lands on + vector> added_columns; +}; + +//! The aggregates that are merged: FILTER (WHERE p) feeds exactly the rows where p holds, so the result over the rows +//! where p holds equals the result with FILTER (WHERE p) over any superset of them, for empty input too +//! (0 for the counts, NULL otherwise). min(x, n) and max(x, n) take two arguments and are not matched. +static bool IsMergeableAggregateFunction(const BoundAggregateExpression &aggregate) { + auto &name = aggregate.Function().GetName().GetIdentifierName(); + const auto argument_count = aggregate.GetChildren().size(); + if (name == "count_star") { + return argument_count == 0; + } + return argument_count == 1 && (name == "count" || name == "sum" || name == "avg" || name == "min" || name == "max"); +} + +//! An expression that may be evaluated on more rows than before: neither volatile nor able to throw. A foldable +//! subtree that can throw failed to fold, and a CASE or OR above it decides per row whether it is reached. +static bool IsSafeOnOtherRows(const Expression &expr) { + return !expr.IsVolatile() && !expr.CanThrow(); +} + +static bool IsMergeableAggregate(const Expression &expr) { + if (expr.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + return false; + } + auto &aggregate = expr.Cast(); + // DISTINCT is fine: the FILTER applies before the deduplication. ORDER BY is not matched. + if (aggregate.GetOrderBys() || !IsMergeableAggregateFunction(aggregate)) { + return false; + } + for (auto &child : aggregate.GetChildren()) { + if (!IsSafeOnOtherRows(*child)) { + return false; + } + } + return !aggregate.GetFilter() || IsSafeOnOtherRows(*aggregate.GetFilter()); +} + +static void SplitConjunction(const Expression &expr, vector> &conjuncts) { + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + for (auto &child : expr.Cast().GetChildren()) { + SplitConjunction(*child, conjuncts); + } + return; + } + conjuncts.push_back(expr); +} + +//! A scan as bound: no filters, time travel, ordinality, projection list, sample, input table or process-local input, +//! and only plain columns. A scan that reads no column gets the empty placeholder once its types are resolved. +static bool IsPlainScan(const LogicalGet &get) { + if (!get.children.empty() || get.bind_info || get.table_filters.HasFilters() || get.at_clause || + get.source_ordinality != OrdinalityType::WITHOUT_ORDINALITY || !get.projection_ids.empty() || + get.has_pushed_projection || get.extra_info.sample_options || get.dynamic_filters || + !get.input_table_types.empty() || !get.projected_input.empty()) { + return false; + } + for (auto &column_id : get.GetColumnIds()) { + if (column_id.IsEmptyColumn()) { + continue; + } + if (column_id.IsVirtualColumn() || column_id.HasChildren()) { + return false; + } + } + return true; +} + +static bool SameValues(const vector &a, const vector &b) { + if (a.size() != b.size()) { + return false; + } + for (idx_t i = 0; i < a.size(); i++) { + if (a[i].type() != b[i].type() || !Value::NotDistinctFrom(a[i], b[i])) { + return false; + } + } + return true; +} + +static bool SameNamedParameters(const named_argument_map_t &a, const named_argument_map_t &b) { + if (a.size() != b.size()) { + return false; + } + for (auto &entry : a) { + auto other = b.find(entry.first); + if (other == b.end() || entry.second.type() != other->second.type() || + !Value::NotDistinctFrom(entry.second, other->second)) { + return false; + } + } + return true; +} + +//! Two plain scans that read the same rows: the same catalog table, or the same table function (read_parquet, +//! read_csv, ...) called with the same arguments. What a call without arguments reads is known to its bind data alone. +static bool IsSameRelation(const LogicalGet &a, const LogicalGet &b) { + if (a.function != b.function || !SameValues(a.parameters, b.parameters) || + !SameNamedParameters(a.named_parameters, b.named_parameters)) { + return false; + } + auto table = a.GetTable(); + if (table || b.GetTable()) { + return table.get() == b.GetTable().get(); + } + return !a.parameters.empty() || FunctionData::Equals(a.bind_data.get(), b.bind_data.get()); +} + +//! The columns a scan reads, without the empty placeholder +static set ReadColumns(const LogicalGet &get) { + set columns; + for (auto &column_id : get.GetColumnIds()) { + if (!column_id.IsEmptyColumn()) { + columns.insert(column_id.GetPrimaryIndex()); + } + } + return columns; +} + +//! A named argument that is set: given, not NULL and not false +static bool HasOption(const LogicalGet &get, const char *name) { + auto entry = get.named_parameters.find(name); + if (entry == get.named_parameters.end() || entry->second.IsNull()) { + return false; + } + return entry->second.type().id() != LogicalTypeId::BOOLEAN || BooleanValue::Get(entry->second); +} + +//! A scan that stores the rows it rejects writes them as a side effect of each scan +static bool RecordsRejects(const LogicalGet &get) { + return HasOption(get, "store_rejects") || HasOption(get, "rejects_table") || HasOption(get, "rejects_scan") || + HasOption(get, "rejects_limit"); +} + +//! Two scans that one scan reading both of their columns can replace: the same relation, and the rows a scan returns do +//! not depend on the columns it reads. A scan that drops the rows it fails to parse (ignore_errors) returns a row when +//! every column it reads parses, so such scans are only shared when they read the same columns. +static bool CanShareScan(const LogicalGet &a, const LogicalGet &b) { + if (!IsSameRelation(a, b) || RecordsRejects(a)) { + return false; + } + return !HasOption(a, "ignore_errors") || ReadColumns(a) == ReadColumns(b); +} + +//! The plain scans under `op`: one scan, or a cross product of scans of different relations (a self-join's copies of +//! a table would not pair one to one with another branch's) +static bool CollectScans(LogicalOperator &op, vector> &scans) { + if (op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + for (auto &child : op.children) { + if (!CollectScans(*child, scans)) { + return false; + } + } + return true; + } + if (op.type != LogicalOperatorType::LOGICAL_GET) { + return false; + } + auto &scan = op.Cast(); + if (!IsPlainScan(scan)) { + return false; + } + for (auto &other : scans) { + if (IsSameRelation(other.get(), scan)) { + return false; + } + } + scans.push_back(scan); + return true; +} + +//! Two branches read the same tables when their scans pair up one to one as scans that can be shared +static bool ReadSameTables(const ScalarAggregateMerger::Branch &a, const ScalarAggregateMerger::Branch &b) { + if (a.scans.size() != b.scans.size()) { + return false; + } + for (auto &scan : a.scans) { + bool found = false; + for (auto &other : b.scans) { + found = found || CanShareScan(scan.get(), other.get()); + } + if (!found) { + return false; + } + } + return true; +} + +//! Equal conjuncts, or the same comparison with its sides swapped (a = b and b = a) +static bool IsSameConjunct(const Expression &a, const Expression &b) { + if (a.Equals(b)) { + return true; + } + if (!BoundComparisonExpression::IsComparison(a) || !BoundComparisonExpression::IsComparison(b)) { + return false; + } + auto &left = a.Cast(); + auto &right = b.Cast(); + return left.GetExpressionType() == FlipComparisonExpression(right.GetExpressionType()) && + BoundComparisonExpression::Left(left).Equals(BoundComparisonExpression::Right(right)) && + BoundComparisonExpression::Right(left).Equals(BoundComparisonExpression::Left(right)); +} + +static bool ContainsConjunct(const vector> &conjuncts, const Expression &expr) { + for (auto &conjunct : conjuncts) { + if (IsSameConjunct(*conjunct, expr)) { + return true; + } + } + return false; +} + +static void CollectBindings(const Expression &expr, column_binding_set_t &bindings) { + ExpressionIterator::VisitExpression( + expr, [&](const BoundColumnRefExpression &column_ref) { bindings.insert(column_ref.Binding()); }); +} + +//! 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 unique_ptr MakeConjunction(ExpressionType type, vector> terms) { + if (terms.size() == 1) { + return std::move(terms[0]); + } + auto result = make_uniq(type); + for (auto &term : terms) { + result->GetChildrenMutable().push_back(std::move(term)); + } + return std::move(result); +} + +static bool TreeHasProjectionMap(const LogicalOperator &op) { + if (op.HasProjectionMap()) { + return true; + } + for (auto &child : op.children) { + if (TreeHasProjectionMap(*child)) { + return true; + } + } + return false; +} + +//! Where `target` reads `column`: the binding it has, or the one it gains once its group merges +static ColumnBinding TargetBinding(ScalarAggregateMerger::MergeTarget &target, column_t column) { + auto &scan = target.scan.get(); + auto &column_ids = scan.GetColumnIds(); + for (idx_t i = 0; i < column_ids.size(); i++) { + if (column_ids[i].GetPrimaryIndex() == column) { + return ColumnBinding(scan.table_index, ProjectionIndex(i)); + } + } + for (auto &entry : target.added_columns) { + if (entry.first == column) { + return entry.second; + } + } + ColumnBinding binding(scan.table_index, ProjectionIndex(column_ids.size() + target.added_columns.size())); + target.added_columns.emplace_back(column, binding); + return binding; +} + +//===--------------------------------------------------------------------===// +// ScalarAggregateMerger +//===--------------------------------------------------------------------===// +ScalarAggregateMerger::ScalarAggregateMerger(Optimizer &optimizer) : optimizer(optimizer) { +} + +void ScalarAggregateMerger::Optimize(unique_ptr &plan) { + // rebuilding a cross-product tree would move the positions a projection map names: only plans without them + if (TreeHasProjectionMap(*plan)) { + return; + } + VisitOperator(plan); + if (replacements.empty()) { + return; + } + ColumnBindingReplacer replacer; + replacer.replacement_bindings = std::move(replacements); + replacer.VisitOperator(*plan); + plan->ResolveOperatorTypes(); +} + +void ScalarAggregateMerger::VisitOperator(unique_ptr &op) { + if (op->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + MergeCrossProduct(op); + return; + } + for (auto &child : op->children) { + VisitOperator(child); + } +} + +static void CollectLeaves(unique_ptr &op, vector>> &leaves) { + if (op->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + for (auto &child : op->children) { + CollectLeaves(child, leaves); + } + return; + } + leaves.push_back(op); +} + +static idx_t LeafPosition(const vector>> &leaves, + const unique_ptr &leaf) { + for (idx_t i = 0; i < leaves.size(); i++) { + if (&leaves[i].get() == &leaf) { + return i; + } + } + throw InternalException("ScalarAggregateMerger: a branch's leaf is not among its tree's leaves"); +} + +bool ScalarAggregateMerger::IsWorthMerging(const Branch &branch) { + auto threshold = Settings::Get(optimizer.context); + for (auto &scan : branch.scans) { + if (!scan.get().GetTable()) { + return true; + } + if (threshold != 0 && scan.get().EstimateCardinality(optimizer.context) >= threshold) { + return true; + } + } + return false; +} + +void ScalarAggregateMerger::MergeCrossProduct(unique_ptr &op) { + vector>> leaves; + CollectLeaves(op, leaves); + for (auto &leaf : leaves) { + VisitOperator(leaf.get()); + } + vector branches; + for (auto &leaf : leaves) { + TryMatchBranch(leaf, branches); + } + // groups of branches that read the same tables, in the order their first branch appears + vector> groups; + for (idx_t i = 0; i < branches.size(); i++) { + bool placed = false; + for (auto &group : groups) { + if (ReadSameTables(branches[group[0]], branches[i])) { + group.push_back(i); + placed = true; + break; + } + } + if (!placed) { + groups.push_back({i}); + } + } + // the merged leaf takes the place of a group's first branch; the other branches' leaves go + vector> merged_leaves(leaves.size()); + vector removed(leaves.size(), false); + bool changed = false; + for (auto &group : groups) { + if (group.size() < 2 || !IsWorthMerging(branches[group[0]])) { + continue; + } + auto merged_leaf = MergeBranches(branches, group); + if (!merged_leaf) { + continue; + } + merged_leaves[LeafPosition(leaves, branches[group[0]].leaf.get())] = std::move(merged_leaf); + for (idx_t k = 1; k < group.size(); k++) { + removed[LeafPosition(leaves, branches[group[k]].leaf.get())] = true; + } + changed = true; + } + if (!changed) { + return; + } + // rebuild the tree over the leaves that remain: a cross product's bindings are its children's, so their order + // changes nothing above it + vector> kept; + for (idx_t i = 0; i < leaves.size(); i++) { + if (removed[i]) { + continue; + } + kept.push_back(merged_leaves[i] ? std::move(merged_leaves[i]) : std::move(leaves[i].get())); + } + auto tree = std::move(kept[0]); + for (idx_t i = 1; i < kept.size(); i++) { + tree = LogicalCrossProduct::Create(std::move(tree), std::move(kept[i])); + } + op = std::move(tree); +} + +void ScalarAggregateMerger::TryMatchBranch(unique_ptr &leaf, vector &branches) { + reference op = *leaf; + optional_ptr projection; + if (op.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + projection = &op.get().Cast(); + op = *op.get().children[0]; + } + if (op.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return; + } + auto &aggregate = op.get().Cast(); + // an aggregate without groups or grouping sets returns exactly one row + if (!aggregate.groups.empty() || !aggregate.grouping_functions.empty() || aggregate.grouping_sets.size() > 1 || + (aggregate.grouping_sets.size() == 1 && !aggregate.grouping_sets[0].empty()) || aggregate.expressions.empty()) { + return; + } + for (auto &expr : aggregate.expressions) { + if (!IsMergeableAggregate(*expr)) { + return; + } + } + vector> conjuncts; + reference> relation = aggregate.children[0]; + while (relation.get()->type == LogicalOperatorType::LOGICAL_FILTER) { + for (auto &expr : relation.get()->Cast().expressions) { + SplitConjunction(*expr, conjuncts); + } + relation = relation.get()->children[0]; + } + for (auto &conjunct : conjuncts) { + if (!IsSafeOnOtherRows(conjunct.get())) { + return; + } + } + vector> scans; + if (!CollectScans(*relation.get(), scans)) { + return; + } + branches.push_back(Branch {leaf, projection, aggregate, relation, std::move(scans), std::move(conjuncts)}); +} + +unique_ptr ScalarAggregateMerger::MergeBranches(vector &branches, const vector &group) { + auto &binder = optimizer.binder; + auto &first = branches[group[0]]; + // every branch's scan bindings land on the first branch's scan of the same table, which gains the columns it + // lacks once the group is known to merge + vector targets; + for (auto &scan : first.scans) { + targets.push_back(MergeTarget {scan, {}}); + } + vector> remaps(group.size()); + for (idx_t k = 1; k < group.size(); k++) { + for (auto &branch_scan : branches[group[k]].scans) { + auto &scan = branch_scan.get(); + optional_ptr target; + for (auto &candidate : targets) { + if (CanShareScan(candidate.scan.get(), scan)) { + target = &candidate; + } + } + D_ASSERT(target); + auto &column_ids = scan.GetColumnIds(); + for (idx_t i = 0; i < column_ids.size(); i++) { + // nothing refers to the empty placeholder + if (column_ids[i].IsEmptyColumn()) { + continue; + } + remaps[k][ColumnBinding(scan.table_index, ProjectionIndex(i))] = + TargetBinding(*target, column_ids[i].GetPrimaryIndex()); + } + } + } + // the conjuncts on the target bindings, then split into the ones every branch has and what each has beyond them + vector>> conjuncts(group.size()); + 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]); + conjuncts[k].push_back(std::move(copy)); + } + } + vector> shared; + for (auto &conjunct : conjuncts[0]) { + bool everywhere = !ContainsConjunct(shared, *conjunct); + for (idx_t k = 1; everywhere && k < group.size(); k++) { + everywhere = ContainsConjunct(conjuncts[k], *conjunct); + } + if (everywhere) { + shared.push_back(conjunct->Copy()); + } + } + vector>> own(group.size()); + for (idx_t k = 0; k < group.size(); k++) { + for (auto &conjunct : conjuncts[k]) { + if (!ContainsConjunct(shared, *conjunct)) { + own[k].push_back(std::move(conjunct)); + } + } + } + // over several tables, every own conjunct must read one and the same table: the tables are then joined by the + // shared conjuncts alone, and the OR filters that table. A join condition only some branches have would turn the + // merged join into a filter over the tables' product. + bool own_table_known = false; + TableIndex own_table; + for (auto &branch_own : own) { + for (auto &conjunct : branch_own) { + column_binding_set_t bindings; + CollectBindings(*conjunct, bindings); + for (auto &binding : bindings) { + if (!own_table_known) { + own_table_known = true; + own_table = binding.table_index; + } else if (binding.table_index != own_table) { + return nullptr; + } + } + } + } + + // the group merges: the target scans read the added columns + for (auto &target : targets) { + for (auto &entry : target.added_columns) { + auto position = target.scan.get().AddColumnId(entry.first); + D_ASSERT(position == entry.second.column_index); + (void)position; + } + } + // each branch's own predicate (none: every row the shared conjuncts keep) + vector> predicates(group.size()); + bool every_branch_restricted = true; + for (idx_t k = 0; k < group.size(); k++) { + if (own[k].empty()) { + every_branch_restricted = false; + continue; + } + predicates[k] = MakeConjunction(ExpressionType::CONJUNCTION_AND, std::move(own[k])); + } + // the merged aggregate: every branch's aggregates, each FILTERed to its branch's rows + auto aggregate_index = binder.GenerateTableIndex(); + vector> aggregates; + vector offsets(group.size()); + for (idx_t k = 0; k < group.size(); k++) { + offsets[k] = aggregates.size(); + for (auto &expr : branches[group[k]].aggregate.get().expressions) { + auto copy = expr->Copy(); + RemapBindings(*copy, remaps[k]); + auto &aggregate = copy->Cast(); + if (predicates[k]) { + auto filter = predicates[k]->Copy(); + if (aggregate.GetFilter()) { + vector> both; + both.push_back(std::move(filter)); + both.push_back(std::move(aggregate.GetFilterMutable())); + filter = MakeConjunction(ExpressionType::CONJUNCTION_AND, std::move(both)); + } + aggregate.GetFilterMutable() = std::move(filter); + } + aggregates.push_back(std::move(copy)); + } + } + // the merged projection: every branch's columns, which the plan above reads in their place + auto projection_index = binder.GenerateTableIndex(); + vector> columns; + for (idx_t k = 0; k < group.size(); k++) { + auto &branch = branches[group[k]]; + auto &aggregate = branch.aggregate.get(); + column_binding_map_t to_merged; + for (idx_t j = 0; j < aggregate.expressions.size(); j++) { + to_merged[ColumnBinding(aggregate.aggregate_index, ProjectionIndex(j))] = + ColumnBinding(aggregate_index, ProjectionIndex(offsets[k] + j)); + } + if (branch.projection) { + auto &expressions = branch.projection->expressions; + for (idx_t i = 0; i < expressions.size(); i++) { + auto copy = expressions[i]->Copy(); + 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)); + } + } else { + for (idx_t j = 0; j < aggregate.expressions.size(); j++) { + replacements.emplace_back(ColumnBinding(aggregate.aggregate_index, ProjectionIndex(j)), + ColumnBinding(projection_index, ProjectionIndex(columns.size()))); + columns.push_back(make_uniq( + aggregate.expressions[j]->GetReturnType(), + ColumnBinding(aggregate_index, ProjectionIndex(offsets[k] + j)))); + } + } + } + + // projection -> aggregate -> filter [shared AND (OR of the branches' own predicates)] -> the first branch's scan(s) + unique_ptr relation = std::move(first.relation.get()); + vector> filters = std::move(shared); + if (every_branch_restricted) { + // branches with the same predicate (q9 has three per range) contribute one alternative + vector> alternatives; + for (auto &predicate : predicates) { + if (!ContainsConjunct(alternatives, *predicate)) { + alternatives.push_back(predicate->Copy()); + } + } + // the OR is a new expression: the rewrite rules that ran before the merge (predicate factoring) derive from it + // the single-column filters that the pushdown places on the scan and that the cardinality estimates see + LogicalFilter rewritten; + rewritten.expressions.push_back(MakeConjunction(ExpressionType::CONJUNCTION_OR, std::move(alternatives))); + optimizer.rewriter.VisitOperator(rewritten); + for (auto &expr : rewritten.expressions) { + filters.push_back(std::move(expr)); + } + } + if (!filters.empty()) { + auto filter = make_uniq(); + filter->expressions = std::move(filters); + filter->AddChild(std::move(relation)); + relation = std::move(filter); + } + auto aggregate = make_uniq(binder.GenerateTableIndex(), aggregate_index, std::move(aggregates)); + aggregate->groupings_index = binder.GenerateTableIndex(); + aggregate->grouping_sets = first.aggregate.get().grouping_sets; + aggregate->AddChild(std::move(relation)); + auto projection = make_uniq(projection_index, std::move(columns)); + projection->AddChild(std::move(aggregate)); + projection->ResolveOperatorTypes(); + return std::move(projection); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/self_join_aggregate.cpp b/src/duckdb/src/optimizer/self_join_aggregate.cpp new file mode 100644 index 000000000..b9107097b --- /dev/null +++ b/src/duckdb/src/optimizer/self_join_aggregate.cpp @@ -0,0 +1,589 @@ +// A self-join of one table on equal keys K and on `a.x <> b.x` for one more column x, read only through K by a parent +// that ignores duplicates, is `GROUP BY K HAVING min(x) <> max(x)` over a single scan. TPC-DS q95's ws_wh is the case: +// +// WITH ws_wh AS (SELECT ws1.ws_order_number, ws1.ws_warehouse_sk wh1, ws2.ws_warehouse_sk wh2 +// FROM web_sales ws1, web_sales ws2 +// WHERE ws1.ws_order_number = ws2.ws_order_number AND ws1.ws_warehouse_sk <> ws2.ws_warehouse_sk) +// ... ws_order_number IN (SELECT ws_order_number FROM ws_wh) +// +// The join pairs every order's rows with each other only to learn which orders ship from more than one warehouse; +// the group-by reads web_sales once and keeps one row per order. +// +// Why it is exact. The join's rows are the pairs (r1, r2) of rows with the same non-NULL K (`=` drops NULL keys) and +// non-NULL, different x (`<>` drops NULL x). The set of their K values is the set of K values of the non-NULL groups +// that hold two different non-NULL x, which is `min(x) <> max(x)` over the group (min and max skip NULLs; a group +// whose x are all NULL gives NULL <> NULL, which the HAVING drops). So the two produce the same SET of K, and a parent +// that reads only K and ignores how often each row occurs cannot tell them apart. The NULL key group is filtered out +// first: in the join no NULL key pairs with anything, and an IN over a NULL would turn a FALSE marker into NULL. +// +// Which parents ignore duplicates, checked from the root down (Walk): the right side of a SEMI, ANTI or MARK join (and +// the left side of a RIGHT_SEMI or RIGHT_ANTI one), whose rows only decide whether a match exists -- a MARK join's NULL +// included, which depends on whether a NULL occurs, not how often; a DISTINCT, whose targets it reads through +// expressions, a DISTINCT ON passing its other columns through by position, which therefore all count as read; and a +// GROUP BY whose aggregates are min, max or DISTINCT ones (`min(x, n)`, the n smallest values, counts duplicates and +// is not one of them). Below such a parent the property passes through projections and filters without volatile +// expressions, cross products and INNER joins: their output, as a set, depends only on their inputs as sets. Anything +// else stops it, a UNION among them: it reads its inputs' columns by position rather than through expressions, so what +// it reads would not be seen. A materialized CTE's definition ignores duplicates when every one of its references does. +// +// What must hold of the join, in the plan as bound (the rewrite runs before filter pushdown, which would move the +// conditions into the scans; the later optimizers then push the new filter into the scan and order the joins around +// the group-by as for any other): a projection over filters over a cross product or an INNER comparison join of two +// scans of the same relation -- the same table, or the same function with equal bind data and marked repeatable, so +// that the two scans return the same rows, read the same way, without table filters, time travel, sampling or +// ordinality -- and every condition of the filters and the join a `=` or `<>` between the same column of the two +// scans. The `=` columns are K, at least one; the `<>` column is x, exactly one and not in K (with two the pairs must +// differ in both, which no per-column test says). K and x are integral or DATE columns, whose ordering agrees with +// their equality; a collated VARCHAR's need not. The projection's columns read above it (through the references of +// the CTE it defines, when it does) must each be one of K: those then come from the group-by and the others, which +// nothing reads, become typed NULLs, so a CTE keeps the columns its references expect. +#include "duckdb/optimizer/self_join_aggregate.hpp" + +#include "duckdb/function/builtin_function_lookup.hpp" +#include "duckdb/function/function_binder.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/logical_operator_repeatability.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_any_join.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cross_product.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_distinct.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" + +namespace duckdb { + +namespace { + +bool AnyVolatile(const vector> &expressions) { + for (auto &expr : expressions) { + if (expr->IsVolatile()) { + return true; + } + } + return false; +} + +bool JoinConditionsVolatile(const LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_ANY_JOIN) { + return op.Cast().condition->IsVolatile(); + } + for (auto &condition : op.Cast().conditions) { + if (condition.IsComparison() ? condition.GetLHS().IsVolatile() || condition.GetRHS().IsVolatile() + : condition.GetJoinExpression().IsVolatile()) { + return true; + } + } + return false; +} + +//! A GROUP BY whose result is the same over its input with or without repeated rows +bool AggregateIgnoresDuplicates(const LogicalAggregate &aggregate) { + if (AnyVolatile(aggregate.groups)) { + return false; + } + for (auto &expr : aggregate.expressions) { + if (expr->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE || expr->IsVolatile()) { + return false; + } + auto &bound = expr->Cast(); + if (bound.IsDistinct()) { + continue; + } + auto &name = bound.Function().GetName().GetIdentifierName(); + if ((name != "min" && name != "max") || bound.GetChildren().size() != 1) { + return false; + } + } + return true; +} + +//! The column bindings the plan reads, visited from the root down so that a candidate projection's expressions count +//! only when the column they compute is itself read: everything above a candidate reads it through expressions, so +//! an unreferenced column of it is dead, and so is whatever only that column referenced (an inlined CTE's identity +//! projection names every column of its body, whether or not anything above reads it) +class LiveBindings : public LogicalOperatorVisitor { +public: + //! `readers`: a candidate projection -> the table indexes through which its columns are read + explicit LiveBindings(const reference_map_t> &readers) : readers(readers) { + } + + column_binding_set_t read; + + bool IsRead(LogicalOperator &projection, idx_t column) const { + for (auto reader : readers.at(projection)) { + if (read.count(ColumnBinding(reader, ProjectionIndex(column))) > 0) { + return true; + } + } + return false; + } + + void VisitOperator(LogicalOperator &op) override { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + // the references, below the second child, are visited before the definition they read + VisitOperator(*op.children[1]); + VisitOperator(*op.children[0]); + return; + } + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && readers.count(op) > 0) { + for (idx_t k = 0; k < op.expressions.size(); k++) { + if (IsRead(op, k)) { + VisitExpression(&op.expressions[k]); + } + } + } else { + VisitOperatorExpressions(op); + } + if (op.type == LogicalOperatorType::LOGICAL_DISTINCT && + op.Cast().distinct_type == DistinctType::DISTINCT_ON) { + // the columns it does not deduplicate on pass through by position + for (auto &binding : op.children[0]->GetColumnBindings()) { + read.insert(binding); + } + } + VisitOperatorChildren(op); + } + +protected: + unique_ptr VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) override { + read.insert(expr.Binding()); + return nullptr; + } + +private: + const reference_map_t> &readers; +}; + +//! A scan that reads its whole relation, so that one of two equal scans can stand in for both +bool PlainScan(const LogicalGet &get) { + return get.children.empty() && !get.table_filters.HasFilters() && !get.at_clause && !get.dynamic_filters && + !get.extra_info.sample_options && get.source_ordinality == OrdinalityType::WITHOUT_ORDINALITY; +} + +bool SameParameters(const LogicalGet &a, const LogicalGet &b) { + if (a.parameters.size() != b.parameters.size() || a.named_parameters.size() != b.named_parameters.size()) { + return false; + } + for (idx_t i = 0; i < a.parameters.size(); i++) { + if (!Value::NotDistinctFrom(a.parameters[i], b.parameters[i])) { + return false; + } + } + for (auto &entry : a.named_parameters) { + auto other = b.named_parameters.find(entry.first); + if (other == b.named_parameters.end() || !Value::NotDistinctFrom(entry.second, other->second)) { + return false; + } + } + return true; +} + +//! Two scans that read the same rows: the same catalog table, or the same repeatable function with equal bind data +bool SameRelation(LogicalGet &a, LogicalGet &b) { + if (!PlainScan(a) || !PlainScan(b) || a.function != b.function || !SameParameters(a, b)) { + return false; + } + auto table = a.GetTable(); + if (table) { + return table.get() == b.GetTable().get(); + } + if (b.GetTable()) { + return false; + } + // a function not marked repeatable may return different rows each time it runs + if (ClassifyLogicalOperatorRepeatability(a) != LogicalOperatorRepeatability::REPEATABLE || + ClassifyLogicalOperatorRepeatability(b) != LogicalOperatorRepeatability::REPEATABLE) { + return false; + } + return a.bind_data && b.bind_data && a.bind_data->Equals(*b.bind_data); +} + +//! The table column a scan emits at `binding`, when it is a plain one +bool ScanColumn(const LogicalGet &get, ProjectionIndex binding, column_t &column) { + idx_t position = binding.GetIndex(); + if (!get.projection_ids.empty()) { + if (position >= get.projection_ids.size()) { + return false; + } + position = get.projection_ids[position].GetIndex(); + } + auto &column_ids = get.GetColumnIds(); + if (position >= column_ids.size()) { + return false; + } + auto &id = column_ids[position]; + if (id.IsVirtualColumn() || id.HasChildren()) { + return false; + } + column = id.GetPrimaryIndex(); + return true; +} + +//! Types whose ordering agrees with their equality, so that min <> max says exactly "two different values" +bool OrderMatchesEquality(const LogicalType &type) { + return type.IsIntegral() || type.id() == LogicalTypeId::DATE; +} + +void SplitConjunctions(const Expression &expr, vector> &out) { + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + for (auto &child : expr.Cast().GetChildren()) { + SplitConjunctions(*child, out); + } + return; + } + out.push_back(expr); +} + +//! One column of the scanned relation, as each of the two scans emits it +struct PairedColumn { + column_t column; + ProjectionIndex left; + ProjectionIndex right; + LogicalType type; +}; + +struct Candidate { + //! The projection's slot in its parent + reference> slot; + //! The CTE the projection defines, or null for one read through its own bindings + optional_ptr cte; +}; + +class SelfJoinAggregateRewriter { +public: + SelfJoinAggregateRewriter(ClientContext &context, Binder &binder) : context(context), binder(binder) { + } + + void Run(unique_ptr &plan) { + Walk(plan, false); + if (candidates.empty()) { + return; + } + reference_map_t> readers; + for (auto &candidate : candidates) { + auto &projection = *candidate.slot.get(); + if (candidate.cte) { + readers[projection] = cte_references[candidate.cte->table_index]; + } else { + readers[projection] = {projection.Cast().table_index}; + } + } + LiveBindings live(readers); + live.VisitOperator(*plan); + // deepest first: a rewrite replaces what is below its projection, never what is above it + for (idx_t i = candidates.size(); i-- > 0;) { + auto &projection = *candidates[i].slot.get(); + vector read(projection.expressions.size(), false); + for (idx_t k = 0; k < read.size(); k++) { + read[k] = live.IsRead(projection, k); + } + Rewrite(projection.Cast(), read); + } + } + +private: + //! `ignores`: whether the parent of `slot` gives the same result over its rows with or without repeats + void Walk(unique_ptr &slot, bool ignores) { + auto &op = *slot; + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + if (ignores) { + candidates.push_back(Candidate {slot, nullptr}); + } + Walk(op.children[0], ignores && !AnyVolatile(op.expressions)); + return; + case LogicalOperatorType::LOGICAL_FILTER: + Walk(op.children[0], ignores && !AnyVolatile(op.expressions)); + return; + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + for (auto &child : op.children) { + Walk(child, ignores); + } + return; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_ANY_JOIN: { + const bool deterministic = !JoinConditionsVolatile(op); + bool left = false; + bool right = false; + switch (op.Cast().join_type) { + case JoinType::INNER: + left = right = ignores; + break; + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + left = ignores; + right = true; + break; + case JoinType::RIGHT_SEMI: + case JoinType::RIGHT_ANTI: + left = true; + right = ignores; + break; + default: + break; + } + Walk(op.children[0], left && deterministic); + Walk(op.children[1], right && deterministic); + return; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + Walk(op.children[0], AggregateIgnoresDuplicates(op.Cast())); + return; + case LogicalOperatorType::LOGICAL_DISTINCT: + // its targets are expressions, so what it deduplicates on counts as read, and so does every column a + // DISTINCT ON passes through + Walk(op.children[0], true); + return; + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { + // its references are all below its second child, so they are all seen before its definition is + auto &cte = op.Cast(); + Walk(op.children[1], ignores); + auto entry = cte_ignores_duplicates.find(cte.table_index); + const bool definition_ignores = entry != cte_ignores_duplicates.end() && entry->second; + auto &definition = op.children[0]; + if (definition->type == LogicalOperatorType::LOGICAL_PROJECTION) { + // read through the references' bindings, not its own: a candidate of its own kind + if (definition_ignores) { + candidates.push_back(Candidate {definition, &cte}); + } + Walk(definition->children[0], definition_ignores && !AnyVolatile(definition->expressions)); + } else { + Walk(definition, definition_ignores); + } + return; + } + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &reference = op.Cast(); + auto entry = cte_ignores_duplicates.emplace(reference.cte_index, true); + entry.first->second = entry.first->second && ignores; + cte_references[reference.cte_index].push_back(reference.table_index); + return; + } + default: + for (auto &child : op.children) { + Walk(child, false); + } + return; + } + } + + //! Rewrites the self-join below `projection` when it is one; `read[k]`: whether column k is read above + bool Rewrite(LogicalProjection &projection, const vector &read) { + vector> predicates; + reference op = *projection.children[0]; + while (op.get().type == LogicalOperatorType::LOGICAL_FILTER) { + auto &filter = op.get().Cast(); + if (filter.HasProjectionMap()) { + return false; + } + for (auto &expr : filter.expressions) { + SplitConjunctions(*expr, predicates); + } + op = *op.get().children[0]; + } + vector> conditions; + if (op.get().type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &comparison_join = op.get().Cast(); + if (comparison_join.join_type != JoinType::INNER || comparison_join.HasProjectionMap()) { + return false; + } + for (auto &condition : comparison_join.conditions) { + if (!condition.IsComparison()) { + return false; + } + conditions.push_back(condition); + } + } else if (op.get().type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + return false; + } + auto &join = op.get(); + if (join.children.size() != 2 || join.children[0]->type != LogicalOperatorType::LOGICAL_GET || + join.children[1]->type != LogicalOperatorType::LOGICAL_GET) { + return false; + } + auto &left = join.children[0]->Cast(); + auto &right = join.children[1]->Cast(); + if (!SameRelation(left, right)) { + return false; + } + + // every condition a `=` (a key) or `<>` (the inequality) between the same column of the two scans + vector keys; + vector inequalities; + auto classify = [&](ExpressionType comparison, const Expression &lhs, const Expression &rhs) { + if (comparison != ExpressionType::COMPARE_EQUAL && comparison != ExpressionType::COMPARE_NOTEQUAL) { + return false; + } + if (lhs.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || + rhs.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return false; + } + auto lhs_binding = lhs.Cast().Binding(); + auto rhs_binding = rhs.Cast().Binding(); + if (lhs_binding.table_index == right.table_index && rhs_binding.table_index == left.table_index) { + std::swap(lhs_binding, rhs_binding); + } + if (lhs_binding.table_index != left.table_index || rhs_binding.table_index != right.table_index) { + return false; + } + column_t left_column; + column_t right_column; + if (!ScanColumn(left, lhs_binding.column_index, left_column) || + !ScanColumn(right, rhs_binding.column_index, right_column) || left_column != right_column || + lhs.GetReturnType() != rhs.GetReturnType() || !OrderMatchesEquality(lhs.GetReturnType())) { + return false; + } + auto &into = comparison == ExpressionType::COMPARE_EQUAL ? keys : inequalities; + for (auto &known : into) { + if (known.column == left_column) { + return known.left == lhs_binding.column_index && known.right == rhs_binding.column_index; + } + } + into.push_back( + PairedColumn {left_column, lhs_binding.column_index, rhs_binding.column_index, lhs.GetReturnType()}); + return true; + }; + for (auto &predicate : predicates) { + auto &expr = predicate.get(); + if (!BoundComparisonExpression::IsComparison(expr)) { + return false; + } + auto &comparison = expr.Cast(); + if (!classify(expr.GetExpressionType(), BoundComparisonExpression::Left(comparison), + BoundComparisonExpression::Right(comparison))) { + return false; + } + } + for (auto &condition : conditions) { + if (!classify(condition.get().GetComparisonType(), condition.get().GetLHS(), condition.get().GetRHS())) { + return false; + } + } + if (keys.empty() || inequalities.size() != 1) { + return false; + } + auto &inequality = inequalities[0]; + for (auto &key : keys) { + if (key.column == inequality.column) { + return false; + } + } + + // each column read above is a key, of either scan: the group-by emits it + vector key_of(projection.expressions.size(), DConstants::INVALID_INDEX); + for (idx_t k = 0; k < projection.expressions.size(); k++) { + if (!read[k]) { + continue; + } + auto &expr = *projection.expressions[k]; + if (expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return false; + } + auto binding = expr.Cast().Binding(); + for (idx_t i = 0; i < keys.size(); i++) { + if ((binding.table_index == left.table_index && binding.column_index == keys[i].left) || + (binding.table_index == right.table_index && binding.column_index == keys[i].right)) { + key_of[k] = i; + } + } + if (key_of[k] == DConstants::INVALID_INDEX) { + return false; + } + } + + // scan WHERE key IS NOT NULL ... GROUP BY keys [min(x), max(x)] HAVING min(x) <> max(x) + auto scan_index = left.table_index; + 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( + make_uniq(key.type, ColumnBinding(scan_index, key.left))); + not_null->expressions.push_back(std::move(check)); + } + not_null->AddChild(std::move(scan)); + + vector> bounds; + FunctionBinder function_binder(context); + for (auto name : {"min", "max"}) { + vector> arguments; + arguments.push_back( + make_uniq(inequality.type, ColumnBinding(scan_index, inequality.left))); + auto function = GetBuiltinAggregateFunction(context, Identifier(name), {inequality.type}); + bounds.push_back(function_binder.BindAggregateFunction(function, std::move(arguments))); + } + auto group_index = binder.GenerateTableIndex(); + auto aggregate_index = binder.GenerateTableIndex(); + auto aggregate = make_uniq(group_index, aggregate_index, std::move(bounds)); + aggregate->groupings_index = binder.GenerateTableIndex(); + GroupingSet every_key; + for (idx_t i = 0; i < keys.size(); i++) { + aggregate->groups.push_back( + make_uniq(keys[i].type, ColumnBinding(scan_index, keys[i].left))); + every_key.insert(ProjectionIndex(i)); + } + aggregate->grouping_sets.push_back(std::move(every_key)); + aggregate->AddChild(std::move(not_null)); + + auto having = make_uniq(BoundComparisonExpression::Create( + ExpressionType::COMPARE_NOTEQUAL, + make_uniq(inequality.type, ColumnBinding(aggregate_index, ProjectionIndex(0))), + make_uniq(inequality.type, ColumnBinding(aggregate_index, ProjectionIndex(1))))); + having->AddChild(std::move(aggregate)); + + // the projection keeps its table index and its columns' types: a read key from the groups, the rest a NULL + for (idx_t k = 0; k < projection.expressions.size(); k++) { + auto &expr = projection.expressions[k]; + unique_ptr replacement; + if (key_of[k] != DConstants::INVALID_INDEX) { + replacement = make_uniq( + expr->GetReturnType(), ColumnBinding(group_index, ProjectionIndex(key_of[k]))); + } else { + replacement = make_uniq(Value(expr->GetReturnType())); + } + replacement->SetAlias(expr->GetAlias()); + expr = std::move(replacement); + } + // drops the filters, the join and the other scan + projection.children[0] = std::move(having); + projection.ResolveOperatorTypes(); + return true; + } + +private: + ClientContext &context; + Binder &binder; + vector candidates; + //! A CTE's index -> whether each of its references seen so far ignores duplicates + unordered_map cte_ignores_duplicates; + //! A CTE's index -> the table indexes of its references + unordered_map> cte_references; +}; + +} // namespace + +SelfJoinAggregate::SelfJoinAggregate(Optimizer &optimizer) : optimizer(optimizer) { +} + +unique_ptr SelfJoinAggregate::Optimize(unique_ptr op) { + SelfJoinAggregateRewriter rewriter(optimizer.GetContext(), optimizer.binder); + rewriter.Run(op); + return op; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp index debc0f07b..d202a699d 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp @@ -76,8 +76,8 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundConjun // we have a constant in a conjunction // we (1) either prune the child // or (2) replace the entire conjunction with a constant - auto constant = ExpressionExecutor::EvaluateScalar(context, *child); - if (constant.IsNull()) { + Value constant; + if (!ExpressionExecutor::TryEvaluateScalar(context, *child, constant) || constant.IsNull()) { continue; } auto b = BooleanValue::Get(constant); diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp index 91143f71d..15692156c 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp @@ -253,6 +253,10 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundFuncti child->GetReturnType().id() == LogicalTypeId::SQLNULL) { has_invalidated_parameter = true; } + // neither does an input whose type depends on an unresolved parameter + if (!child->GetReturnType().IsComplete()) { + has_invalidated_parameter = true; + } if (!stat) { stats.push_back(BaseStatistics::CreateUnknown(child->GetReturnType())); } else { diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp index d001d0964..9df72ffd6 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp @@ -3,6 +3,7 @@ #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -108,35 +109,59 @@ void StatisticsPropagator::UpdateExpressionFilterStatistics(BaseStatistics &inpu } } -static bool IsConstantOrNullFilter(const TableFilter &table_filter) { - auto &expr_filter = ExpressionFilter::GetExpressionFilter(table_filter, "IsConstantOrNullFilter"); - if (expr_filter.expr->GetExpressionType() != ExpressionType::BOUND_FUNCTION) { - return false; +//! Whether all arguments are the filter column or non-NULL constants, with at least one being the column +static bool ArgumentsAreColumnOrConstant(const vector> &children, idx_t start_idx) { + bool has_column = false; + for (idx_t child_idx = start_idx; child_idx < children.size(); child_idx++) { + auto &child = *children[child_idx]; + if (child.GetExpressionType() == ExpressionType::BOUND_REF) { + has_column = true; + } else if (child.GetExpressionType() != ExpressionType::VALUE_CONSTANT || + child.Cast().GetValue().IsNull()) { + // e.g. CASE or COALESCE can be NULL independently of the column + return false; + } } - auto &func = expr_filter.expr->Cast(); - return ConstantOrNull::IsConstantOrNull(func, Value::BOOLEAN(true)); + return has_column; } -static bool CanReplaceConstantOrNull(const TableFilter &table_filter) { - if (!IsConstantOrNullFilter(table_filter)) { - throw InternalException("CanReplaceConstantOrNull() called on unexpected Table Filter"); - } - auto &expr_filter = ExpressionFilter::GetExpressionFilter(table_filter, "CanReplaceConstantOrNull"); - auto &func = expr_filter.expr->Cast(); - if (ConstantOrNull::IsConstantOrNull(func, Value::BOOLEAN(true))) { - for (auto child = ++func.GetChildren().begin(); child != func.GetChildren().end(); child++) { - switch (child->get()->GetExpressionType()) { - case ExpressionType::BOUND_REF: - case ExpressionType::VALUE_CONSTANT: - continue; - default: - // expression type could be a function like Coalesce +//! Whether a filter expression is NULL exactly when the filter column is NULL +static bool IsNullOnlyForNullColumn(Expression &expr) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_REF: + return true; + case ExpressionClass::BOUND_FUNCTION: { + auto &func = expr.Cast(); + if (ConstantOrNull::IsConstantOrNull(func, Value::BOOLEAN(true))) { + return ArgumentsAreColumnOrConstant(func.GetChildren(), 1); + } + if (func.Function().GetNullHandling() != FunctionNullHandling::DEFAULT_NULL_HANDLING) { + return false; + } + return ArgumentsAreColumnOrConstant(func.GetChildren(), 0); + } + case ExpressionClass::BOUND_OPERATOR: { + auto &op = expr.Cast(); + if (op.GetExpressionType() == ExpressionType::OPERATOR_NOT && op.GetChildren().size() == 1) { + return IsNullOnlyForNullColumn(*op.GetChildren()[0]); + } + if (op.GetExpressionType() == ExpressionType::COMPARE_IN) { + return op.GetChildren()[0]->GetExpressionType() == ExpressionType::BOUND_REF && + ArgumentsAreColumnOrConstant(op.GetChildren(), 0); + } + return false; + } + case ExpressionClass::BOUND_CONJUNCTION: { + for (auto &child : expr.Cast().GetChildren()) { + if (!IsNullOnlyForNullColumn(*child)) { return false; } } + return true; + } + default: + return false; } - // all children of constant or null are bound refs to the table filter column - return true; } unique_ptr StatisticsPropagator::PropagateStatistics(LogicalGet &get, @@ -191,7 +216,9 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalGet removed_expressions = true; break; case FilterPropagateResult::FILTER_TRUE_OR_NULL: { - if (IsConstantOrNullFilter(filter) && !CanReplaceConstantOrNull(filter)) { + auto &expr_filter = + ExpressionFilter::GetExpressionFilter(filter, "StatisticsPropagator::PropagateStatistics"); + if (!IsNullOnlyForNullColumn(*expr_filter.expr)) { break; } // filter is true or null; we can replace this with a not null filter diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp index 836d58163..42bb343a5 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp @@ -106,7 +106,33 @@ 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; + } + ~VerificationStatsGuard() { + attach = previous; + } + + bool &attach; + bool previous; +}; + 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 + // the condition expressions are derived from the input statistics before any condition narrows them + for (auto &condition : join.conditions) { + if (condition.IsComparison()) { + PropagateExpression(condition.LeftReference()); + PropagateExpression(condition.RightReference()); + } else { + PropagateExpression(condition.JoinExpressionReference()); + } + } + // below, the conditions are propagated again against statistics narrowed by the earlier conditions: these hold + // for the join output and the later conditions, but not for the vectors the conditions are evaluated on + VerificationStatsGuard narrowing_guard(attach_verification_stats); for (idx_t i = 0; i < join.conditions.size(); i++) { auto &condition = join.conditions[i]; if (!condition.IsComparison()) { @@ -194,7 +220,8 @@ void StatisticsPropagator::PropagateStatistics(LogicalComparisonJoin &join, uniq } switch (join.join_type) { case JoinType::INNER: - case JoinType::SEMI: { + case JoinType::SEMI: + case JoinType::RIGHT_SEMI: { UpdateFilterStatistics(condition.GetLHS(), condition.GetRHS(), condition.GetComparisonType()); auto updated_stats_left = PropagateExpression(condition.LeftReference()); auto updated_stats_right = PropagateExpression(condition.RightReference()); diff --git a/src/duckdb/src/optimizer/statistics_propagator.cpp b/src/duckdb/src/optimizer/statistics_propagator.cpp index 85a603aa6..03095c73b 100644 --- a/src/duckdb/src/optimizer/statistics_propagator.cpp +++ b/src/duckdb/src/optimizer/statistics_propagator.cpp @@ -209,7 +209,7 @@ unique_ptr StatisticsPropagator::PropagateExpression(unique_ptr< #endif auto stats = PropagateExpression(*expr, expr); D_ASSERT(expr->GetReturnType() != return_type || expr->GetReturnType().EqualsIncludingCollation(return_type)); - if (Settings::Get(context) && stats) { + if (attach_verification_stats && stats && Settings::Get(context)) { expr->SetVerificationStats(stats->ToUnique()); } return stats; diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index 1fa831e0e..9c4e995e6 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -7,6 +7,7 @@ #include "duckdb/common/unique_ptr.hpp" #include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/optimizer/late_materialization_helper.hpp" +#include "duckdb/optimizer/remove_unused_columns.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression_nullability.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" @@ -14,6 +15,7 @@ #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cte.hpp" #include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -231,7 +233,8 @@ unique_ptr TopNWindowElimination::Optimize(unique_ptr TopNWindowElimination::OptimizeInternal(unique_ptr op, ColumnBindingReplacer &replacer) { - if (!CanOptimize(*op)) { + const auto limit = CanOptimize(*op); + if (!limit.IsValid()) { // Traverse through query plan to find grouped top-n pattern if (op->children.size() > 1) { // If an operator has multiple children, we do not want them to overwrite each other's stop operator. @@ -253,7 +256,10 @@ unique_ptr TopNWindowElimination::OptimizeInternal(unique_ptr(std::move(op)); } + // We have made sure that this is an operator sequence of filter -> N optional projections -> window auto &filter = op->Cast(); reference child = *filter.children[0]; @@ -536,14 +542,24 @@ TopNWindowElimination::CreateProjectionOperator(unique_ptr op, return unique_ptr(std::move(logical_projection)); } -bool TopNWindowElimination::CanOptimize(LogicalOperator &op) { +class ColumnReferenceExtractor : public BaseColumnPruner { +public: + static column_binding_map_t GetReferences(unique_ptr *expression) { + ColumnReferenceExtractor extractor; + extractor.VisitExpression(expression); + return extractor.column_references; + } +}; + +optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op) { + const optional_idx cant_optimize; if (op.type != LogicalOperatorType::LOGICAL_FILTER) { - return false; + return cant_optimize; } const auto &filter = op.Cast(); if (filter.expressions.size() != 1) { - return false; + return cant_optimize; } const auto comparison = filter.expressions[0]->GetExpressionType(); @@ -553,122 +569,132 @@ bool TopNWindowElimination::CanOptimize(LogicalOperator &op) { case ExpressionType::COMPARE_EQUAL: break; default: - return false; + return cant_optimize; } auto &filter_comparison = filter.expressions[0]->Cast(); auto &right = BoundComparisonExpression::Right(filter_comparison); if (right.GetExpressionType() != ExpressionType::VALUE_CONSTANT) { - return false; + return cant_optimize; } auto &filter_value = right.Cast(); if (filter_value.GetValue().type() != LogicalType::BIGINT) { - return false; + return cant_optimize; } if (filter_value.GetValue().IsNull()) { - return false; + return cant_optimize; } const auto bigint_value = filter_value.GetValue().GetValue(); + optional_idx can_optimize(0); switch (comparison) { case ExpressionType::COMPARE_LESSTHANOREQUALTO: if (bigint_value < 1) { - return false; + break; } if (bigint_value >= MIN_MAX_N_MAX_VALUE) { // The rewrite passes the limit as the n value to the min/max/arg_min/arg_max "n" aggregates, which // require n < MIN_MAX_N_MAX_VALUE. Fall back to the regular window plan for larger limits. - return false; + return cant_optimize; } + can_optimize = UnsafeNumericCast(bigint_value); break; case ExpressionType::COMPARE_LESSTHAN: if (bigint_value < 2) { - return false; + break; } if (bigint_value - 1 >= MIN_MAX_N_MAX_VALUE) { - return false; + return cant_optimize; } + can_optimize = UnsafeNumericCast(bigint_value - 1); break; case ExpressionType::COMPARE_EQUAL: // TODO: Handle other values + if (bigint_value < 1) { + break; + } if (bigint_value != 1) { - return false; + return cant_optimize; } + can_optimize = UnsafeNumericCast(bigint_value); break; default: - return false; + return cant_optimize; } auto &left = BoundComparisonExpression::LeftMutable(filter_comparison); if (left->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - return false; + return cant_optimize; } - VisitExpression(&left); + auto column_references = ColumnReferenceExtractor::GetReferences(&left); reference child = *filter.children[0]; while (child.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { auto &projection = child.get().Cast(); if (column_references.size() != 1) { - column_references.clear(); - return false; + return cant_optimize; } const auto current_column_ref = column_references.begin()->first; - column_references.clear(); D_ASSERT(current_column_ref.table_index == projection.table_index); - VisitExpression(&projection.expressions[current_column_ref.column_index]); + // The filter has to name the window column itself. An expression that only mentions it, such as + // row_number + 10, is a different predicate, and following the inner reference would drop that expression. + auto &proj_expr = *projection.expressions[current_column_ref.column_index]; + if (proj_expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return cant_optimize; + } + column_references = + ColumnReferenceExtractor::GetReferences(&projection.expressions[current_column_ref.column_index]); child = *child.get().children[0]; } if (column_references.size() != 1) { - column_references.clear(); - return false; + return cant_optimize; } const auto filter_col_idx = column_references.begin()->first.table_index; - column_references.clear(); if (child.get().type != LogicalOperatorType::LOGICAL_WINDOW) { - return false; + return cant_optimize; } const auto &window = child.get().Cast(); if (window.window_index != filter_col_idx) { - return false; + return cant_optimize; } const auto &first_window_expr = window.expressions[0]->Cast(); for (auto &partition : first_window_expr.Partitions()) { if (partition->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return false; + return cant_optimize; } } if (window.expressions.size() != 1) { for (idx_t i = 1; i < window.expressions.size(); ++i) { if (!window.expressions[i]->Equals(first_window_expr)) { - return false; + return cant_optimize; } } } if (window.expressions[0]->GetExpressionType() != ExpressionType::WINDOW_ROW_NUMBER) { - return false; + return cant_optimize; } auto &window_expr = window.expressions[0]->Cast(); if (!window_expr.ArgOrders().empty()) { - return false; + return cant_optimize; } if (window_expr.OrderBy().size() != 1) { - return false; + return cant_optimize; } if (window_expr.OrderBy()[0].type != OrderType::DESCENDING && window_expr.OrderBy()[0].type != OrderType::ASCENDING) { - return false; + return cant_optimize; } if (window_expr.OrderBy()[0].null_order != OrderByNullType::NULLS_LAST) { - return false; + return cant_optimize; } // We have found a grouped top-n window construct! - return true; + return can_optimize; } vector> TopNWindowElimination::GenerateAggregatePayload(const vector &bindings, @@ -686,9 +712,8 @@ vector> TopNWindowElimination::GenerateAggregatePayload(c column_binding_map_t group_bindings; for (idx_t i = 0; i < window_expr.PartitionsMutable().size(); i++) { auto &expr = window_expr.PartitionsMutable()[i]; - VisitExpression(&expr); + auto column_references = ColumnReferenceExtractor::GetReferences(&expr); group_bindings[column_references.begin()->first] = i; - column_references.clear(); } for (idx_t i = 0; i < bindings.size(); i++) { @@ -719,7 +744,7 @@ vector> TopNWindowElimination::GenerateAggregatePayload(c if (aggregate_args.size() == 1) { // If we only project the aggregate value itself, we do not need it as an arg - VisitExpression(&window_expr.OrderByMutable()[0].expression); + auto column_references = ColumnReferenceExtractor::GetReferences(&window_expr.OrderByMutable()[0].expression); if (column_references.size() != 1) { column_references.clear(); return aggregate_args; @@ -748,13 +773,12 @@ bool TopNWindowElimination::TraverseProjectionBindings(const vectorfirst; - column_references.clear(); } op = *op.get().children[0]; } @@ -913,13 +937,11 @@ bool TopNWindowElimination::ExtractSingleBinding(unique_ptr *expr, C if (require_direct_column_ref && expr->get()->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { return false; } - VisitExpression(expr); + auto column_references = ColumnReferenceExtractor::GetReferences(expr); if (column_references.size() != 1) { - column_references.clear(); return false; } binding = column_references.begin()->first; - column_references.clear(); return true; } @@ -945,6 +967,8 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo } reference op = *window.children[0]; + // Only a single cast per column can be re-applied, so a cast chain over several projections is not recreatable + vector column_is_cast(projections.size(), false); // Traverse projections to a single table scan while (!op.get().children.empty()) { @@ -965,6 +989,12 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo // cannot reconstruct. Fall back to carrying the computed value through the aggregate instead. return false; } + if (BoundCastExpression::IsCast(*projection.expressions[projection_idx])) { + if (column_is_cast[i]) { + return false; + } + column_is_cast[i] = true; + } if (!ExtractSingleBinding(&projection.expressions[projection_idx], projections[i])) { return false; } @@ -1106,12 +1136,22 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo } } // Check if we need the projection map - for (idx_t i = 0; i < projections.size(); i++) { - if (projections[i].column_index != i) { - for (auto &proj : projections) { - lhs_projections.push_back(proj.column_index); + bool need_projection = false; + for (idx_t i = 0; i < projections.size() && !need_projection; i++) { + need_projection = projections[i].column_index != i; + } + // ConstructJoin expects the row id columns to be the last columns of the LHS. A row id that is also used as a + // payload column sits somewhere before that, so it has to be projected again to end up in the right position. + for (const auto &col_idx : rowid_column_idxs) { + for (auto &column_index : logical_get.GetColumnIds()) { + if (column_index.GetPrimaryIndex() == col_idx) { + need_projection = true; } - break; + } + } + if (need_projection) { + for (auto &proj : projections) { + lhs_projections.push_back(proj.column_index); } } return true; diff --git a/src/duckdb/src/parallel/executor.cpp b/src/duckdb/src/parallel/executor.cpp index c77922067..14b94ff23 100644 --- a/src/duckdb/src/parallel/executor.cpp +++ b/src/duckdb/src/parallel/executor.cpp @@ -60,6 +60,9 @@ struct ScheduleEventData { const vector> &meta_pipelines; vector> &events; bool initial_schedule; + //! The schedule ResolveExternalInputs validated, reused so the runtime-filter edges the analysis saw are + //! exactly the edges that run (nullptr when nothing needed resolution or for reschedules). + unique_ptr resolved_schedule; }; static shared_ptr CreatePipelineScheduleEvent(const PipelineScheduleStage &stage, bool initial_schedule) { @@ -88,12 +91,22 @@ void Executor::ScheduleEventsInternal(ScheduleEventData &event_data) { auto &events = event_data.events; D_ASSERT(events.empty()); - auto schedule = BuildPipelineSchedule(event_data.meta_pipelines); - if (schedule->HasCycle()) { + auto schedule = std::move(event_data.resolved_schedule); + const bool reused_resolved_schedule = schedule != nullptr; + if (!schedule) { + schedule = BuildPipelineSchedule(event_data.meta_pipelines); + } + if (schedule->HasCycle(PipelineScheduleGraph::SCHEDULED)) { throw InternalException("Cyclic dependency in pipeline schedule"); } if (event_data.initial_schedule && recursive_ctes.empty()) { - ScheduleRuntimeFilters(*schedule); + if (reused_resolved_schedule) { + // The reused schedule already carries the runtime-filter edges the liveness analysis validated, + // so only the stale filters need clearing. + ClearRuntimeFilters(*schedule); + } else { + ScheduleRuntimeFilters(*schedule); + } } events.reserve(schedule->stages.size()); for (auto &stage : schedule->stages) { @@ -122,8 +135,10 @@ void Executor::ScheduleEventsInternal(ScheduleEventData &event_data) { } } -void Executor::ScheduleEvents(const vector> &meta_pipelines) { +void Executor::ScheduleEvents(const vector> &meta_pipelines, + unique_ptr resolved_schedule) { ScheduleEventData event_data(meta_pipelines, events, true); + event_data.resolved_schedule = std::move(resolved_schedule); ScheduleEventsInternal(event_data); } @@ -246,7 +261,7 @@ void Executor::InitializeInternal(PhysicalOperator &plan) { lock_guard elock(executor_lock); physical_plan = &plan; - this->profiler = ClientData::Get(context).profiler; + this->profiler = context.GetContext().GetQueryProfilerPtr(); this->producer = scheduler.CreateProducer(); auto verify_progress = Settings::Get(context); @@ -263,7 +278,9 @@ void Executor::InitializeInternal(PhysicalOperator &plan) { // Resolve graph-dependent input modes after every pipeline and dependency has been constructed. vector> to_schedule; root_pipeline->GetMetaPipelines(to_schedule, true, true); - state.ResolveExternalInputs(to_schedule); + // Model the runtime-filter ordering edges under the same condition ScheduleRuntimeFilters uses below: + // this is the initial schedule, so only recursive CTEs disable them. + auto resolved_schedule = state.ResolveExternalInputs(to_schedule, recursive_ctes.empty()); profiler->Initialize(plan); root_pipeline->Ready(); @@ -286,7 +303,7 @@ void Executor::InitializeInternal(PhysicalOperator &plan) { // finally, verify and schedule VerifyPipelines(); - ScheduleEvents(to_schedule); + ScheduleEvents(to_schedule, std::move(resolved_schedule)); } } @@ -654,6 +671,11 @@ idx_t Executor::GetPipelinesProgress(ProgressData &progress) { // LCOV_EXCL_STAR progress.total = 0; idx_t count_invalid = 0; for (auto &pipeline : pipelines) { + if (pipeline->GetSource()->type == PhysicalOperatorType::RESULT_COLLECTOR) { + // this pipeline only holds the result collector as the root of the plan: it never runs, so including it + // would add a row that never completes to the total + continue; + } ProgressData p; if (!pipeline->GetProgress(p)) { count_invalid++; diff --git a/src/duckdb/src/parallel/executor_task.cpp b/src/duckdb/src/parallel/executor_task.cpp index 1f228b0b3..0f2224ab2 100644 --- a/src/duckdb/src/parallel/executor_task.cpp +++ b/src/duckdb/src/parallel/executor_task.cpp @@ -41,7 +41,7 @@ TaskExecutionResult ExecutorTask::Execute(TaskExecutionMode mode) { if (thread_context) { TaskExecutionResult result; do { - TaskNotifier task_notifier {context}; + TaskNotifier task_notifier {&context.GetContext()}; thread_context->profiler.StartOperator(op); // to allow continuous profiling, always execute in small steps result = ExecuteTask(TaskExecutionMode::PROCESS_PARTIAL); @@ -50,7 +50,7 @@ TaskExecutionResult ExecutorTask::Execute(TaskExecutionMode mode) { } while (mode == TaskExecutionMode::PROCESS_ALL && result == TaskExecutionResult::TASK_NOT_FINISHED); return result; } else { - TaskNotifier task_notifier {context}; + TaskNotifier task_notifier {&context.GetContext()}; auto result = ExecuteTask(mode); return result; } diff --git a/src/duckdb/src/parallel/pipeline.cpp b/src/duckdb/src/parallel/pipeline.cpp index 3bbe29582..a0eeef176 100644 --- a/src/duckdb/src/parallel/pipeline.cpp +++ b/src/duckdb/src/parallel/pipeline.cpp @@ -652,6 +652,32 @@ void Pipeline::AddDataflowDependency(shared_ptr &pipeline) { pipeline->parents.push_back(weak_ptr(shared_from_this())); } +void Pipeline::RemoveDataflowDependency(const shared_ptr &pipeline) { + D_ASSERT(pipeline); + bool found_dependency = false; + for (auto entry = dataflow_dependencies.begin(); entry != dataflow_dependencies.end(); entry++) { + auto dependency = entry->lock(); + D_ASSERT(dependency); + if (RefersToSameObject(*dependency, *pipeline)) { + dataflow_dependencies.erase(entry); + found_dependency = true; + break; + } + } + if (!found_dependency) { + throw InternalException("Attempted to remove a missing pipeline dataflow dependency"); + } + for (auto entry = pipeline->parents.begin(); entry != pipeline->parents.end(); entry++) { + auto parent = entry->lock(); + D_ASSERT(parent); + if (RefersToSameObject(*parent, *this)) { + pipeline->parents.erase(entry); + return; + } + } + throw InternalException("Pipeline dataflow dependency had no matching parent"); +} + vector> Pipeline::GetDependencies() const { return dependencies; } @@ -829,11 +855,27 @@ struct CTEPipelineSelection { bool stream_serialized_candidates = false; }; +struct PipelineBufferedConsumerRecord { + PipelineBufferedConsumerRecord(Pipeline &pipeline_p, PhysicalOperator &materialized_source_p, + shared_ptr cte_dependency_p, PhysicalCTE &cte_p, idx_t consumer_idx_p) + : pipeline(pipeline_p), materialized_source(materialized_source_p), cte_dependency(std::move(cte_dependency_p)), + cte(cte_p), consumer_idx(consumer_idx_p) { + } + + reference pipeline; + reference materialized_source; + shared_ptr cte_dependency; + reference cte; + idx_t consumer_idx; + bool demoted = false; +}; + class PipelineBuildStateData { public: vector external_input_candidates; vector cte_selections; reference_map_t cte_selection_map; + vector buffered_consumers; }; struct RemovedOptionalPipelineDependency { @@ -1022,6 +1064,355 @@ void PipelineBuildState::AddExternalInputCandidate(Pipeline &pipeline, PhysicalO std::move(cte_dependency), cte, consumer_idx); } +void PipelineBuildState::AddBufferedConsumer(Pipeline &pipeline, PhysicalOperator &materialized_source, + shared_ptr cte_dependency, PhysicalCTE &cte, + idx_t consumer_idx) { + data->buffered_consumers.emplace_back(pipeline, materialized_source, std::move(cte_dependency), cte, consumer_idx); +} + +//! Deadlock avoidance for buffered exchange consumers. An exchange producer throttles once the exchange buffer is +//! full. It can only progress when a direct consumer runs it, or when a buffered consumer is draining. A buffered +//! consumer drains when it can start without waiting on the exchange's own progress, and when its sink chain is +//! itself live. This computes a least fixed point of stage and exchange liveness over the scheduled and analysis +//! dependencies and returns a buffered consumer of an exchange that cannot be proven live, if any. Such a consumer +//! is demoted to the materialized working table, which removes the producer's dependence on it. +//! Before demoting, the caller tries the optional_candidates: execute-to-execute edges in the dead exchanges' +//! gating regions. When such an edge is an optional ordering (cross product and union siblings are ordered for +//! memory, not correctness), removing it can revive the exchange and preserve streaming, which beats falling back +//! to a full materialization. +static optional_ptr +FindExchangeStarvedBufferedConsumer(PipelineBuildStateData &data, const PipelineSchedule &schedule, + vector, reference>> &optional_candidates) { + struct ExchangeLiveness { + vector> records; + bool has_direct = false; + //! The producers can run and the buffered consumers can drain, so the producers are never parked forever. + bool live = false; + //! The exchange can also deliver EOF: live, and every producer's own dataflow inputs can finish. An EOF + //! wait must only be discharged by this, never by liveness alone, because a live producer that consumes + //! another exchange completes only once that exchange finishes. + bool finishes = false; + }; + reference_map_t exchanges; + for (auto &record : data.buffered_consumers) { + if (!record.demoted) { + exchanges[record.cte.get()].records.push_back(record); + } + } + if (exchanges.empty()) { + return nullptr; + } + // An exchange with a direct consumer creates a shared spool at the buffer high watermark instead of + // throttling, so its producer never waits on the buffered consumers. + for (auto &entry : exchanges) { + auto &cte = entry.first.get(); + D_ASSERT(cte.exchange); + entry.second.has_direct = cte.exchange->GetConsumerSummary().direct > 0; + } + for (auto &candidate : data.external_input_candidates) { + if (!candidate.UsesExternalInput()) { + continue; + } + auto entry = exchanges.find(candidate.cte.get()); + if (entry != exchanges.end()) { + entry->second.has_direct = true; + } + } + + auto stage_count = schedule.stages.size(); + // The exchange a stage's pipeline produces into, if that exchange has active buffered consumers. + auto producing_exchange = [&](const PipelineScheduleStage &stage) -> optional_ptr { + auto sink = stage.pipeline->GetSink(); + if (!sink || sink->type != PhysicalOperatorType::CTE) { + return nullptr; + } + auto entry = exchanges.find(sink->Cast()); + if (entry == exchanges.end()) { + return nullptr; + } + return &entry->second; + }; + // A consumer's execute only completes after its own producer finalized (the mirrored analysis edge), but for + // liveness that wait resolves whenever the exchange itself is live, so it must not count as a gate. For two + // ordered consumers of one exchange this exclusion is sound only together with the exchange's shared-spool + // rule: with more than one active consumer the producer spools at the high watermark instead of throttling + // (ShouldCreateSharedSpoolLocked), so the pinned later consumer cannot park the producer. Tightening that + // spool rule would reintroduce an ordered-pair deadlock invisible to this analysis. + auto is_own_producer_eof = [&](const PipelineScheduleStage &stage, idx_t dependency) { + if (stage.type != PipelineScheduleStageType::EXECUTE) { + return false; + } + auto &target = schedule.stages[dependency]; + if (target.type != PipelineScheduleStageType::FINISH) { + return false; + } + for (auto &dataflow : stage.pipeline->GetDataflowDependencies()) { + auto producer = dataflow.lock(); + if (producer && RefersToSameObject(*producer, *target.pipeline)) { + return true; + } + } + return false; + }; + // Index the execute stages once: the stage array is scanned repeatedly below. + reference_map_t execute_stages; + vector> stage_producing_exchange(stage_count, nullptr); + vector, idx_t>> producer_execute_stages; + for (idx_t stage_idx = 0; stage_idx < stage_count; stage_idx++) { + auto &stage = schedule.stages[stage_idx]; + if (stage.type != PipelineScheduleStageType::EXECUTE) { + continue; + } + execute_stages.emplace(*stage.pipeline, stage_idx); + auto exchange = producing_exchange(stage); + stage_producing_exchange[stage_idx] = exchange; + if (exchange) { + producer_execute_stages.emplace_back(*exchange, stage_idx); + } + } + auto record_execute_stage = [&](const PipelineBufferedConsumerRecord &record) { + auto entry = execute_stages.find(record.pipeline.get()); + return entry == execute_stages.end() ? optional_idx() : optional_idx(entry->second); + }; + + // The exchange each active dataflow producer pipeline feeds, for resolving EOF waits. + reference_map_t> producer_pipeline_exchange; + for (auto &record : data.buffered_consumers) { + if (record.demoted) { + continue; + } + auto entry = exchanges.find(record.cte.get()); + D_ASSERT(entry != exchanges.end()); + producer_pipeline_exchange.emplace(*record.cte_dependency, entry->second); + } + + vector stage_live(stage_count, false); + // An analysis dependency is the mirrored wait on a producer's finalization. It resolves only once the + // producer's exchange can deliver EOF: exchange liveness alone proves the producer can run, not that it can + // finish, because the producer may itself wait on another exchange's EOF. The finish stage's own liveness + // must not be used either, since a dataflow consumer's execute is considered live without its EOF wait. + auto dependencies_live = [&](const PipelineScheduleStage &stage) { + for (auto dependency : stage.dependencies) { + if (!stage_live[dependency]) { + return false; + } + } + for (auto dependency : stage.analysis_dependencies) { + if (is_own_producer_eof(stage, dependency)) { + continue; + } + auto target_exchange = producing_exchange(schedule.stages[dependency]); + if (target_exchange) { + if (!target_exchange->finishes) { + return false; + } + } else if (!stage_live[dependency]) { + return false; + } + } + return true; + }; + // The exchange's producers must be able to run: a live exchange with a producer that is itself gated would + // wrongly resolve the finalization waits of its consumers. Ordering between the exchange's own producer + // pipelines (a UNION's later branches wait on the base pipeline) resolves with the exchange itself and must + // not count as a gate. + auto producers_startable = [&](const ExchangeLiveness &exchange) { + for (auto &entry : producer_execute_stages) { + if (&entry.first.get() != &exchange) { + continue; + } + auto &stage = schedule.stages[entry.second]; + for (auto dependency : stage.dependencies) { + if (stage_live[dependency] || producing_exchange(schedule.stages[dependency]).get() == &exchange) { + continue; + } + return false; + } + for (auto dependency : stage.analysis_dependencies) { + if (stage_live[dependency] || is_own_producer_eof(stage, dependency)) { + continue; + } + auto target_exchange = producing_exchange(schedule.stages[dependency]); + if (target_exchange && (target_exchange->live || target_exchange.get() == &exchange)) { + continue; + } + return false; + } + } + return true; + }; + + bool changed = true; + while (changed) { + changed = false; + for (auto &entry : exchanges) { + auto &exchange = entry.second; + if (exchange.live) { + continue; + } + if (!producers_startable(exchange)) { + continue; + } + bool all_draining = true; + if (!exchange.has_direct) { + // A direct consumer creates the shared spool; otherwise every buffered consumer must be able + // to start (everything its execute waits on is live) and to drain (its own sink's exchange + // is live). + for (auto &record_ref : exchange.records) { + auto &record = record_ref.get(); + auto execute_stage = record_execute_stage(record); + if (!execute_stage.IsValid()) { + continue; + } + if (!dependencies_live(schedule.stages[execute_stage.GetIndex()])) { + all_draining = false; + break; + } + // Only CTE exchange sinks are modeled as drain obstacles. Blocking batch sinks (batch + // INSERT/COPY) cannot stall a consumer here because PhysicalUnion::BuildPipelines forces + // ordering edges between sibling pipelines whenever the sink requires a batch index, which + // makes that gate visible as scheduled dependencies. + auto consumer_sink_exchange = stage_producing_exchange[execute_stage.GetIndex()]; + if (consumer_sink_exchange && !consumer_sink_exchange->live) { + all_draining = false; + break; + } + } + } + if (all_draining) { + exchange.live = true; + changed = true; + } + } + for (auto &entry : exchanges) { + auto &exchange = entry.second; + if (!exchange.live || exchange.finishes) { + continue; + } + // EOF requires every producer's own dataflow inputs to finish as well. CTE references are acyclic, + // so this grounds out at exchanges whose producers read no other exchange. + bool inputs_finish = true; + for (auto &producer_entry : producer_execute_stages) { + if (&producer_entry.first.get() != &exchange) { + continue; + } + for (auto &dataflow : schedule.stages[producer_entry.second].pipeline->GetDataflowDependencies()) { + auto producer = dataflow.lock(); + D_ASSERT(producer); + auto upstream = producer_pipeline_exchange.find(*producer); + if (upstream == producer_pipeline_exchange.end() || !upstream->second.get().finishes) { + inputs_finish = false; + break; + } + } + if (!inputs_finish) { + break; + } + } + if (inputs_finish) { + exchange.finishes = true; + changed = true; + } + } + for (idx_t stage_idx = 0; stage_idx < stage_count; stage_idx++) { + if (stage_live[stage_idx]) { + continue; + } + auto &stage = schedule.stages[stage_idx]; + if (!dependencies_live(stage)) { + continue; + } + auto exchange = stage_producing_exchange[stage_idx]; + if (exchange && !exchange->live) { + continue; + } + stage_live[stage_idx] = true; + changed = true; + } + } + + // Collect candidate ordering edges in the dead exchanges' gating regions, in registration order for + // deterministic removal: walk from each record's and producer's execute stage through non-live stages and + // record every execute-to-execute edge onto a non-live dependency. Only edges that are optional orderings + // can actually be removed; the caller filters by attempting the removal. + vector walked(stage_count, false); + auto collect_gating_edges = [&](idx_t seed_stage) { + vector worklist {seed_stage}; + while (!worklist.empty()) { + auto stage_idx = worklist.back(); + worklist.pop_back(); + if (walked[stage_idx]) { + continue; + } + walked[stage_idx] = true; + auto &stage = schedule.stages[stage_idx]; + for (auto dependency : stage.dependencies) { + if (stage_live[dependency]) { + continue; + } + auto &target = schedule.stages[dependency]; + if (stage.type == PipelineScheduleStageType::EXECUTE && + target.type == PipelineScheduleStageType::EXECUTE) { + optional_candidates.emplace_back(*stage.pipeline, *target.pipeline); + } + worklist.push_back(dependency); + } + for (auto dependency : stage.analysis_dependencies) { + if (is_own_producer_eof(stage, dependency)) { + // Exempted waits are not gates, so descending through them only surfaces noise candidates. + continue; + } + // An EOF wait resolves through the target exchange's finishes bit, so the gate can run through + // a live-but-unfinishing exchange even when the finish stage itself is live. + auto target_exchange = producing_exchange(schedule.stages[dependency]); + if (!stage_live[dependency] || (target_exchange && !target_exchange->finishes)) { + worklist.push_back(dependency); + } + } + } + }; + for (auto &record : data.buffered_consumers) { + if (record.demoted) { + continue; + } + auto entry = exchanges.find(record.cte.get()); + if (entry == exchanges.end() || entry->second.live) { + continue; + } + auto execute_stage = record_execute_stage(record); + if (execute_stage.IsValid()) { + collect_gating_edges(execute_stage.GetIndex()); + } + for (auto &producer_entry : producer_execute_stages) { + if (&producer_entry.first.get() == &entry->second) { + collect_gating_edges(producer_entry.second); + } + } + } + + // Select the victim in registration order: the exchange map is keyed by pointers, and an address-dependent + // choice would make the demoted side of mutually gated exchanges differ across runs. + optional_ptr fallback; + for (auto &record : data.buffered_consumers) { + if (record.demoted) { + continue; + } + auto entry = exchanges.find(record.cte.get()); + if (entry == exchanges.end() || entry->second.live) { + continue; + } + // Prefer a consumer that cannot start, otherwise any consumer of a dead exchange. + auto execute_stage = record_execute_stage(record); + if (execute_stage.IsValid() && !dependencies_live(schedule.stages[execute_stage.GetIndex()])) { + return &record; + } + if (!fallback) { + fallback = &record; + } + } + return fallback; +} + void PipelineBuildState::AddCTEPipelineSelection(PhysicalCTE &cte, Pipeline &pipeline, shared_ptr cte_dependency, bool dependency_added) { D_ASSERT(data->cte_selection_map.find(cte) == data->cte_selection_map.end()); @@ -1029,11 +1420,15 @@ void PipelineBuildState::AddCTEPipelineSelection(PhysicalCTE &cte, Pipeline &pip data->cte_selections.emplace_back(cte, pipeline, std::move(cte_dependency), dependency_added); } -void PipelineBuildState::ResolveExternalInputs(const vector> &meta_pipelines) { - if (data->external_input_candidates.empty()) { - return; +unique_ptr +PipelineBuildState::ResolveExternalInputs(const vector> &meta_pipelines, + bool model_runtime_filter_edges) { + if (data->external_input_candidates.empty() && data->buffered_consumers.empty()) { + return nullptr; + } + if (!data->external_input_candidates.empty()) { + SelectExternalInputCandidates(*data); } - SelectExternalInputCandidates(*data); auto activate_candidate = [&](PipelineExternalInputCandidate &candidate) { D_ASSERT(candidate.UsesExternalInput()); auto &pipeline = candidate.pipeline.get(); @@ -1072,12 +1467,58 @@ void PipelineBuildState::ResolveExternalInputs(const vector removed_dependencies; + unique_ptr validated_schedule; while (true) { auto schedule = BuildPipelineSchedule(meta_pipelines); + if (model_runtime_filter_edges) { + // The executor adds runtime-filter ordering edges to the final schedule under the same condition + // (Executor::ScheduleEventsInternal, initial schedule without recursive CTEs). Cycle detection and + // the exchange liveness analysis must see those edges: an edge they never saw can gate a buffered + // exchange consumer invisibly and deadlock the producer at the exchange watermark. The selection is + // a deterministic function of the schedule graph, so the final iteration models exactly the edges + // the executor will add. The suppression check inside the selection already refuses edges that would + // cycle through streaming EOF waits, so an admitted edge cannot close a WITH_ANALYSIS cycle; it can + // still gate a consumer through producer backpressure, which the liveness analysis resolves. + AddRuntimeFilterScheduleDependencies(*schedule); + } auto cycle = schedule->GetCycle(); if (cycle.empty()) { - break; + vector, reference>> optional_candidates; + auto starved = FindExchangeStarvedBufferedConsumer(*data, *schedule, optional_candidates); + if (!starved) { + validated_schedule = std::move(schedule); + break; + } + // An optional ordering (cross product and union siblings) in the gating region can starve the + // exchange. Dropping the ordering preserves streaming and beats a full materialization, so try + // that before demoting, mirroring the cycle path below. + bool removed_optional = false; + for (auto &candidate : optional_candidates) { + if (MetaPipeline::RemoveOptionalDependency(candidate.first.get(), candidate.second.get())) { + removed_dependencies.emplace_back(candidate.first.get(), candidate.second.get()); + removed_optional = true; + break; + } + } + if (removed_optional) { + continue; + } + demote_buffered_consumer(*starved); + RestoreOptionalDependencies(removed_dependencies); + continue; } if (RemoveOptionalDependencyInCycle(*schedule, cycle, removed_dependencies)) { continue; @@ -1090,6 +1531,27 @@ void PipelineBuildState::ResolveExternalInputs(const vector 0; removed_idx--) { + auto &removed = removed_dependencies[removed_idx - 1]; + MetaPipeline::AddOptionalDependency(removed.pipeline, removed.dependency); + auto probe_schedule = BuildPipelineSchedule(meta_pipelines); + if (model_runtime_filter_edges) { + AddRuntimeFilterScheduleDependencies(*probe_schedule); + } + vector, reference>> probe_candidates; + if (!probe_schedule->HasCycle() && + !FindExchangeStarvedBufferedConsumer(*data, *probe_schedule, probe_candidates)) { + validated_schedule = std::move(probe_schedule); + removed_dependencies.erase(removed_dependencies.begin() + NumericCast(removed_idx - 1)); + } else { + MetaPipeline::RemoveOptionalDependency(removed.pipeline, removed.dependency); + } + } + for (auto &candidate : data->external_input_candidates) { auto &pipeline = candidate.pipeline.get(); auto &cte = candidate.cte.get(); @@ -1111,7 +1573,18 @@ void PipelineBuildState::ResolveExternalInputs(const vectorcte_selections) { selection.cte.get().SetPipelineSelectionResolved(); } - D_ASSERT(!BuildPipelineSchedule(meta_pipelines)->HasCycle()); +#ifdef D_ASSERT_IS_ENABLED + { + auto final_schedule = BuildPipelineSchedule(meta_pipelines); + if (model_runtime_filter_edges) { + AddRuntimeFilterScheduleDependencies(*final_schedule); + } + D_ASSERT(!final_schedule->HasCycle()); + } +#endif + // Hand the validated graph to the executor: the consumer registrations above change modes and batch + // preferences, never schedule edges, so this is the graph the analysis proved live and acyclic. + return validated_schedule; } } // namespace duckdb diff --git a/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp b/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp index 84db381bd..aa4a1688d 100644 --- a/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp +++ b/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp @@ -713,6 +713,26 @@ void PipelineBroadcastExchange::SelectBufferedConsumer(idx_t consumer_idx, } } +void PipelineBroadcastExchange::DemoteBufferedConsumerToMaterialized(idx_t consumer_idx) { + // Pre-execution demotion of a buffered consumer that the schedule gates behind its own producer's + // completion: it could never drain the exchange, so serve it from CTE storage instead. + annotated_lock_guard guard(lock); + D_ASSERT(consumer_idx < consumers.size()); + auto &consumer = consumers[consumer_idx]; + D_ASSERT(consumer.mode == PipelineBroadcastExchangeConsumerMode::BUFFERED); + consumer.mode = PipelineBroadcastExchangeConsumerMode::MATERIALIZED; + consumer.scan_mode = PipelineBroadcastExchangeScanMode::CHUNK; + DeactivateConsumerLocked(consumer, buffer->NextPosition()); + has_batch_scan_consumer = false; + for (auto &entry : consumers) { + if (entry.mode == PipelineBroadcastExchangeConsumerMode::BUFFERED && + entry.scan_mode == PipelineBroadcastExchangeScanMode::BATCH) { + has_batch_scan_consumer = true; + break; + } + } +} + void PipelineBroadcastExchange::ResetConsumerRegistrations() { annotated_lock_guard guard(lock); buffer->EndExecution(); diff --git a/src/duckdb/src/parallel/pipeline_schedule.cpp b/src/duckdb/src/parallel/pipeline_schedule.cpp index ae6c9b6b4..170e8a0c9 100644 --- a/src/duckdb/src/parallel/pipeline_schedule.cpp +++ b/src/duckdb/src/parallel/pipeline_schedule.cpp @@ -53,7 +53,23 @@ static optional_ptr GetExternalInputConsumer(const PipelineSchedule &s enum class CycleVisitState : uint8_t { UNVISITED, VISITING, VISITED }; -vector PipelineSchedule::GetCycle() const { +vector PipelineSchedule::GetCycle(PipelineScheduleGraph graph) const { + auto dependency_count = [&](const PipelineScheduleStage &stage) { + auto count = stage.dependencies.size(); + if (graph == PipelineScheduleGraph::WITH_ANALYSIS) { + count += stage.analysis_dependencies.size(); + } + return count; + }; + // Combined indices address the scheduled dependencies first, then the analysis dependencies. External-input + // tags always store indices below the scheduled-dependency count, so a combined index of an analysis edge can + // never falsely match a tag in GetExternalInputConsumer. + auto get_dependency = [&](const PipelineScheduleStage &stage, idx_t dependency_idx) { + if (dependency_idx < stage.dependencies.size()) { + return stage.dependencies[dependency_idx]; + } + return stage.analysis_dependencies[dependency_idx - stage.dependencies.size()]; + }; vector states(stages.size(), CycleVisitState::UNVISITED); for (idx_t stage_idx = 0; stage_idx < stages.size(); stage_idx++) { if (states[stage_idx] != CycleVisitState::UNVISITED) { @@ -64,13 +80,13 @@ vector PipelineSchedule::GetCycle() const { states[stage_idx] = CycleVisitState::VISITING; while (!stack.empty()) { auto &entry = stack.back(); - auto &dependencies = stages[entry.first].dependencies; - if (entry.second == dependencies.size()) { + auto &stage = stages[entry.first]; + if (entry.second == dependency_count(stage)) { states[entry.first] = CycleVisitState::VISITED; stack.pop_back(); continue; } - auto dependency = dependencies[entry.second++]; + auto dependency = get_dependency(stage, entry.second++); D_ASSERT(dependency < stages.size()); if (states[dependency] == CycleVisitState::UNVISITED) { states[dependency] = CycleVisitState::VISITING; @@ -89,7 +105,7 @@ vector PipelineSchedule::GetCycle() const { for (idx_t path_idx = cycle_start; path_idx + 1 < stack.size(); path_idx++) { auto dependent = stack[path_idx].first; auto dependency_idx = stack[path_idx].second - 1; - result.emplace_back(dependent, stages[dependent].dependencies[dependency_idx], + result.emplace_back(dependent, get_dependency(stages[dependent], dependency_idx), GetExternalInputConsumer(*this, dependent, dependency_idx)); } auto dependent = stack.back().first; @@ -101,8 +117,8 @@ vector PipelineSchedule::GetCycle() const { return {}; } -bool PipelineSchedule::HasCycle() const { - return !GetCycle().empty(); +bool PipelineSchedule::HasCycle(PipelineScheduleGraph graph) const { + return !GetCycle(graph).empty(); } bool PipelineSchedule::DependsOn(idx_t dependent, idx_t dependency) const { @@ -235,7 +251,8 @@ unique_ptr BuildPipelineSchedule(const vectorsecond.complete); } } - // A dataflow dependency only needs the producer's source and sink state to be initialized. + // A dataflow dependency only needs the producer's source and sink state to be initialized to start. + // The completion-ordering constraint is added in a separate pass below. for (auto &dependency : pipeline.GetDataflowDependencies()) { auto dep = dependency.lock(); D_ASSERT(dep); @@ -275,6 +292,10 @@ unique_ptr BuildPipelineSchedule(const vectorType() != MetaPipelineType::JOIN_BUILD) { continue; } + // Small builds can finalize without coordinating memory reservations with their siblings. + if (child1->GetSink()->children[1].get().estimated_cardinality < 1000000) { + continue; + } auto child1_entry = stage_map.find(*child1->GetBasePipeline()); if (child1_entry == stage_map.end()) { if (!allow_missing_meta_pipelines) { @@ -347,6 +368,41 @@ unique_ptr BuildPipelineSchedule(const vector> dataflow_finish_stages; + for (auto &entry : stage_map) { + for (auto &dependency : entry.first.get().GetDataflowDependencies()) { + auto dep = dependency.lock(); + D_ASSERT(dep); + auto dep_entry = stage_map.find(*dep); + if (dep_entry != stage_map.end()) { + dataflow_finish_stages[entry.second.execute].push_back(dep_entry->second.finish); + } + } + } + if (!dataflow_finish_stages.empty()) { + for (idx_t stage_idx = 0; stage_idx < result->stages.size(); stage_idx++) { + for (auto dependency : result->stages[stage_idx].dependencies) { + auto finish_entry = dataflow_finish_stages.find(dependency); + if (finish_entry == dataflow_finish_stages.end()) { + continue; + } + for (auto finish_stage : finish_entry->second) { + if (finish_stage != stage_idx) { + result->stages[stage_idx].analysis_dependencies.push_back(finish_stage); + } + } + } + } + } + return result; } diff --git a/src/duckdb/src/parallel/runtime_filter_schedule.cpp b/src/duckdb/src/parallel/runtime_filter_schedule.cpp index b0dfe976b..e13692990 100644 --- a/src/duckdb/src/parallel/runtime_filter_schedule.cpp +++ b/src/duckdb/src/parallel/runtime_filter_schedule.cpp @@ -69,7 +69,38 @@ static vector CollectJoinBuildStages(const PipelineSchedule &schedule) { return build_stages; } -void ScheduleRuntimeFilters(PipelineSchedule &schedule) { +static PipelineSchedule RuntimeFilterDependencyCheck(const PipelineSchedule &schedule) { + PipelineSchedule result; + result.stages = schedule.stages; + reference_map_t completions; + for (idx_t i = 0; i < result.stages.size(); i++) { + auto &stage = result.stages[i]; + if (stage.type == PipelineScheduleStageType::COMPLETE) { + completions.emplace(*stage.pipeline, i); + } + } + for (auto &stage : result.stages) { + if (stage.type != PipelineScheduleStageType::EXECUTE) { + continue; + } + // Streaming consumers can wait for producer rows despite depending only on initialization. + for (auto &dependency : stage.pipeline->GetDataflowDependencies()) { + auto producer = dependency.lock(); + D_ASSERT(producer); + auto completion = completions.find(*producer); + if (completion != completions.end()) { + stage.dependencies.push_back(completion->second); + } + } + } + return result; +} + +// The dependency check above refuses edges that would cycle through streaming EOF waits. Edges that pass it can +// still gate a buffered exchange consumer through producer backpressure, which is not a cycle in the augmented +// graph; the exchange liveness analysis in ResolveExternalInputs handles those. Both edge-adding call paths go +// through this one function, so the analysis always sees the edge set the executor runs. +static void ScheduleRuntimeFiltersInternal(PipelineSchedule &schedule, bool clear_filters, bool add_edges) { reference_map_t> publications; vector> producers; for (idx_t stage_idx = 0; stage_idx < schedule.stages.size(); stage_idx++) { @@ -90,24 +121,35 @@ void ScheduleRuntimeFilters(PipelineSchedule &schedule) { return; } - auto join_build_stages = CollectJoinBuildStages(schedule); + // The clear-only path never adds edges, so the admission state is not needed there. + PipelineSchedule dependency_check; + vector join_build_stages; + if (add_edges) { + dependency_check = RuntimeFilterDependencyCheck(schedule); + join_build_stages = CollectJoinBuildStages(schedule); + } reference_map_t> sources; - for (idx_t stage_idx = 0; stage_idx < schedule.stages.size(); stage_idx++) { + 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; auto source = pipeline.GetSource(); - if (stage.type != PipelineScheduleStageType::EXECUTE || join_build_stages[stage_idx] || !source || + if (stage.type != PipelineScheduleStageType::EXECUTE || !source || source->type != PhysicalOperatorType::TABLE_SCAN || pipeline.HasSourceState() || pipeline.IsExternalInput()) { continue; } auto &scan = source->Cast(); if (!scan.dynamic_filters || - scan.function.global_initialization == TableFunctionInitialization::INITIALIZE_ON_SCHEDULE || - (scan.table_filters && (scan.table_filters->HasFilters() || scan.table_filters->HasMultiColumnFilters()))) { + scan.function.global_initialization == TableFunctionInitialization::INITIALIZE_ON_SCHEDULE) { continue; } - sources[*scan.dynamic_filters].push_back(stage_idx); + 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); + } + for (auto &filters : scan.dynamic_filters->GetDisjunctionFilters()) { + sources[filters.get()].push_back(stage_idx); + } } for (auto &producer_ref : producers) { @@ -116,18 +158,43 @@ void ScheduleRuntimeFilters(PipelineSchedule &schedule) { auto build_estimate = producer.children[1].get().estimated_cardinality; auto probe_estimate = producer.children[0].get().estimated_cardinality; for (auto &target : producer.filter_pushdown->probe_info) { - // Clear previous executions before any scan can take its filter snapshot. - target.dynamic_filters->ClearFilters(producer); + if (clear_filters) { + // Clear previous executions before any scan can take its filter snapshot. + target.dynamic_filters->ClearFilters(producer); + } + if (!add_edges) { + continue; + } auto source = sources.find(*target.dynamic_filters); if (publication.size() != 1 || source == sources.end() || build_estimate >= MaxValue(probe_estimate, target.estimated_scan_cardinality)) { continue; } for (auto execution : source->second) { - schedule.TryAddDependency(execution, publication[0]); + if (dependency_check.TryAddDependency(execution, publication[0])) { + schedule.TryAddDependency(execution, publication[0]); + } } } } } +void ScheduleRuntimeFilters(PipelineSchedule &schedule) { + // Executor entry point when no resolved schedule was handed over: adds the ordering edges and clears stale + // filters before any scan snapshot (clearing is idempotent and sink initialization clears again). + ScheduleRuntimeFiltersInternal(schedule, true, true); +} + +void ClearRuntimeFilters(PipelineSchedule &schedule) { + // Executor entry point for a schedule reused from ResolveExternalInputs: the ordering edges are already in + // the graph the analysis validated, so only the stale filters need clearing. + ScheduleRuntimeFiltersInternal(schedule, true, false); +} + +void AddRuntimeFilterScheduleDependencies(PipelineSchedule &schedule) { + // Pure edge addition for the schedules ResolveExternalInputs analyzes: no filter clearing, which belongs to + // the executor pass on the final schedule. + ScheduleRuntimeFiltersInternal(schedule, false, true); +} + } // namespace duckdb diff --git a/src/duckdb/src/parallel/scan_read_ahead.cpp b/src/duckdb/src/parallel/scan_read_ahead.cpp index 77f75a89d..edd56bf2a 100644 --- a/src/duckdb/src/parallel/scan_read_ahead.cpp +++ b/src/duckdb/src/parallel/scan_read_ahead.cpp @@ -71,6 +71,8 @@ class ReadAheadIOTask : public BaseExecutorTask { completion->AddIOTask(); } ~ReadAheadIOTask() override { + // release the task's resources before waking the scan, they may outlive the database otherwise + task.reset(); // If we are done we decrement the pending completion->FinishIOTask(); } @@ -83,6 +85,8 @@ class ReadAheadIOTask : public BaseExecutorTask { // recording the error through the read-ahead also wakes the threads waiting for progress read_ahead.PushError(ErrorData(ex)); } + // release the task's resources while the executor still counts this task as running + task.reset(); } private: @@ -177,7 +181,7 @@ unique_ptr ScanReadAhead::Create(ClientContext &context) { if (configured_depth < 0) { // automatic mode, unlimited depth, the backlog is bounded by a temp-memory reservation instead return make_uniq(context, NumericLimits::Maximum(), - make_uniq(context)); + make_uniq(context.GetContext())); } return make_uniq(context, NumericCast(configured_depth), nullptr); } diff --git a/src/duckdb/src/parallel/task_executor.cpp b/src/duckdb/src/parallel/task_executor.cpp index 566f40891..152d7c527 100644 --- a/src/duckdb/src/parallel/task_executor.cpp +++ b/src/duckdb/src/parallel/task_executor.cpp @@ -1,6 +1,8 @@ #include "duckdb/parallel/task_executor.hpp" #include "duckdb/parallel/task_notifier.hpp" #include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { @@ -108,9 +110,13 @@ TaskExecutor::TaskExecutor(TaskScheduler &scheduler, TaskSchedulerType type_p) : scheduler(scheduler), type(type_p), token(scheduler.CreateProducer()) { } -TaskExecutor::TaskExecutor(ClientContext &context_p, TaskSchedulerType type_p) - : TaskExecutor(TaskScheduler::GetScheduler(context_p), type_p) { - context = context_p; +TaskExecutor::TaskExecutor(ClientContext &context, TaskSchedulerType type_p) + : TaskExecutor(context.GetContext(), type_p) { +} + +TaskExecutor::TaskExecutor(Context &context_p, TaskSchedulerType type_p) + : TaskExecutor(context_p.GetTaskScheduler(), type_p) { + context = &context_p; } TaskExecutor::~TaskExecutor() { diff --git a/src/duckdb/src/parallel/task_notifier.cpp b/src/duckdb/src/parallel/task_notifier.cpp index 4b1eb34ed..fd686d95f 100644 --- a/src/duckdb/src/parallel/task_notifier.cpp +++ b/src/duckdb/src/parallel/task_notifier.cpp @@ -1,18 +1,19 @@ #include "duckdb/parallel/task_notifier.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_context_state.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { -TaskNotifier::TaskNotifier(optional_ptr context_p) : context(context_p) { - if (context) { - context->registered_state->ForEachState([&](ClientContextState &state) { state.OnTaskStart(*context); }); +TaskNotifier::TaskNotifier(optional_ptr context_p) : context(context_p) { + if (context && context->IsClient()) { + context->GetRegisteredState().ForEachState([&](ClientContextState &state) { state.OnTaskStart(*context); }); } } TaskNotifier::~TaskNotifier() { - if (context) { - context->registered_state->ForEachState([&](ClientContextState &state) { state.OnTaskStop(*context); }); + if (context && context->IsClient()) { + context->GetRegisteredState().ForEachState([&](ClientContextState &state) { state.OnTaskStop(*context); }); } } diff --git a/src/duckdb/src/parallel/task_scheduler.cpp b/src/duckdb/src/parallel/task_scheduler.cpp index b5d0c2b0c..358b9f826 100644 --- a/src/duckdb/src/parallel/task_scheduler.cpp +++ b/src/duckdb/src/parallel/task_scheduler.cpp @@ -27,7 +27,7 @@ namespace duckdb { -TaskScheduler::TaskScheduler(DatabaseInstance &db) : db(db) { +TaskScheduler::TaskScheduler(DatabaseInstance &db) : db(db), relaunch_requested(true) { for (uint8_t i = 0; i < TASK_SCHEDULER_TYPE_COUNT; i++) { pools[i] = make_uniq(db, static_cast(i)); queues[i] = make_uniq(static_cast(i)); @@ -93,6 +93,7 @@ TaskSchedulerQueue &TaskScheduler::GetQueue(TaskSchedulerType pool_type) const { void TaskScheduler::SetThreadsInternal(TaskSchedulerType pool_type, idx_t n) { GetPool(pool_type).SetThreads(n); + relaunch_requested = true; } void TaskScheduler::ScheduleTask(ProducerToken &token, shared_ptr task, TaskSchedulerType pool_type) { @@ -510,7 +511,11 @@ idx_t TaskScheduler::GetEstimatedCPUId() { } void TaskScheduler::RelaunchThreads() { + if (!relaunch_requested) { + return; + } lock_guard t(thread_lock); + relaunch_requested = false; for (auto &pool : pools) { pool->RelaunchThreads(*this, false); } diff --git a/src/duckdb/src/parallel/thread_context.cpp b/src/duckdb/src/parallel/thread_context.cpp index 4eaced452..c91dfa255 100644 --- a/src/duckdb/src/parallel/thread_context.cpp +++ b/src/duckdb/src/parallel/thread_context.cpp @@ -22,7 +22,7 @@ ThreadContext::ThreadContext(ClientContext &context) : profiler(context) { } log_context.thread_id = TaskScheduler::GetEstimatedCPUId(); - logger = LogManager::Get(context).CreateLogger(log_context, true); + logger = LogManager::Get(context).CreateLogger(log_context, context.GetLogConfig()); } ThreadContext::~ThreadContext() { diff --git a/src/duckdb/src/parser/column_definition.cpp b/src/duckdb/src/parser/column_definition.cpp index 1f6550cc5..6d95fd955 100644 --- a/src/duckdb/src/parser/column_definition.cpp +++ b/src/duckdb/src/parser/column_definition.cpp @@ -228,6 +228,10 @@ const ParsedExpression &ColumnDefinition::GeneratedExpression() const { return *expression; } +bool ColumnDefinition::HasGeneratedExpression() const { + return expression != nullptr; +} + ParsedExpression &ColumnDefinition::GeneratedExpressionMutable() { D_ASSERT(Generated()); return *expression; diff --git a/src/duckdb/src/parser/literal.cpp b/src/duckdb/src/parser/literal.cpp index d5f83a698..3f4a50e91 100644 --- a/src/duckdb/src/parser/literal.cpp +++ b/src/duckdb/src/parser/literal.cpp @@ -151,13 +151,13 @@ static Value NumberToValue(const string &val) { if (try_cast_as_decimal && decimal_position.IsValid() && str_val.GetSize() - num_underscores < Decimal::MAX_WIDTH_DECIMAL + decimal_offset) { // figure out the width/scale based on the decimal position - auto width = NumericCast(str_val.GetSize() - 1 - num_underscores); + auto width = NumericCast(str_val.GetSize() - 1 - num_underscores); // a well-formed decimal has a single '.', so its position never sits past the width; a second (e.g. trailing) // dot pushes decimal_position beyond width and would underflow the scale computation below if (decimal_position.GetIndex() > NumericCast(width) + num_integer_underscores) { throw ParserException("Could not convert string \"%s\" to a decimal value", val); } - auto scale = NumericCast(width - decimal_position.GetIndex() + num_integer_underscores); + auto scale = NumericCast(width - decimal_position.GetIndex() + num_integer_underscores); if (val[0] == '-') { width--; } diff --git a/src/duckdb/src/parser/parser.cpp b/src/duckdb/src/parser/parser.cpp index a4340c311..a698e893a 100644 --- a/src/duckdb/src/parser/parser.cpp +++ b/src/duckdb/src/parser/parser.cpp @@ -14,6 +14,8 @@ #include "duckdb/parser/statement/update_statement.hpp" #include "duckdb/parser/query_node/update_query_node.hpp" #include "duckdb/parser/tableref/expressionlistref.hpp" +#include "duckdb/parser/peg/matcher.hpp" +#include "duckdb/parser/peg/parser_packrat.hpp" #include "duckdb/parser/peg/transformer/peg_transformer.hpp" #include "duckdb/parser/peg/syntax_error.hpp" #include "duckdb/parser/peg/tokenizer/parser_tokenizer.hpp" @@ -389,6 +391,117 @@ unique_ptr Parser::ParseTopLevelStatement(TokenIterator &token_ite throw PEGSyntaxError::Create(token_iterator, statement_start, failure_index.GetIndex(), compiled_grammar, options); } +//! Tokenizes like ParserTokenizerBehavior, but pushes unterminated trailing tokens with their +//! `unterminated` flag set instead of throwing - completeness checks treat them as "needs more input". +class CompletenessTokenizerBehavior : public TokenizerBehavior { +public: + using TokenizerBehavior::TokenizerBehavior; + + //! The input ended inside a block comment or dollar-quoted string - the token itself may be + //! dropped from the stream (comments), so the flag has to be recorded here + bool unterminated_input = false; + //! The input holds a token the parser tokenizer rejects outright - no continuation can repair it + bool fatal_token = false; + + void PushToken(idx_t start, idx_t end, TokenType type, bool unterminated = false) override { + if (unterminated) { + unterminated_input = true; + } + if (ParserTokenizerBehavior::IsEmptyQuotedIdentifier(sql, start, end, type)) { + fatal_token = true; + } + TokenizerBehavior::PushToken(start, end, type, unterminated); + } + + void OnStatementEnd(idx_t pos) override { + tokens.emplace_back(";", pos, TokenType::TERMINATOR); + } +}; + +bool Parser::IsQueryComplete(const string &query_p) { + string query; + try { + query = NormalizeSQLString(query_p); + } catch (ParserException &) { + // invalid UTF-8 - submit the input so the error surfaces + return true; + } + auto &grammar = GetGrammar(); + auto owned_tokens = make_uniq>(); + CompletenessTokenizerBehavior behavior(query, *owned_tokens); + grammar.GetTokenizer().TokenizeInput(behavior); + if (behavior.fatal_token) { + // no continuation can repair the input - submit it so the error surfaces + return true; + } + if (behavior.unterminated_input) { + return false; + } + // the final statement must be terminated by a top-level semicolon + bool terminated = false; + for (auto &token : *owned_tokens) { + switch (token.type) { + case TokenType::END_OF_INPUT: + case TokenType::END_OF_INPUT_AUTOCOMPLETE: + break; + default: + if (token.unterminated) { + // the input ends inside a string, quoted identifier, comment or dollar-quoted string + return false; + } + terminated = token.type == TokenType::TERMINATOR; + break; + } + } + if (!terminated) { + return false; + } + TokenIterator token_iterator(std::move(owned_tokens)); + 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 + vector suggestions; + ParseResultAllocator parse_result_allocator; + ArenaAllocator process_allocator(Allocator::DefaultAllocator()); + ArenaAllocator packrat_allocator(Allocator::DefaultAllocator()); + ParserPackratCache packrat_cache(packrat_allocator, token_iterator.Position(), token_iterator.Size()); + idx_t max_token_index = token_iterator.Position(); + MatchContext match_context(suggestions, parse_result_allocator, process_allocator, max_token_index, + MatchMode::BUILD_PARSE_RESULT, options.identifier_case_mode, &packrat_cache); + MatchState state(token_iterator, match_context); + bool success = false; + try { + auto match_result = grammar.TopLevelStatementMatcher().MatchParseResult(state); + success = match_result.IsSuccess(); + if (!success) { + auto index = MinValue(state.GetMaxTokenIndex(), token_iterator.Size() - 1); + if (token_iterator.GetToken(index).type == TokenType::END_OF_INPUT) { + // the parse failed at the end of the input - more input can complete the statement + return false; + } + } + } catch (ParserException &) { + // the matcher rejected the input outright, e.g. a malformed numeric literal + } + if (success) { + token_iterator.SetPosition(state.token_iterator); + continue; + } + // a parse_function extension may claim the rejected segment, as in ParseQuery + try { + auto ext_stmt = TryParseExtensionStatement(token_iterator, query); + if (ext_stmt) { + continue; + } + } catch (ParserException &) { + // the extension rejected the segment with an error of its own + } + // rejected mid-input - submit it so the error surfaces on execution + return true; + } + return true; +} + vector Parser::Tokenize(const string &query) { auto &keyword_helper = DuckDBKeywordHelper::Instance(); vector tokens; diff --git a/src/duckdb/src/parser/peg/autocomplete_core.cpp b/src/duckdb/src/parser/peg/autocomplete_core.cpp index 401f4b4ba..030e47fb9 100644 --- a/src/duckdb/src/parser/peg/autocomplete_core.cpp +++ b/src/duckdb/src/parser/peg/autocomplete_core.cpp @@ -1,5 +1,6 @@ #include "duckdb/parser/peg/autocomplete_catalog_provider.hpp" #include "duckdb/parser/peg/compiled_grammar.hpp" +#include "duckdb/parser/peg/parser_packrat.hpp" #include "duckdb/common/case_insensitive_map.hpp" #include "duckdb/parser/keyword_helper.hpp" #include "duckdb/parser/parser.hpp" @@ -214,8 +215,11 @@ vector GenerateAutoCompleteSuggestions(AutoCompleteCatal // run the root matcher TokenIterator token_iterator(tokens); ArenaAllocator process_allocator(Allocator::DefaultAllocator()); + // memoize match results so backtracking over unbalanced input stays polynomial + ArenaAllocator packrat_allocator(Allocator::DefaultAllocator()); + ParserPackratCache packrat_cache(packrat_allocator, token_iterator.Position(), token_iterator.Size()); MatchContext match_context(suggestions, parse_allocator, process_allocator, max_token_index, - MatchMode::RECOGNIZE_ONLY, IdentifierCaseMode::PRESERVE_CASE); + MatchMode::RECOGNIZE_ONLY, IdentifierCaseMode::PRESERVE_CASE, &packrat_cache); MatchState state(token_iterator, match_context); compiled_grammar->ProgramMatcher().MatchParseResult(state); } diff --git a/src/duckdb/src/parser/peg/matcher.cpp b/src/duckdb/src/parser/peg/matcher.cpp index a38ac2ea3..9d49dc224 100644 --- a/src/duckdb/src/parser/peg/matcher.cpp +++ b/src/duckdb/src/parser/peg/matcher.cpp @@ -57,7 +57,7 @@ SuggestionType Matcher::AddLabelledSuggestion(MatchState &state) const { return AddSuggestionInternal(state); } context.active_label = label; - if (context.memoizable_suggestions) { + if (context.memoizable_suggestions && !context.expand_labels) { // only the label is reported, so the rule is not walked; labelled rules never match empty input state.AddSuggestion(MatcherSuggestion(SuggestionState::SUGGEST_VARIABLE)); context.active_label = nullptr; diff --git a/src/duckdb/src/parser/peg/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index 772ef6a98..137cb1f4d 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -434,6 +434,8 @@ static const char *const PEG_RULE_NAMES[] = { "TargetAlias", "DeleteUsingClause", "DescribeStatement", + "ShowExternalResources", + "ShowExternalResourcesType", "ShowDeprecatedSelect", "DescribeSelect", "ShowAllTables", @@ -553,6 +555,11 @@ static const char *const PEG_RULE_NAMES[] = { "SubqueryNot", "SubqueryExists", "CaseExpression", + "SimpleCaseExpression", + "SearchedCaseExpression", + "SimpleCaseWhenThen", + "SimpleCaseWhenOperand", + "SimpleCaseWhenEquals", "CaseWhenThen", "CaseElse", "TypeLiteral", @@ -689,6 +696,8 @@ static const char *const PEG_RULE_NAMES[] = { "OtherOperatorExpression", "InfixOtherOperatorExpression", "OtherOperatorTail", + "AnyAllSubqueryTail", + "OtherOperatorExpressionTail", "OtherOperator", "AnyAllParsedOperator", "NamedOtherOperator", @@ -787,8 +796,6 @@ static const char *const PEG_RULE_NAMES[] = { "CreateExternalResourceStmt", "RegisterExternalResourceStmt", "DestroyExternalResourceStmt", - "ShowExternalResourcesStmt", - "ShowAllModifier", "ExternalResourceKeyword", "ExternalResourceCreationOptions", "AttachToExternalResource", diff --git a/src/duckdb/src/parser/peg/syntax_error.cpp b/src/duckdb/src/parser/peg/syntax_error.cpp index f7ff539d5..4a8129b37 100644 --- a/src/duckdb/src/parser/peg/syntax_error.cpp +++ b/src/duckdb/src/parser/peg/syntax_error.cpp @@ -27,6 +27,9 @@ struct ExpectedTokens { bool AcceptsIdentifiers() const { return !categories.empty() || !labels.empty(); } + bool HasKeyword(const string &keyword) const { + return std::find(keywords.begin(), keywords.end(), keyword) != keywords.end(); + } }; bool IsEndOfInput(const MatcherToken &token) { @@ -102,7 +105,8 @@ const char *CategoryDescription(SuggestionState type) { //! With `suggestions`, the autocomplete cursor at the end of the tokens collects them. //! The parse tree is built and discarded: RECOGNIZE_ONLY mode backtracks several times more on nested input. bool Recognize(vector &statement_tokens, const CompiledGrammar &grammar, const ParserOptions &options, - idx_t &furthest, optional_ptr> suggestions = nullptr) { + idx_t &furthest, optional_ptr> suggestions = nullptr, + bool expand_labels = false) { vector unused_suggestions; ParseResultAllocator parse_result_allocator; ArenaAllocator process_allocator(Allocator::DefaultAllocator()); @@ -113,21 +117,26 @@ bool Recognize(vector &statement_tokens, const CompiledGrammar &gr process_allocator, furthest, MatchMode::BUILD_PARSE_RESULT, options.identifier_case_mode, &packrat_cache); match_context.memoizable_suggestions = suggestions != nullptr; + match_context.expand_labels = expand_labels; TokenIterator token_iterator(statement_tokens); MatchState state(token_iterator, match_context); return grammar.TopLevelStatementMatcher().MatchParseResult(state).IsSuccess(); } -//! Copy the statement's tokens, replacing or inserting one token at `index`. -vector EditedStatement(const TokenIterator &tokens, idx_t statement_start, idx_t index, - const string &text, bool replace) { +enum class EditKind { INSERT, REPLACE, DELETE }; + +//! Copy the statement's tokens with one token inserted before, replaced at, or deleted from `index`. +vector EditedStatement(const TokenIterator &tokens, idx_t statement_start, idx_t index, EditKind kind, + const string &text = string()) { vector result; result.reserve(tokens.Size() - statement_start + 1); for (idx_t i = statement_start; i < tokens.Size(); i++) { if (i == index) { - auto type = IsWordKeyword(text) ? TokenType::KEYWORD : TokenType::OPERATOR; - result.emplace_back(text, tokens.GetToken(i).offset, type); - if (replace) { + if (kind != EditKind::DELETE) { + auto type = IsWordKeyword(text) ? TokenType::KEYWORD : TokenType::OPERATOR; + result.emplace_back(text, tokens.GetToken(i).offset, type); + } + if (kind != EditKind::INSERT) { continue; } } @@ -136,9 +145,19 @@ vector EditedStatement(const TokenIterator &tokens, idx_t statemen return result; } +//! Whether the statement parses after the edit. +bool EditRepairs(const TokenIterator &tokens, idx_t statement_start, idx_t index, EditKind kind, + const CompiledGrammar &grammar, const ParserOptions &options, const string &text = string()) { + auto repaired = EditedStatement(tokens, statement_start, index, kind, text); + idx_t furthest; + return Recognize(repaired, grammar, options, furthest); +} + //! Re-run the grammar on the statement prefix with an autocomplete cursor at `position` to collect what fits there. +//! With `expand_labels` the keywords inside labelled rules are collected as well, for correction candidates. ExpectedTokens ComputeExpectedTokens(const TokenIterator &tokens, idx_t statement_start, idx_t position, - const CompiledGrammar &grammar, const ParserOptions &options) { + const CompiledGrammar &grammar, const ParserOptions &options, + bool expand_labels = false) { vector prefix; prefix.reserve(position - statement_start + 1); for (idx_t i = statement_start; i < position; i++) { @@ -148,7 +167,7 @@ ExpectedTokens ComputeExpectedTokens(const TokenIterator &tokens, idx_t statemen vector suggestions; idx_t furthest; - Recognize(prefix, grammar, options, furthest, &suggestions); + Recognize(prefix, grammar, options, furthest, &suggestions, expand_labels); ExpectedTokens result; case_insensitive_set_t seen_keywords; @@ -164,7 +183,9 @@ ExpectedTokens ComputeExpectedTokens(const TokenIterator &tokens, idx_t statemen } if (suggestion.label) { add_unique(result.labels, *suggestion.label); - continue; + if (suggestion.type != SuggestionState::SUGGEST_KEYWORD) { + continue; + } } if (suggestion.type == SuggestionState::SUGGEST_KEYWORD) { auto &keyword = suggestion.keyword.candidate; @@ -217,7 +238,7 @@ vector SimilarKeywords(const string &token_text, const ExpectedTokens &e //! Does replacing the token at `index` with `replacement` let the parser get past the original failure? bool SubstitutionAdvances(const TokenIterator &tokens, idx_t statement_start, idx_t index, const string &replacement, idx_t error_index, const CompiledGrammar &grammar, const ParserOptions &options) { - auto repaired = EditedStatement(tokens, statement_start, index, replacement, true); + auto repaired = EditedStatement(tokens, statement_start, index, EditKind::REPLACE, replacement); idx_t furthest; if (Recognize(repaired, grammar, options, furthest)) { return true; @@ -231,7 +252,14 @@ string KeywordCorrectionHint(const TokenIterator &tokens, idx_t statement_start, const ExpectedTokens &expected, const CompiledGrammar &grammar, const ParserOptions &options) { static constexpr idx_t MAX_CANDIDATES = 3; - auto candidates = SimilarKeywords(tokens.GetToken(index).text, expected, grammar.GetKeywordHelper()); + vector candidates; + if (expected.labels.empty()) { + candidates = SimilarKeywords(tokens.GetToken(index).text, expected, grammar.GetKeywordHelper()); + } else { + // keywords that start a labelled rule (CASE, CAST, ...) are hidden behind the label - collect them too + auto expanded = ComputeExpectedTokens(tokens, statement_start, index, grammar, options, true); + candidates = SimilarKeywords(tokens.GetToken(index).text, expanded, grammar.GetKeywordHelper()); + } for (idx_t i = 0; i < MinValue(candidates.size(), MAX_CANDIDATES); i++) { if (SubstitutionAdvances(tokens, statement_start, index, candidates[i], error_index, grammar, options)) { return "Did you mean \"" + candidates[i] + "\"?"; @@ -240,42 +268,137 @@ string KeywordCorrectionHint(const TokenIterator &tokens, idx_t statement_start, return string(); } -bool IsRepairCandidate(const string &keyword) { - return IsWordKeyword(keyword) || keyword == "," || keyword == ")" || keyword == "]" || keyword == "}"; -} +//! A token whose insertion repairs the statement, and the index it belongs before. +struct MissingToken { + string text; + idx_t index = 0; +}; -//! Expected tokens whose insertion at the failure point makes the whole statement parse. -vector FindMissingTokens(const TokenIterator &tokens, idx_t statement_start, idx_t error_index, - const ExpectedTokens &expected, const CompiledGrammar &grammar, - const ParserOptions &options) { +//! The missing token at the failure point, if one can be named with confidence. +//! `previous_expected` describes the position one token earlier, where a comma may also be missing. +optional_idx FindMissingToken(const TokenIterator &tokens, idx_t statement_start, idx_t error_index, + const ExpectedTokens &expected, const ExpectedTokens &previous_expected, + const CompiledGrammar &grammar, const ParserOptions &options, MissingToken &result) { // each candidate costs one parse of the statement static constexpr idx_t MAX_REPAIR_CANDIDATES = 32; + // A forgotten comma or closing bracket is by far the most common cause, and the grammar usually also accepts + // an operator keyword there (AND, OR, LIKE) that is rarely what was meant - so punctuation is tried first. + const char *punctuations[] = {",", ")", "]", "}"}; + for (auto punctuation : punctuations) { + if (expected.AcceptsIdentifiers() && punctuation != punctuations[0]) { + // where an identifier would also fit, only a comma is a safe guess + break; + } + if (expected.HasKeyword(punctuation) && + EditRepairs(tokens, statement_start, error_index, EditKind::INSERT, grammar, options, punctuation)) { + result = {punctuation, error_index}; + return result.index; + } + } + // a comma may be missing one token earlier, when the previous word was taken as an alias + if (error_index > statement_start) { + auto &previous = tokens.GetToken(error_index - 1); + if (IsWordToken(previous) && !grammar.GetKeywordHelper().IsKeyword(previous.text) && + previous_expected.HasKeyword(",") && + EditRepairs(tokens, statement_start, error_index - 1, EditKind::INSERT, grammar, options, ",")) { + result = {",", error_index - 1}; + return result.index; + } + } if (expected.AcceptsIdentifiers()) { // a missing identifier cannot be guessed, and a keyword that happens to parse (LIMIT ALL) is rarely meant - return {}; + return optional_idx(); } vector candidates; for (auto &keyword : expected.keywords) { - if (IsRepairCandidate(keyword)) { + if (IsWordKeyword(keyword)) { candidates.push_back(keyword); } } if (candidates.empty() || candidates.size() > MAX_REPAIR_CANDIDATES) { - return {}; + return optional_idx(); } - vector result; + vector repairs; for (auto &candidate : candidates) { - if (result.size() > 1) { - // the caller only acts on a unique repair + if (repairs.size() > 1) { + // only a unique keyword repair is reported break; } - auto repaired = EditedStatement(tokens, statement_start, error_index, candidate, false); - idx_t furthest; - if (Recognize(repaired, grammar, options, furthest)) { - result.push_back(candidate); + if (EditRepairs(tokens, statement_start, error_index, EditKind::INSERT, grammar, options, candidate)) { + repairs.push_back(candidate); } } - return result; + if (repairs.size() != 1) { + return optional_idx(); + } + result = {repairs[0], error_index}; + return result.index; +} + +//! Keywords and punctuation can be stray; literals and identifiers are content, a terminator is where input ends. +//! Opening brackets are excluded: nesting repeats them legitimately, and a missing closer is reported instead. +bool IsDroppable(const MatcherToken &token, const PEGKeywordHelper &keyword_helper) { + if (token.type == TokenType::OPERATOR) { + return token.text != "(" && token.text != "[" && token.text != "{"; + } + return IsWordToken(token) && keyword_helper.IsKeyword(token.text); +} + +bool RepeatsPredecessor(const TokenIterator &tokens, idx_t statement_start, idx_t index) { + return index > statement_start && + StringUtil::CIEquals(tokens.GetToken(index - 1).text, tokens.GetToken(index).text); +} + +//! A plain word followed by "(", as in "COUNT COUNT(*)": a doubled function name rather than a column and an alias. +bool IsRepeatedFunctionName(const TokenIterator &tokens, idx_t index) { + if (!IsWordToken(tokens.GetToken(index))) { + return false; + } + if (index + 1 >= tokens.Size()) { + return false; + } + return tokens.GetToken(index + 1).text == "("; +} + +//! Whether the token at `index` repeats its predecessor ("WHERE WHERE", "AS AS", ",,") and dropping it repairs. +bool IsRepeatedToken(const TokenIterator &tokens, idx_t statement_start, idx_t index, const CompiledGrammar &grammar, + const ParserOptions &options) { + if (!RepeatsPredecessor(tokens, statement_start, index)) { + return false; + } + if (!IsDroppable(tokens.GetToken(index), grammar.GetKeywordHelper()) && !IsRepeatedFunctionName(tokens, index)) { + return false; + } + return EditRepairs(tokens, statement_start, index, EditKind::DELETE, grammar, options); +} + +//! A repeated token whose removal makes the statement parse: the failing token, or the token right before it when +//! the repeat was still consumed. Repeats are a safer guess than any insertion. +optional_idx FindRepeatedToken(const TokenIterator &tokens, idx_t statement_start, idx_t error_index, + const CompiledGrammar &grammar, const ParserOptions &options) { + if (IsRepeatedToken(tokens, statement_start, error_index, grammar, options)) { + return error_index; + } + if (error_index == statement_start) { + return optional_idx(); + } + if (IsRepeatedToken(tokens, statement_start, error_index - 1, grammar, options)) { + return error_index - 1; + } + return optional_idx(); +} + +//! Whether the failing token is stray where only literal tokens fit, and its removal makes the statement parse. +//! Where an identifier or expression fits, the failure usually means something is missing, not that a token is extra. +bool IsStrayToken(const TokenIterator &tokens, idx_t statement_start, idx_t error_index, const ExpectedTokens &expected, + const CompiledGrammar &grammar, const ParserOptions &options) { + if (expected.AcceptsIdentifiers()) { + return false; + } + if (!IsDroppable(tokens.GetToken(error_index), grammar.GetKeywordHelper())) { + return false; + } + return EditRepairs(tokens, statement_start, error_index, EditKind::DELETE, grammar, options); } string DescribeExpected(const ExpectedTokens &expected, const PEGKeywordHelper &keyword_helper) { @@ -311,6 +434,63 @@ string DescribeExpected(const ExpectedTokens &expected, const PEGKeywordHelper & return "Expected one of: " + StringUtil::Join(items, ", "); } +//! A hint for the syntax error and the token it is about. +struct SyntaxHint { + string text; + idx_t index; +}; + +SyntaxHint UnexpectedHint(const TokenIterator &tokens, idx_t index) { + return {"Unexpected \"" + tokens.GetToken(index).text + "\"", index}; +} + +//! The most specific hint for the failure at `error_index`, tried from the most to the least confident kind. +SyntaxHint FindHint(const TokenIterator &tokens, idx_t statement_start, idx_t error_index, + const CompiledGrammar &grammar, const ParserOptions &options) { + auto expected = ComputeExpectedTokens(tokens, statement_start, error_index, grammar, options); + auto &error_token = tokens.GetToken(error_index); + const bool at_end = IsEndOfInput(error_token); + if (!at_end && IsWordToken(error_token)) { + auto correction = + KeywordCorrectionHint(tokens, statement_start, error_index, error_index, expected, grammar, options); + if (!correction.empty()) { + return {correction, error_index}; + } + } + + // a misspelled keyword or a missing comma often hides one token earlier, in a word taken as an alias + const bool previous_is_word = error_index > statement_start && IsWordToken(tokens.GetToken(error_index - 1)) && + !grammar.GetKeywordHelper().IsKeyword(tokens.GetToken(error_index - 1).text); + ExpectedTokens previous_expected; + if (previous_is_word) { + previous_expected = ComputeExpectedTokens(tokens, statement_start, error_index - 1, grammar, options); + auto correction = KeywordCorrectionHint(tokens, statement_start, error_index - 1, error_index, + previous_expected, grammar, options); + if (!correction.empty()) { + return {correction, error_index - 1}; + } + } + + if (!at_end) { + auto repeated = FindRepeatedToken(tokens, statement_start, error_index, grammar, options); + if (repeated.IsValid()) { + return UnexpectedHint(tokens, repeated.GetIndex()); + } + } + + MissingToken missing; + if (FindMissingToken(tokens, statement_start, error_index, expected, previous_expected, grammar, options, missing) + .IsValid()) { + return {"Missing \"" + missing.text + "\"", missing.index}; + } + + if (!at_end && IsStrayToken(tokens, statement_start, error_index, expected, grammar, options)) { + return UnexpectedHint(tokens, error_index); + } + + return {DescribeExpected(expected, grammar.GetKeywordHelper()), error_index}; +} + } // namespace ParserException PEGSyntaxError::Create(const TokenIterator &tokens, idx_t statement_start, idx_t failure_index, @@ -324,36 +504,15 @@ ParserException PEGSyntaxError::Create(const TokenIterator &tokens, idx_t statem bool at_end = IsEndOfInput(error_token); const bool compute_hints = tokens.Size() - statement_start <= MAX_HINT_TOKENS; - ExpectedTokens expected; + SyntaxHint hint {string(), error_index}; if (compute_hints) { - expected = ComputeExpectedTokens(tokens, statement_start, error_index, grammar, options); + hint = FindHint(tokens, statement_start, error_index, grammar, options); } idx_t report_index = error_index; - string hint; - if (compute_hints && !at_end && IsWordToken(error_token)) { - hint = KeywordCorrectionHint(tokens, statement_start, error_index, error_index, expected, grammar, options); - } - if (compute_hints && hint.empty() && error_index > statement_start) { - // a misspelled keyword is often swallowed as an alias, so the failure surfaces one token late - auto &previous = tokens.GetToken(error_index - 1); - if (IsWordToken(previous) && !grammar.GetKeywordHelper().IsKeyword(previous.text)) { - auto previous_expected = ComputeExpectedTokens(tokens, statement_start, error_index - 1, grammar, options); - hint = KeywordCorrectionHint(tokens, statement_start, error_index - 1, error_index, previous_expected, - grammar, options); - if (!hint.empty()) { - report_index = error_index - 1; - at_end = false; - } - } - } - if (compute_hints && hint.empty()) { - auto missing = FindMissingTokens(tokens, statement_start, error_index, expected, grammar, options); - if (missing.size() == 1) { - hint = "Missing \"" + missing[0] + "\""; - } - } - if (hint.empty()) { - hint = DescribeExpected(expected, grammar.GetKeywordHelper()); + if (hint.index != error_index) { + // the hint is about an earlier token, so the error is reported there and not at the end of the input + report_index = hint.index; + at_end = false; } string message; @@ -366,8 +525,8 @@ ParserException PEGSyntaxError::Create(const TokenIterator &tokens, idx_t statem } else { message = "syntax error at or near \"" + tokens.GetToken(report_index).text + "\""; } - if (!hint.empty()) { - message += "\n" + hint; + if (!hint.text.empty()) { + message += "\n" + hint.text; } auto &location_token = tokens.GetToken(report_index); return ParserException::SyntaxError(string(), message, QueryLocation(location_token.offset, location_token.length)); diff --git a/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp b/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp index bdf8fcc50..d6ee3d51b 100644 --- a/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp +++ b/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp @@ -3,7 +3,7 @@ namespace duckdb { -static bool IsEmptyQuotedIdentifier(const string &sql, idx_t start, idx_t end, TokenType type) { +bool ParserTokenizerBehavior::IsEmptyQuotedIdentifier(const string &sql, idx_t start, idx_t end, TokenType type) { if (type != TokenType::IDENTIFIER || end != start + 2) { return false; } diff --git a/src/duckdb/src/parser/peg/transformer/peg_transformer.cpp b/src/duckdb/src/parser/peg/transformer/peg_transformer.cpp index fc6c2ba90..865b95031 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer.cpp @@ -27,6 +27,40 @@ arena_ptr TransformStep::TakeResult() { return std::move(result); } +TransformInput TransformInput::Unwrap() const { + if (GetRule()) { + return *this; + } + // choices, present optionals and unnamed single-child groups carry no rule: unwrap to the rule-boundary node + reference target(parse_result); + while (!target.get().GetRule()) { + auto &node = target.get(); + if (node.type == ParseResultType::CHOICE) { + target = node.Cast().GetResult(); + } else if (node.type == ParseResultType::OPTIONAL && node.Cast().HasResult()) { + target = node.Cast().GetResult(); + } else if (node.type == ParseResultType::LIST && node.Name().empty() && + node.Cast().GetChildren().size() == 1) { + target = node.Cast().GetChild(0); + } else { + break; + } + } + auto &node = target.get(); + if (!node.GetRule()) { + string description = ParseResultToString(node.type); + if (node.type == ParseResultType::OPTIONAL) { + description = "empty " + description; + } + if (!node.Name().empty()) { + description += " '" + node.Name() + "'"; + } + throw NotImplementedException("Cannot transform %s parse node: no grammar rule is associated with it", + description); + } + return TransformInput(node); +} + GeneratedTransformProcess::GeneratedTransformProcess(PEGTransformer &transformer_p, TransformInput input, const TransformFrameOps &info_p) : parse_result(input.parse_result), info(info_p), child_results(transformer_p.process_allocator), @@ -144,7 +178,8 @@ TransformStack::~TransformStack() { } void TransformStack::PushFrame(TransformInput input) { - frames.emplace_back(input); + // inline fast path: in-tree frames always carry a rule + frames.emplace_back(input.GetRule() ? input : input.Unwrap()); auto &frame = frames.back(); frame.process_arena_position = transformer.process_allocator.GetPosition(); auto weight = transformer.ExpressionDepthWeight(frame.rule, frame.parse_result); @@ -165,9 +200,8 @@ void TransformStack::PopFrame() { } void TransformStack::InitializeFrame(TransformStackFrame &frame) { - if (!frame.rule) { - throw InternalException("No registered data exists for rule '%s'", frame.parse_result.Name()); - } + // PushFrame unwraps every input to a rule-bearing node or throws + D_ASSERT(frame.rule); frame.process = frame.rule->StartTransform(transformer, frame.parse_result); } @@ -187,9 +221,6 @@ arena_ptr TransformStack::ExecuteFrame(TransformStackFrame arena_ptr TransformStack::Execute(TransformInput input) { D_ASSERT(frames.empty()); - if (!input.GetRule()) { - throw InternalException("No registered data exists for rule '%s'", input.parse_result.Name()); - } PushFrame(input); while (!frames.empty()) { auto result = ExecuteFrame(frames.back()); @@ -227,13 +258,8 @@ string TransformStack::FormatStack() const { #endif arena_ptr PEGTransformer::TransformInternal(ParseResult &parse_result) { - auto rule = parse_result.GetRule(); - if (!rule) { - throw InternalException("No registered data exists for rule '%s'", parse_result.Name()); - } - TransformInput input {*rule, parse_result}; TransformStack stack(*this); - return stack.Execute(input); + return stack.Execute(TransformInput(parse_result)); } //! The number of repeated elements directly in a rule's match: the links of an operator chain diff --git a/src/duckdb/src/parser/peg/transformer/transform_create_sequence.cpp b/src/duckdb/src/parser/peg/transformer/transform_create_sequence.cpp index d8169e9d9..796d436e7 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_create_sequence.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_create_sequence.cpp @@ -110,13 +110,17 @@ unique_ptr PEGTransformerFactory::TransformCreateSequenceStmt( if (info->max_value <= info->min_value) { throw ParserException("MINVALUE (%lld) must be less than MAXVALUE (%lld)", info->min_value, info->max_value); } - if (info->start_value < info->min_value) { - throw ParserException("START value (%lld) cannot be less than MINVALUE (%lld)", info->start_value, - info->min_value); - } - if (info->start_value > info->max_value) { - throw ParserException("START value (%lld) cannot be greater than MAXVALUE (%lld)", info->start_value, - info->max_value); + // a non cycling sequence can start outside its range, the exhausted state EXPORT DATABASE writes once the counter + // has moved past the last value. a cycling sequence wraps and never exhausts, so its range still bounds its START + if (info->cycle) { + if (info->start_value < info->min_value) { + throw ParserException("START value (%lld) cannot be less than MINVALUE (%lld)", info->start_value, + info->min_value); + } + if (info->start_value > info->max_value) { + throw ParserException("START value (%lld) cannot be greater than MAXVALUE (%lld)", info->start_value, + info->max_value); + } } result->info = std::move(info); return result; diff --git a/src/duckdb/src/parser/peg/transformer/transform_expression.cpp b/src/duckdb/src/parser/peg/transformer/transform_expression.cpp index 4b22ded85..444640ba5 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_expression.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_expression.cpp @@ -33,6 +33,32 @@ static bool ExpressionIsUnqualifiedStar(const ParsedExpression &expr) { enum class ParserRewriteCallForm : uint8_t { PLAIN, METHOD_CHAIN }; //! Names that the parser rewrites into a syntax node instead of a catalog function call. +enum class ParserFunctionRewrite { NONE, UNPACK, TRY, CONSTRUCT_ARRAY, IFNULL, COALESCE, DATE }; + +//! Which rewrite the lowercase name takes, NONE for an ordinary function +static ParserFunctionRewrite GetParserFunctionRewrite(const string &lowercase_name) { + if (lowercase_name == "unpack") { + return ParserFunctionRewrite::UNPACK; + } + if (lowercase_name == "try") { + return ParserFunctionRewrite::TRY; + } + if (lowercase_name == "construct_array") { + return ParserFunctionRewrite::CONSTRUCT_ARRAY; + } + if (lowercase_name == "ifnull") { + return ParserFunctionRewrite::IFNULL; + } + if (lowercase_name == "coalesce") { + return ParserFunctionRewrite::COALESCE; + } + if (lowercase_name == "date") { + return ParserFunctionRewrite::DATE; + } + return ParserFunctionRewrite::NONE; +} + +//! Rewrites a call of such a name into its syntax node. //! Every path that can name a function must go through this, or the paths disagree. //! Returns nullptr when the name is an ordinary function. static unique_ptr TransformParserFunctionRewrite(const string &lowercase_name, @@ -46,7 +72,8 @@ static unique_ptr TransformParserFunctionRewrite(const string } }; - if (lowercase_name == "unpack") { + switch (GetParserFunctionRewrite(lowercase_name)) { + case ParserFunctionRewrite::UNPACK: { if (function_children.size() != 1) { throw ParserException("Wrong number of arguments to the UNPACK operator"); } @@ -57,7 +84,7 @@ static unique_ptr TransformParserFunctionRewrite(const string } return std::move(expr); } - if (lowercase_name == "try") { + case ParserFunctionRewrite::TRY: { if (function_children.size() != 1) { throw ParserException("Wrong number of arguments provided to TRY expression"); } @@ -68,7 +95,7 @@ static unique_ptr TransformParserFunctionRewrite(const string } return std::move(try_expression); } - if (lowercase_name == "construct_array") { + case ParserFunctionRewrite::CONSTRUCT_ARRAY: { reject_named_arguments("array constructors"); auto construct_array = make_uniq(ExpressionType::ARRAY_CONSTRUCTOR); for (auto &arg : function_children) { @@ -76,7 +103,7 @@ static unique_ptr TransformParserFunctionRewrite(const string } return std::move(construct_array); } - if (lowercase_name == "ifnull") { + case ParserFunctionRewrite::IFNULL: { if (function_children.size() != 2) { throw ParserException("Wrong number of arguments to IFNULL."); } @@ -92,7 +119,10 @@ static unique_ptr TransformParserFunctionRewrite(const string // it. Reaching the plain path under this name therefore means the caller wrote it as a function // call - quoted, or schema-qualified - which resolves in the catalog and lets a user macro named // coalesce win. The method chain has no grammar form, so the rewrite is its only route. - if (lowercase_name == "coalesce" && call_form == ParserRewriteCallForm::METHOD_CHAIN) { + case ParserFunctionRewrite::COALESCE: { + if (call_form != ParserRewriteCallForm::METHOD_CHAIN) { + return nullptr; + } reject_named_arguments("COALESCE expressions"); auto coalesce_op = make_uniq(ExpressionType::OPERATOR_COALESCE); for (auto &arg : function_children) { @@ -100,16 +130,44 @@ static unique_ptr TransformParserFunctionRewrite(const string } return std::move(coalesce_op); } - if (lowercase_name == "date") { + case ParserFunctionRewrite::DATE: { if (function_children.size() != 1) { throw ParserException("Wrong number of arguments provided to DATE function"); } return std::move( make_uniq(LogicalType::DATE, std::move(function_children[0].GetExpressionMutable()))); } + case ParserFunctionRewrite::NONE: + break; + } return nullptr; } +//! Makes a call on a value, as x.f(y), the call f(x, y) with the rewrites of a method call +static unique_ptr TransformMethodCall(unique_ptr value, + unique_ptr function) { + function->GetArgumentsMutable().insert(function->GetArgumentsMutable().begin(), std::move(value)); + auto lowercase_name = StringUtil::Lower(function->FunctionName().GetIdentifierName()); + auto rewritten = TransformParserFunctionRewrite(lowercase_name, function->GetArgumentsMutable(), + ParserRewriteCallForm::METHOD_CHAIN); + if (!rewritten) { + return std::move(function); + } + // A method call accepts modifiers for every name, but a rewrite yields a syntax node with nowhere to put them. + // Reject rather than drop them silently. + auto upper_name = StringUtil::Upper(lowercase_name); + if (function->Distinct()) { + throw ParserException("DISTINCT is not supported in %s expressions", upper_name); + } + if (function->OrderBy() && !function->OrderBy()->orders.empty()) { + throw ParserException("ORDER BY is not supported in %s expressions", upper_name); + } + if (function->Filter()) { + throw ParserException("FILTER is not supported in %s expressions", upper_name); + } + return rewritten; +} + unique_ptr PEGTransformerFactory::TransformBaseExpression(PEGTransformer &transformer, unique_ptr single_expression, @@ -138,26 +196,7 @@ PEGTransformerFactory::TransformBaseExpression(PEGTransformer &transformer, prev_indirection_was_cast = false; } else if (indirection_expr->GetExpressionClass() == ExpressionClass::FUNCTION) { auto function_expr = unique_ptr_cast(std::move(indirection_expr)); - function_expr->GetArgumentsMutable().insert(function_expr->GetArgumentsMutable().begin(), std::move(expr)); - // A method-chained call names a function too, so it takes the same rewrites. - auto lowercase_name = StringUtil::Lower(function_expr->FunctionName().GetIdentifierName()); - const bool distinct = function_expr->Distinct(); - const bool has_order_by = function_expr->OrderBy() && !function_expr->OrderBy()->orders.empty(); - if (auto rewritten = TransformParserFunctionRewrite(lowercase_name, function_expr->GetArgumentsMutable(), - ParserRewriteCallForm::METHOD_CHAIN)) { - // The method grammar accepts DISTINCT and ORDER BY for every call, but a rewrite yields a - // syntax node with nowhere to put them. Reject rather than drop them silently. - auto upper_name = StringUtil::Upper(lowercase_name); - if (distinct) { - throw ParserException("DISTINCT is not supported in %s expressions", upper_name); - } - if (has_order_by) { - throw ParserException("ORDER BY is not supported in %s expressions", upper_name); - } - expr = std::move(rewritten); - } else { - expr = std::move(function_expr); - } + expr = TransformMethodCall(std::move(expr), std::move(function_expr)); prev_indirection_was_cast = false; } else if (indirection_expr->GetExpressionClass() == ExpressionClass::CONSTANT) { vector> struct_children; @@ -294,9 +333,17 @@ unique_ptr PEGTransformerFactory::TransformFunctionExpression( lowercase_name = "count_star"; } - if (auto rewritten = - TransformParserFunctionRewrite(lowercase_name, function_children, ParserRewriteCallForm::PLAIN)) { - return rewritten; + // x.ifnull(y) parses as a call in schema x. The rewrites are not catalog functions, so for them a qualification + // other than main is the column the function is called on, as in (x).ifnull(y) + const auto &path = qualified_function.Path(); + const bool call_on_column = path.size() > 1 && + GetParserFunctionRewrite(lowercase_name) != ParserFunctionRewrite::NONE && + !StringUtil::CIEquals(qualified_function.Schema().GetIdentifierName(), DEFAULT_SCHEMA); + if (!call_on_column) { + if (auto rewritten = + TransformParserFunctionRewrite(lowercase_name, function_children, ParserRewriteCallForm::PLAIN)) { + return rewritten; + } } if (function_expression_arguments.has_ignore_nulls) { throw ParserException("RESPECT/IGNORE NULLS is not supported for non-window functions"); @@ -324,7 +371,10 @@ unique_ptr PEGTransformerFactory::TransformFunctionExpression( auto result = make_uniq(qualified_function.WithName(Identifier(lowercase_name)), std::move(function_children), std::move(filter_expr), std::move(order_modifier), distinct, false, export_clause); - + if (call_on_column) { + vector column_name(path.begin(), path.end() - 1); + return TransformMethodCall(make_uniq(std::move(column_name)), std::move(result)); + } return std::move(result); } @@ -1359,7 +1409,7 @@ PEGTransformerFactory::TransformInfixOtherOperatorExpression(PEGTransformer &tra auto expression_type = OperatorToExpressionType(op_string); auto subquery_expr = make_uniq(); - if (right_expr->GetExpressionClass() == ExpressionClass::SUBQUERY) { + if (other_operator_expr.is_subquery) { if (expression_type == ExpressionType::INVALID) { throw ParserException("ANY and ALL operators require one of =,<>,>,<,>=,<= comparisons!"); } @@ -1433,9 +1483,22 @@ PEGTransformerFactory::TransformCustomPrefixExpression(PEGTransformer &transform return TransformOperatorFunction(operator_literal, std::move(children)); } -OtherOperatorTail PEGTransformerFactory::TransformOtherOperatorTail(PEGTransformer &transformer, - ParsedOperator other_operator, - unique_ptr bitwise_expression) { +OtherOperatorTail PEGTransformerFactory::TransformAnyAllSubqueryTail(PEGTransformer &transformer, + ParsedOperator any_all_parsed_operator, + unique_ptr subquery_reference) { + auto subquery = make_uniq(); + subquery->GetSubqueryTypeMutable() = SubqueryType::SCALAR; + subquery->SubqueryMutable() = std::move(subquery_reference->Cast().subquery); + OtherOperatorTail result; + result.op = std::move(any_all_parsed_operator); + result.expression = std::move(subquery); + result.is_subquery = true; + return result; +} + +OtherOperatorTail +PEGTransformerFactory::TransformOtherOperatorExpressionTail(PEGTransformer &transformer, ParsedOperator other_operator, + unique_ptr bitwise_expression) { OtherOperatorTail result; result.op = std::move(other_operator); result.expression = std::move(bitwise_expression); @@ -2718,30 +2781,66 @@ bool PEGTransformerFactory::TransformTryCastKeyword(PEGTransformer &transformer) return true; } -unique_ptr PEGTransformerFactory::TransformCaseExpression( - PEGTransformer &transformer, optional> expression, vector case_when_then, +static void SetCaseElse(CaseExpression &result, optional> case_else) { + if (case_else) { + result.ElseMutable() = std::move(*case_else); + } else { + result.ElseMutable() = ConstantExpression::Null(); + } +} + +unique_ptr PEGTransformerFactory::TransformSimpleCaseExpression( + PEGTransformer &transformer, unique_ptr expression, vector simple_case_when_then, optional> case_else) { auto result = make_uniq(); - - for (auto &case_expr : case_when_then) { + for (auto &case_expr : simple_case_when_then) { + vector> comparisons; + for (auto &when : case_expr.when) { + comparisons.push_back(ApplyComparisonTail(expression->Copy(), std::move(when))); + } CaseCheck new_case; - if (expression) { - new_case.when_expr = make_uniq(ExpressionType::COMPARE_EQUAL, (*expression)->Copy(), - std::move(case_expr.when_expr)); + if (comparisons.size() == 1) { + new_case.when_expr = std::move(comparisons[0]); } else { - new_case.when_expr = std::move(case_expr.when_expr); + new_case.when_expr = + make_uniq(ExpressionType::CONJUNCTION_OR, std::move(comparisons)); } new_case.then_expr = std::move(case_expr.then_expr); result->CaseChecksMutable().push_back(std::move(new_case)); } - if (case_else) { - result->ElseMutable() = std::move(*case_else); - } else { - result->ElseMutable() = ConstantExpression::Null(); + SetCaseElse(*result, std::move(case_else)); + return std::move(result); +} + +unique_ptr +PEGTransformerFactory::TransformSearchedCaseExpression(PEGTransformer &transformer, vector case_when_then, + optional> case_else) { + auto result = make_uniq(); + for (auto &case_expr : case_when_then) { + result->CaseChecksMutable().push_back(std::move(case_expr)); } + SetCaseElse(*result, std::move(case_else)); return std::move(result); } +SimpleCaseCheck +PEGTransformerFactory::TransformSimpleCaseWhenThen(PEGTransformer &transformer, + vector simple_case_when_operand, + unique_ptr expression) { + SimpleCaseCheck result; + result.when = std::move(simple_case_when_operand); + result.then_expr = std::move(expression); + return result; +} + +ComparisonExpressionTail PEGTransformerFactory::TransformSimpleCaseWhenEquals(PEGTransformer &transformer, + unique_ptr expression) { + ComparisonExpressionTail result; + result.comparison_type = ExpressionType::COMPARE_EQUAL; + result.expression = std::move(expression); + return result; +} + unique_ptr PEGTransformerFactory::TransformCaseElse(PEGTransformer &transformer, unique_ptr expression) { return expression; diff --git a/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp b/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp index 08a011847..002528b69 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp @@ -1,7 +1,11 @@ #include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/star_expression.hpp" #include "duckdb/parser/peg/ast/generic_copy_option.hpp" #include "duckdb/parser/peg/transformer/peg_transformer.hpp" +#include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/parser/statement/external_resource_statement.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" namespace duckdb { @@ -45,16 +49,35 @@ unique_ptr PEGTransformerFactory::TransformDestroyExternalResource return std::move(result); } -unique_ptr -PEGTransformerFactory::TransformShowExternalResourcesStmt(PEGTransformer &transformer, - const optional &show_all_modifier) { - auto result = make_uniq(ExternalResourceOperation::SHOW); - result->all = show_all_modifier.has_value(); - return std::move(result); +//! A named argument of a table function call: the name goes on the argument and, for the binder, on the expression. +static void AddNamedArgument(vector &children, const string &name, + unique_ptr value) { + value->SetAlias(Identifier(name)); + children.emplace_back(Identifier(name), std::move(value)); } -bool PEGTransformerFactory::TransformShowAllModifier(PEGTransformer &transformer) { - return true; +// SHOW [ALL] EXTERNAL RESOURCES [WITH TYPE t] is the query +// `SELECT * FROM duckdb_external_resources(discover := , type := t)`, so it can be used wherever a query can, +// such as a subquery. +unique_ptr +PEGTransformerFactory::TransformShowExternalResources(PEGTransformer &transformer, const ShowType &show_rule, + const bool &has_result, + optional show_external_resources_type) { + vector children; + if (has_result) { + AddNamedArgument(children, "discover", ConstantExpression::Boolean(true)); + } + if (show_external_resources_type) { + auto type = ConstantExpression::String(show_external_resources_type->GetIdentifierName()); + AddNamedArgument(children, "type", std::move(type)); + } + auto table_function = make_uniq(); + table_function->function = make_uniq("duckdb_external_resources", std::move(children)); + + auto select_node = make_uniq(); + select_node->select_list.push_back(make_uniq()); + select_node->from_table = std::move(table_function); + return std::move(select_node); } } // namespace duckdb diff --git a/src/duckdb/src/parser/peg/transformer/transform_frame_plan.cpp b/src/duckdb/src/parser/peg/transformer/transform_frame_plan.cpp new file mode 100644 index 000000000..22235194b --- /dev/null +++ b/src/duckdb/src/parser/peg/transformer/transform_frame_plan.cpp @@ -0,0 +1,170 @@ +#include "duckdb/parser/peg/transformer/peg_transformer.hpp" + +namespace duckdb { + +static ParseResult &UnwrapParens(ParseResult &parse_result, idx_t parens) { + reference result(parse_result); + for (idx_t i = 0; i < parens; i++) { + result = PEGTransformerFactory::ExtractResultFromParens(result.get()); + } + return result.get(); +} + +static ParseResult &FollowPath(ParseResult &start, const TransformChildPath &path) { + auto &unwrapped = UnwrapParens(start, path.parens); + if (path.nested_child == TRANSFORM_PATH_END) { + return unwrapped; + } + return UnwrapParens(unwrapped.Cast().GetChild(path.nested_child), path.nested_parens); +} + +static ParseResult &PlannedChild(ListParseResult &list_pr, const TransformChildPlan &child) { + return FollowPath(list_pr.GetChild(child.parse_child), child.path); +} + +//! The parse result of an optional child, if present +static optional_ptr PlannedOptionalChild(ListParseResult &list_pr, const TransformChildPlan &child) { + auto &opt = PlannedChild(list_pr, child).Cast(); + if (!opt.HasResult()) { + return nullptr; + } + return FollowPath(opt.GetResult(), child.content_path); +} + +static bool IsDynamicChild(const TransformChildPlan &child) { + return child.kind != TransformChildKind::REQUIRED && child.kind != TransformChildKind::OPTIONAL; +} + +//! The items of a dynamic (list or repeat) child, in grammar order +static vector> PlannedDynamicItems(ListParseResult &list_pr, const TransformChildPlan &child) { + vector> items; + switch (child.kind) { + case TransformChildKind::LIST: + return PEGTransformerFactory::ExtractParseResultsFromList(PlannedChild(list_pr, child)); + case TransformChildKind::OPTIONAL_LIST: { + auto content = PlannedOptionalChild(list_pr, child); + if (content) { + return PEGTransformerFactory::ExtractParseResultsFromList(*content); + } + return items; + } + case TransformChildKind::REPEAT: { + auto repeat_children = PlannedChild(list_pr, child).Cast().GetChildren(); + items.reserve(repeat_children.size()); + for (idx_t i = 0; i < repeat_children.size(); i++) { + items.push_back(repeat_children[i]); + } + return items; + } + case TransformChildKind::OPTIONAL_REPEAT: { + auto content = PlannedOptionalChild(list_pr, child); + if (!content) { + return items; + } + auto repeat_children = content->Cast().GetChildren(); + items.reserve(repeat_children.size()); + for (idx_t i = 0; i < repeat_children.size(); i++) { + items.push_back(repeat_children[i]); + } + return items; + } + default: + throw InternalException("Unexpected dynamic transformer child kind"); + } +} + +void PEGTransformerFactory::InitializePlannedTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &plan = *process.info.plan; + if (plan.child_count == 0) { + process.ReserveChildSlots(plan.fixed_slots); + return; + } + auto &list_pr = process.parse_result.Cast(); + // the dynamic child decides how many slots the frame needs: the plan counts it as one slot, and its items take + // one each. Kept in idx_t, added before the one is taken off: with no items, size() - 1 wraps in size_t, which + // is 32 bits wide on some platforms. + vector> dynamic_items; + idx_t dynamic_item_count = 0; + idx_t slot_count = plan.fixed_slots; + if (plan.has_dynamic) { + for (idx_t i = 0; i < plan.child_count; i++) { + if (IsDynamicChild(plan.children[i])) { + dynamic_items = PlannedDynamicItems(list_pr, plan.children[i]); + break; + } + } + dynamic_item_count = dynamic_items.size(); + slot_count = slot_count + dynamic_item_count - 1; + } + process.ReserveChildSlots(slot_count); + // children are pushed last-first, so the first child in grammar order is transformed first + for (idx_t i = 0; i < plan.child_count; i++) { + auto &child = plan.children[i]; + idx_t slot = child.slot; + if (child.after_dynamic) { + slot = slot + dynamic_item_count - 1; + } + switch (child.kind) { + case TransformChildKind::REQUIRED: + process.PushChild({transformer.GetRule(child.rule), PlannedChild(list_pr, child)}, slot); + break; + case TransformChildKind::OPTIONAL: { + auto content = PlannedOptionalChild(list_pr, child); + if (content) { + process.PushChild({transformer.GetRule(child.rule), *content}, slot); + } + break; + } + default: + for (idx_t item_idx = dynamic_item_count; item_idx > 0; item_idx--) { + process.PushChild({transformer.GetRule(child.rule), dynamic_items[item_idx - 1].get()}, + slot + item_idx - 1); + } + break; + } + } +} + +void PEGTransformerFactory::InitializePlannedChoiceTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &dispatch = process.info.plan->choice; + auto &list_pr = process.parse_result.Cast(); + auto &choice_pr = list_pr.Child(0); + auto &choice_result = choice_pr.GetResult(); + process.ReserveChildSlots(1); + auto child_rule = choice_result.GetRule(); + auto has_transform_process = child_rule && child_rule->transform_process; + auto type_bit = ParseResultTypeBit(choice_result.type); + // the finalize step reads these alternatives straight from the parse result + if ((dispatch.early_type_mask & type_bit) || (dispatch.early_empty_name && choice_result.Name().empty())) { + return; + } + if (!has_transform_process) { + if (dispatch.fallback_type_mask & type_bit) { + return; + } + for (idx_t i = 0; i < dispatch.fallback_name_count; i++) { + if (choice_result.Name() == dispatch.fallback_names[i]) { + return; + } + } + if (!dispatch.throw_without_process) { + return; + } + throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); + } + process.PushChild({*child_rule, choice_result}, 0); +} + +arena_ptr +PEGTransformerFactory::FinalizePassthroughTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { + idx_t slot = process.info.plan->result_slot; + if (slot >= process.child_results.size() || !process.child_results[slot]) { + throw InternalException("Missing transformer result for slot %llu in rule '%s'", slot, process.info.name); + } + // the rule returns its child's result as its own, so the child's result object is reused + return std::move(process.child_results[slot]); +} + +} // namespace duckdb 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 6fd3871c9..6ebd8b728 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -6,4450 +6,9248 @@ namespace duckdb { -static const TransformFrameOps STATEMENT_OPS = {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, - &PEGTransformerFactory::FinalizeStatementTrampoline}; -static const TransformFrameOps PRAGMA_NAME_OPS = {"PragmaName", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps TYPE_NAME_OPS = {"TypeName", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps PLAIN_IDENTIFIER_OPS = {"PlainIdentifier", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps QUOTED_IDENTIFIER_OPS = {"QuotedIdentifier", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps RESERVED_KEYWORD_OPS = {"ReservedKeyword", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps UNRESERVED_KEYWORD_OPS = { - "UnreservedKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps COLUMN_NAME_KEYWORD_OPS = { - "ColumnNameKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps FUNC_NAME_KEYWORD_OPS = {"FuncNameKeyword", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps TYPE_NAME_KEYWORD_OPS = {"TypeNameKeyword", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps BARE_LABEL_KEYWORD_OPS = { - "BareLabelKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps SETTING_NAME_OPS = {"SettingName", - &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline}; -static const TransformFrameOps ALTER_STATEMENT_OPS = {"AlterStatement", - &PEGTransformerFactory::InitializeAlterStatementTrampoline, - &PEGTransformerFactory::FinalizeAlterStatementTrampoline}; -static const TransformFrameOps ALTER_OPTIONS_OPS = {"AlterOptions", - &PEGTransformerFactory::InitializeAlterOptionsTrampoline, - &PEGTransformerFactory::FinalizeAlterOptionsTrampoline}; -static const TransformFrameOps ALTER_TABLE_STMT_OPS = {"AlterTableStmt", - &PEGTransformerFactory::InitializeAlterTableStmtTrampoline, - &PEGTransformerFactory::FinalizeAlterTableStmtTrampoline}; -static const TransformFrameOps ALTER_SCHEMA_STMT_OPS = {"AlterSchemaStmt", - &PEGTransformerFactory::InitializeAlterSchemaStmtTrampoline, - &PEGTransformerFactory::FinalizeAlterSchemaStmtTrampoline}; -static const TransformFrameOps ALTER_SCHEMA_OPTIONS_OPS = { - "AlterSchemaOptions", &PEGTransformerFactory::InitializeAlterSchemaOptionsTrampoline, - &PEGTransformerFactory::FinalizeAlterSchemaOptionsTrampoline}; -static const TransformFrameOps ALTER_TABLE_OPTIONS_OPS = {"AlterTableOptions", - &PEGTransformerFactory::InitializeAlterTableOptionsTrampoline, - &PEGTransformerFactory::FinalizeAlterTableOptionsTrampoline}; -static const TransformFrameOps ADD_CONSTRAINT_OPS = {"AddConstraint", - &PEGTransformerFactory::InitializeAddConstraintTrampoline, - &PEGTransformerFactory::FinalizeAddConstraintTrampoline}; -static const TransformFrameOps DROP_CONSTRAINT_OPS = {"DropConstraint", - &PEGTransformerFactory::InitializeDropConstraintTrampoline, - &PEGTransformerFactory::FinalizeDropConstraintTrampoline}; -static const TransformFrameOps ADD_COLUMN_OPS = {"AddColumn", &PEGTransformerFactory::InitializeAddColumnTrampoline, - &PEGTransformerFactory::FinalizeAddColumnTrampoline}; -static const TransformFrameOps ADD_COLUMN_ENTRY_OPS = {"AddColumnEntry", - &PEGTransformerFactory::InitializeAddColumnEntryTrampoline, - &PEGTransformerFactory::FinalizeAddColumnEntryTrampoline}; -static const TransformFrameOps DROP_COLUMN_OPS = {"DropColumn", &PEGTransformerFactory::InitializeDropColumnTrampoline, - &PEGTransformerFactory::FinalizeDropColumnTrampoline}; -static const TransformFrameOps ALTER_COLUMN_OPS = {"AlterColumn", - &PEGTransformerFactory::InitializeAlterColumnTrampoline, - &PEGTransformerFactory::FinalizeAlterColumnTrampoline}; -static const TransformFrameOps RENAME_COLUMN_OPS = {"RenameColumn", - &PEGTransformerFactory::InitializeRenameColumnTrampoline, - &PEGTransformerFactory::FinalizeRenameColumnTrampoline}; -static const TransformFrameOps NESTED_COLUMN_NAME_OPS = {"NestedColumnName", - &PEGTransformerFactory::InitializeNestedColumnNameTrampoline, - &PEGTransformerFactory::FinalizeNestedColumnNameTrampoline}; -static const TransformFrameOps IDENTIFIER_DOT_OPS = {"IdentifierDot", - &PEGTransformerFactory::InitializeIdentifierDotTrampoline, - &PEGTransformerFactory::FinalizeIdentifierDotTrampoline}; -static const TransformFrameOps RENAME_ALTER_OPS = {"RenameAlter", - &PEGTransformerFactory::InitializeRenameAlterTrampoline, - &PEGTransformerFactory::FinalizeRenameAlterTrampoline}; -static const TransformFrameOps SET_PARTITIONED_BY_OPS = {"SetPartitionedBy", - &PEGTransformerFactory::InitializeSetPartitionedByTrampoline, - &PEGTransformerFactory::FinalizeSetPartitionedByTrampoline}; -static const TransformFrameOps RESET_PARTITIONED_BY_OPS = { - "ResetPartitionedBy", &PEGTransformerFactory::InitializeResetPartitionedByTrampoline, - &PEGTransformerFactory::FinalizeResetPartitionedByTrampoline}; -static const TransformFrameOps SET_SORTED_BY_OPS = {"SetSortedBy", - &PEGTransformerFactory::InitializeSetSortedByTrampoline, - &PEGTransformerFactory::FinalizeSetSortedByTrampoline}; -static const TransformFrameOps RESET_SORTED_BY_OPS = {"ResetSortedBy", - &PEGTransformerFactory::InitializeResetSortedByTrampoline, - &PEGTransformerFactory::FinalizeResetSortedByTrampoline}; -static const TransformFrameOps SET_OPTIONS_OPS = {"SetOptions", &PEGTransformerFactory::InitializeSetOptionsTrampoline, - &PEGTransformerFactory::FinalizeSetOptionsTrampoline}; -static const TransformFrameOps RESET_OPTIONS_OPS = {"ResetOptions", - &PEGTransformerFactory::InitializeResetOptionsTrampoline, - &PEGTransformerFactory::FinalizeResetOptionsTrampoline}; -static const TransformFrameOps ALTER_COLUMN_ENTRY_OPS = {"AlterColumnEntry", - &PEGTransformerFactory::InitializeAlterColumnEntryTrampoline, - &PEGTransformerFactory::FinalizeAlterColumnEntryTrampoline}; -static const TransformFrameOps ADD_OR_DROP_DEFAULT_OPS = {"AddOrDropDefault", - &PEGTransformerFactory::InitializeAddOrDropDefaultTrampoline, - &PEGTransformerFactory::FinalizeAddOrDropDefaultTrampoline}; -static const TransformFrameOps ADD_DEFAULT_OPS = {"AddDefault", &PEGTransformerFactory::InitializeAddDefaultTrampoline, - &PEGTransformerFactory::FinalizeAddDefaultTrampoline}; -static const TransformFrameOps DROP_DEFAULT_OPS = {"DropDefault", - &PEGTransformerFactory::InitializeDropDefaultTrampoline, - &PEGTransformerFactory::FinalizeDropDefaultTrampoline}; -static const TransformFrameOps CHANGE_NULLABILITY_OPS = {"ChangeNullability", - &PEGTransformerFactory::InitializeChangeNullabilityTrampoline, - &PEGTransformerFactory::FinalizeChangeNullabilityTrampoline}; -static const TransformFrameOps DROP_OR_SET_OPS = {"DropOrSet", &PEGTransformerFactory::InitializeDropOrSetTrampoline, - &PEGTransformerFactory::FinalizeDropOrSetTrampoline}; -static const TransformFrameOps DROP_NULLABILITY_OPS = {"DropNullability", - &PEGTransformerFactory::InitializeDropNullabilityTrampoline, - &PEGTransformerFactory::FinalizeDropNullabilityTrampoline}; -static const TransformFrameOps SET_NULLABILITY_OPS = {"SetNullability", - &PEGTransformerFactory::InitializeSetNullabilityTrampoline, - &PEGTransformerFactory::FinalizeSetNullabilityTrampoline}; -static const TransformFrameOps ALTER_TYPE_OPS = {"AlterType", &PEGTransformerFactory::InitializeAlterTypeTrampoline, - &PEGTransformerFactory::FinalizeAlterTypeTrampoline}; -static const TransformFrameOps USING_EXPRESSION_OPS = {"UsingExpression", - &PEGTransformerFactory::InitializeUsingExpressionTrampoline, - &PEGTransformerFactory::FinalizeUsingExpressionTrampoline}; -static const TransformFrameOps ALTER_VIEW_STMT_OPS = {"AlterViewStmt", - &PEGTransformerFactory::InitializeAlterViewStmtTrampoline, - &PEGTransformerFactory::FinalizeAlterViewStmtTrampoline}; -static const TransformFrameOps ALTER_SEQUENCE_STMT_OPS = {"AlterSequenceStmt", - &PEGTransformerFactory::InitializeAlterSequenceStmtTrampoline, - &PEGTransformerFactory::FinalizeAlterSequenceStmtTrampoline}; -static const TransformFrameOps QUALIFIED_SEQUENCE_NAME_OPS = { - "QualifiedSequenceName", &PEGTransformerFactory::InitializeQualifiedSequenceNameTrampoline, - &PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline}; -static const TransformFrameOps ALTER_SEQUENCE_OPTIONS_OPS = { - "AlterSequenceOptions", &PEGTransformerFactory::InitializeAlterSequenceOptionsTrampoline, - &PEGTransformerFactory::FinalizeAlterSequenceOptionsTrampoline}; -static const TransformFrameOps RENAME_ALTER_SEQUENCE_OPTIONS_OPS = { - "RenameAlterSequenceOptions", &PEGTransformerFactory::InitializeRenameAlterSequenceOptionsTrampoline, - &PEGTransformerFactory::FinalizeRenameAlterSequenceOptionsTrampoline}; -static const TransformFrameOps SET_SEQUENCE_OPTION_OPS = {"SetSequenceOption", - &PEGTransformerFactory::InitializeSetSequenceOptionTrampoline, - &PEGTransformerFactory::FinalizeSetSequenceOptionTrampoline}; -static const TransformFrameOps ALTER_DATABASE_STMT_OPS = {"AlterDatabaseStmt", - &PEGTransformerFactory::InitializeAlterDatabaseStmtTrampoline, - &PEGTransformerFactory::FinalizeAlterDatabaseStmtTrampoline}; -static const TransformFrameOps ANALYZE_STATEMENT_OPS = {"AnalyzeStatement", - &PEGTransformerFactory::InitializeAnalyzeStatementTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeStatementTrampoline}; -static const TransformFrameOps ANALYZE_TARGET_OPS = {"AnalyzeTarget", - &PEGTransformerFactory::InitializeAnalyzeTargetTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeTargetTrampoline}; -static const TransformFrameOps ANALYZE_VERBOSE_OPS = {"AnalyzeVerbose", - &PEGTransformerFactory::InitializeAnalyzeVerboseTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeVerboseTrampoline}; -static const TransformFrameOps ATTACH_STATEMENT_OPS = {"AttachStatement", - &PEGTransformerFactory::InitializeAttachStatementTrampoline, - &PEGTransformerFactory::FinalizeAttachStatementTrampoline}; -static const TransformFrameOps DATABASE_PATH_OPS = {"DatabasePath", - &PEGTransformerFactory::InitializeDatabasePathTrampoline, - &PEGTransformerFactory::FinalizeDatabasePathTrampoline}; -static const TransformFrameOps ATTACH_ALIAS_OPS = {"AttachAlias", - &PEGTransformerFactory::InitializeAttachAliasTrampoline, - &PEGTransformerFactory::FinalizeAttachAliasTrampoline}; -static const TransformFrameOps ATTACH_OPTIONS_OPS = {"AttachOptions", - &PEGTransformerFactory::InitializeAttachOptionsTrampoline, - &PEGTransformerFactory::FinalizeAttachOptionsTrampoline}; -static const TransformFrameOps CALL_STATEMENT_OPS = {"CallStatement", - &PEGTransformerFactory::InitializeCallStatementTrampoline, - &PEGTransformerFactory::FinalizeCallStatementTrampoline}; -static const TransformFrameOps CHECKPOINT_STATEMENT_OPS = { - "CheckpointStatement", &PEGTransformerFactory::InitializeCheckpointStatementTrampoline, - &PEGTransformerFactory::FinalizeCheckpointStatementTrampoline}; -static const TransformFrameOps CHECKPOINT_FORCE_OPS = {"CheckpointForce", - &PEGTransformerFactory::InitializeCheckpointForceTrampoline, - &PEGTransformerFactory::FinalizeCheckpointForceTrampoline}; -static const TransformFrameOps COMMENT_STATEMENT_OPS = {"CommentStatement", - &PEGTransformerFactory::InitializeCommentStatementTrampoline, - &PEGTransformerFactory::FinalizeCommentStatementTrampoline}; -static const TransformFrameOps COMMENT_TARGET_OPS = {"CommentTarget", - &PEGTransformerFactory::InitializeCommentTargetTrampoline, - &PEGTransformerFactory::FinalizeCommentTargetTrampoline}; -static const TransformFrameOps COMMENT_STRING_LITERAL_IDENTIFIER_OPS = { - "CommentStringLiteralIdentifier", &PEGTransformerFactory::InitializeCommentStringLiteralIdentifierTrampoline, - &PEGTransformerFactory::FinalizeCommentStringLiteralIdentifierTrampoline}; -static const TransformFrameOps COMMENT_ON_TYPE_OPS = {"CommentOnType", - &PEGTransformerFactory::InitializeCommentOnTypeTrampoline, - &PEGTransformerFactory::FinalizeCommentOnTypeTrampoline}; -static const TransformFrameOps COMMENT_TABLE_OPS = {"CommentTable", - &PEGTransformerFactory::InitializeCommentTableTrampoline, - &PEGTransformerFactory::FinalizeCommentTableTrampoline}; -static const TransformFrameOps COMMENT_SEQUENCE_OPS = {"CommentSequence", - &PEGTransformerFactory::InitializeCommentSequenceTrampoline, - &PEGTransformerFactory::FinalizeCommentSequenceTrampoline}; -static const TransformFrameOps COMMENT_FUNCTION_OPS = {"CommentFunction", - &PEGTransformerFactory::InitializeCommentFunctionTrampoline, - &PEGTransformerFactory::FinalizeCommentFunctionTrampoline}; -static const TransformFrameOps COMMENT_MACRO_TABLE_OPS = {"CommentMacroTable", - &PEGTransformerFactory::InitializeCommentMacroTableTrampoline, - &PEGTransformerFactory::FinalizeCommentMacroTableTrampoline}; -static const TransformFrameOps COMMENT_MACRO_OPS = {"CommentMacro", - &PEGTransformerFactory::InitializeCommentMacroTrampoline, - &PEGTransformerFactory::FinalizeCommentMacroTrampoline}; -static const TransformFrameOps COMMENT_VIEW_OPS = {"CommentView", - &PEGTransformerFactory::InitializeCommentViewTrampoline, - &PEGTransformerFactory::FinalizeCommentViewTrampoline}; -static const TransformFrameOps COMMENT_DATABASE_OPS = {"CommentDatabase", - &PEGTransformerFactory::InitializeCommentDatabaseTrampoline, - &PEGTransformerFactory::FinalizeCommentDatabaseTrampoline}; -static const TransformFrameOps COMMENT_INDEX_OPS = {"CommentIndex", - &PEGTransformerFactory::InitializeCommentIndexTrampoline, - &PEGTransformerFactory::FinalizeCommentIndexTrampoline}; -static const TransformFrameOps COMMENT_SCHEMA_OPS = {"CommentSchema", - &PEGTransformerFactory::InitializeCommentSchemaTrampoline, - &PEGTransformerFactory::FinalizeCommentSchemaTrampoline}; -static const TransformFrameOps COMMENT_TYPE_OPS = {"CommentType", - &PEGTransformerFactory::InitializeCommentTypeTrampoline, - &PEGTransformerFactory::FinalizeCommentTypeTrampoline}; -static const TransformFrameOps COMMENT_COLUMN_OPS = {"CommentColumn", - &PEGTransformerFactory::InitializeCommentColumnTrampoline, - &PEGTransformerFactory::FinalizeCommentColumnTrampoline}; -static const TransformFrameOps COMMENT_VALUE_OPS = {"CommentValue", - &PEGTransformerFactory::InitializeCommentValueTrampoline, - &PEGTransformerFactory::FinalizeCommentValueTrampoline}; -static const TransformFrameOps STRING_LITERAL_VALUE_OPS = { - "StringLiteralValue", &PEGTransformerFactory::InitializeStringLiteralValueTrampoline, - &PEGTransformerFactory::FinalizeStringLiteralValueTrampoline}; -static const TransformFrameOps ANALYZE_KEYWORD_OPS = {"AnalyzeKeyword", - &PEGTransformerFactory::InitializeAnalyzeKeywordTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeKeywordTrampoline}; -static const TransformFrameOps INDEX_NAME_OPS = {"IndexName", &PEGTransformerFactory::InitializeIndexNameTrampoline, - &PEGTransformerFactory::FinalizeIndexNameTrampoline}; -static const TransformFrameOps CONSTRAINT_NAME_OPS = {"ConstraintName", - &PEGTransformerFactory::InitializeConstraintNameTrampoline, - &PEGTransformerFactory::FinalizeConstraintNameTrampoline}; -static const TransformFrameOps SEQUENCE_NAME_OPS = {"SequenceName", - &PEGTransformerFactory::InitializeSequenceNameTrampoline, - &PEGTransformerFactory::FinalizeSequenceNameTrampoline}; -static const TransformFrameOps COLLATION_NAME_OPS = {"CollationName", - &PEGTransformerFactory::InitializeCollationNameTrampoline, - &PEGTransformerFactory::FinalizeCollationNameTrampoline}; -static const TransformFrameOps NUMBER_LITERAL_OPS = {"NumberLiteral", - &PEGTransformerFactory::InitializeNumberLiteralTrampoline, - &PEGTransformerFactory::FinalizeNumberLiteralTrampoline}; -static const TransformFrameOps STRING_LITERAL_OPS = {"StringLiteral", - &PEGTransformerFactory::InitializeStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeStringLiteralTrampoline}; -static const TransformFrameOps TYPE_OPS = {"Type", &PEGTransformerFactory::InitializeTypeTrampoline, - &PEGTransformerFactory::FinalizeTypeTrampoline}; -static const TransformFrameOps TYPE_VARIATIONS_OPS = {"TypeVariations", - &PEGTransformerFactory::InitializeTypeVariationsTrampoline, - &PEGTransformerFactory::FinalizeTypeVariationsTrampoline}; -static const TransformFrameOps SIMPLE_TYPE_OPS = {"SimpleType", &PEGTransformerFactory::InitializeSimpleTypeTrampoline, - &PEGTransformerFactory::FinalizeSimpleTypeTrampoline}; -static const TransformFrameOps CHARACTER_SIMPLE_TYPE_OPS = { - "CharacterSimpleType", &PEGTransformerFactory::InitializeCharacterSimpleTypeTrampoline, - &PEGTransformerFactory::FinalizeCharacterSimpleTypeTrampoline}; -static const TransformFrameOps QUALIFIED_SIMPLE_TYPE_OPS = { - "QualifiedSimpleType", &PEGTransformerFactory::InitializeQualifiedSimpleTypeTrampoline, - &PEGTransformerFactory::FinalizeQualifiedSimpleTypeTrampoline}; -static const TransformFrameOps INTERVAL_TYPE_OPS = {"IntervalType", - &PEGTransformerFactory::InitializeIntervalTypeTrampoline, - &PEGTransformerFactory::FinalizeIntervalTypeTrampoline}; -static const TransformFrameOps INTERVAL_INTERVAL_OPS = {"IntervalInterval", - &PEGTransformerFactory::InitializeIntervalIntervalTrampoline, - &PEGTransformerFactory::FinalizeIntervalIntervalTrampoline}; -static const TransformFrameOps INTERVAL_WITH_SPECIFIER_OPS = { - "IntervalWithSpecifier", &PEGTransformerFactory::InitializeIntervalWithSpecifierTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithSpecifierTrampoline}; -static const TransformFrameOps INTERVAL_WITH_RANGE_SPECIFIER_OPS = { - "IntervalWithRangeSpecifier", &PEGTransformerFactory::InitializeIntervalWithRangeSpecifierTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithRangeSpecifierTrampoline}; -static const TransformFrameOps INTERVAL_WITH_SIMPLE_SPECIFIER_OPS = { - "IntervalWithSimpleSpecifier", &PEGTransformerFactory::InitializeIntervalWithSimpleSpecifierTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithSimpleSpecifierTrampoline}; -static const TransformFrameOps INTERVAL_WITHOUT_SPECIFIER_OPS = { - "IntervalWithoutSpecifier", &PEGTransformerFactory::InitializeIntervalWithoutSpecifierTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithoutSpecifierTrampoline}; -static const TransformFrameOps INTERVAL_TO_INTERVAL_AS_TYPE_OPS = { - "IntervalToIntervalAsType", &PEGTransformerFactory::InitializeIntervalToIntervalAsTypeTrampoline, - &PEGTransformerFactory::FinalizeIntervalToIntervalAsTypeTrampoline}; -static const TransformFrameOps YEAR_KEYWORD_OPS = {"YearKeyword", - &PEGTransformerFactory::InitializeYearKeywordTrampoline, - &PEGTransformerFactory::FinalizeYearKeywordTrampoline}; -static const TransformFrameOps MONTH_KEYWORD_OPS = {"MonthKeyword", - &PEGTransformerFactory::InitializeMonthKeywordTrampoline, - &PEGTransformerFactory::FinalizeMonthKeywordTrampoline}; -static const TransformFrameOps DAY_KEYWORD_OPS = {"DayKeyword", &PEGTransformerFactory::InitializeDayKeywordTrampoline, - &PEGTransformerFactory::FinalizeDayKeywordTrampoline}; -static const TransformFrameOps HOUR_KEYWORD_OPS = {"HourKeyword", - &PEGTransformerFactory::InitializeHourKeywordTrampoline, - &PEGTransformerFactory::FinalizeHourKeywordTrampoline}; -static const TransformFrameOps MINUTE_KEYWORD_OPS = {"MinuteKeyword", - &PEGTransformerFactory::InitializeMinuteKeywordTrampoline, - &PEGTransformerFactory::FinalizeMinuteKeywordTrampoline}; -static const TransformFrameOps SECOND_KEYWORD_OPS = {"SecondKeyword", - &PEGTransformerFactory::InitializeSecondKeywordTrampoline, - &PEGTransformerFactory::FinalizeSecondKeywordTrampoline}; -static const TransformFrameOps MILLISECOND_KEYWORD_OPS = { - "MillisecondKeyword", &PEGTransformerFactory::InitializeMillisecondKeywordTrampoline, - &PEGTransformerFactory::FinalizeMillisecondKeywordTrampoline}; -static const TransformFrameOps MICROSECOND_KEYWORD_OPS = { - "MicrosecondKeyword", &PEGTransformerFactory::InitializeMicrosecondKeywordTrampoline, - &PEGTransformerFactory::FinalizeMicrosecondKeywordTrampoline}; -static const TransformFrameOps WEEK_KEYWORD_OPS = {"WeekKeyword", - &PEGTransformerFactory::InitializeWeekKeywordTrampoline, - &PEGTransformerFactory::FinalizeWeekKeywordTrampoline}; -static const TransformFrameOps QUARTER_KEYWORD_OPS = {"QuarterKeyword", - &PEGTransformerFactory::InitializeQuarterKeywordTrampoline, - &PEGTransformerFactory::FinalizeQuarterKeywordTrampoline}; -static const TransformFrameOps DECADE_KEYWORD_OPS = {"DecadeKeyword", - &PEGTransformerFactory::InitializeDecadeKeywordTrampoline, - &PEGTransformerFactory::FinalizeDecadeKeywordTrampoline}; -static const TransformFrameOps CENTURY_KEYWORD_OPS = {"CenturyKeyword", - &PEGTransformerFactory::InitializeCenturyKeywordTrampoline, - &PEGTransformerFactory::FinalizeCenturyKeywordTrampoline}; -static const TransformFrameOps MILLENNIUM_KEYWORD_OPS = {"MillenniumKeyword", - &PEGTransformerFactory::InitializeMillenniumKeywordTrampoline, - &PEGTransformerFactory::FinalizeMillenniumKeywordTrampoline}; -static const TransformFrameOps INTERVAL_OPS = {"Interval", &PEGTransformerFactory::InitializeIntervalTrampoline, - &PEGTransformerFactory::FinalizeIntervalTrampoline}; -static const TransformFrameOps INTERVAL_TO_INTERVAL_OPS = { - "IntervalToInterval", &PEGTransformerFactory::InitializeIntervalToIntervalTrampoline, - &PEGTransformerFactory::FinalizeIntervalToIntervalTrampoline}; -static const TransformFrameOps YEAR_TO_MONTH_OPS = {"YearToMonth", - &PEGTransformerFactory::InitializeYearToMonthTrampoline, - &PEGTransformerFactory::FinalizeYearToMonthTrampoline}; -static const TransformFrameOps DAY_TO_HOUR_OPS = {"DayToHour", &PEGTransformerFactory::InitializeDayToHourTrampoline, - &PEGTransformerFactory::FinalizeDayToHourTrampoline}; -static const TransformFrameOps DAY_TO_MINUTE_OPS = {"DayToMinute", - &PEGTransformerFactory::InitializeDayToMinuteTrampoline, - &PEGTransformerFactory::FinalizeDayToMinuteTrampoline}; -static const TransformFrameOps DAY_TO_SECOND_OPS = {"DayToSecond", - &PEGTransformerFactory::InitializeDayToSecondTrampoline, - &PEGTransformerFactory::FinalizeDayToSecondTrampoline}; -static const TransformFrameOps HOUR_TO_MINUTE_OPS = {"HourToMinute", - &PEGTransformerFactory::InitializeHourToMinuteTrampoline, - &PEGTransformerFactory::FinalizeHourToMinuteTrampoline}; -static const TransformFrameOps HOUR_TO_SECOND_OPS = {"HourToSecond", - &PEGTransformerFactory::InitializeHourToSecondTrampoline, - &PEGTransformerFactory::FinalizeHourToSecondTrampoline}; -static const TransformFrameOps MINUTE_TO_SECOND_OPS = {"MinuteToSecond", - &PEGTransformerFactory::InitializeMinuteToSecondTrampoline, - &PEGTransformerFactory::FinalizeMinuteToSecondTrampoline}; -static const TransformFrameOps BIT_TYPE_OPS = {"BitType", &PEGTransformerFactory::InitializeBitTypeTrampoline, - &PEGTransformerFactory::FinalizeBitTypeTrampoline}; -static const TransformFrameOps GEOMETRY_TYPE_OPS = {"GeometryType", - &PEGTransformerFactory::InitializeGeometryTypeTrampoline, - &PEGTransformerFactory::FinalizeGeometryTypeTrampoline}; -static const TransformFrameOps VARIANT_TYPE_OPS = {"VariantType", - &PEGTransformerFactory::InitializeVariantTypeTrampoline, - &PEGTransformerFactory::FinalizeVariantTypeTrampoline}; -static const TransformFrameOps NUMERIC_TYPE_OPS = {"NumericType", - &PEGTransformerFactory::InitializeNumericTypeTrampoline, - &PEGTransformerFactory::FinalizeNumericTypeTrampoline}; -static const TransformFrameOps SIMPLE_NUMERIC_TYPE_OPS = {"SimpleNumericType", - &PEGTransformerFactory::InitializeSimpleNumericTypeTrampoline, - &PEGTransformerFactory::FinalizeSimpleNumericTypeTrampoline}; -static const TransformFrameOps DECIMAL_NUMERIC_TYPE_OPS = { - "DecimalNumericType", &PEGTransformerFactory::InitializeDecimalNumericTypeTrampoline, - &PEGTransformerFactory::FinalizeDecimalNumericTypeTrampoline}; -static const TransformFrameOps INT_TYPE_OPS = {"IntType", &PEGTransformerFactory::InitializeIntTypeTrampoline, - &PEGTransformerFactory::FinalizeIntTypeTrampoline}; -static const TransformFrameOps INTEGER_TYPE_OPS = {"IntegerType", - &PEGTransformerFactory::InitializeIntegerTypeTrampoline, - &PEGTransformerFactory::FinalizeIntegerTypeTrampoline}; -static const TransformFrameOps SMALLINT_TYPE_OPS = {"SmallintType", - &PEGTransformerFactory::InitializeSmallintTypeTrampoline, - &PEGTransformerFactory::FinalizeSmallintTypeTrampoline}; -static const TransformFrameOps BIGINT_TYPE_OPS = {"BigintType", &PEGTransformerFactory::InitializeBigintTypeTrampoline, - &PEGTransformerFactory::FinalizeBigintTypeTrampoline}; -static const TransformFrameOps REAL_TYPE_OPS = {"RealType", &PEGTransformerFactory::InitializeRealTypeTrampoline, - &PEGTransformerFactory::FinalizeRealTypeTrampoline}; -static const TransformFrameOps BOOLEAN_TYPE_OPS = {"BooleanType", - &PEGTransformerFactory::InitializeBooleanTypeTrampoline, - &PEGTransformerFactory::FinalizeBooleanTypeTrampoline}; -static const TransformFrameOps DOUBLE_TYPE_OPS = {"DoubleType", &PEGTransformerFactory::InitializeDoubleTypeTrampoline, - &PEGTransformerFactory::FinalizeDoubleTypeTrampoline}; -static const TransformFrameOps FLOAT_TYPE_OPS = {"FloatType", &PEGTransformerFactory::InitializeFloatTypeTrampoline, - &PEGTransformerFactory::FinalizeFloatTypeTrampoline}; -static const TransformFrameOps DECIMAL_TYPE_OPS = {"DecimalType", - &PEGTransformerFactory::InitializeDecimalTypeTrampoline, - &PEGTransformerFactory::FinalizeDecimalTypeTrampoline}; -static const TransformFrameOps DEC_TYPE_OPS = {"DecType", &PEGTransformerFactory::InitializeDecTypeTrampoline, - &PEGTransformerFactory::FinalizeDecTypeTrampoline}; -static const TransformFrameOps NUMERIC_MOD_TYPE_OPS = {"NumericModType", - &PEGTransformerFactory::InitializeNumericModTypeTrampoline, - &PEGTransformerFactory::FinalizeNumericModTypeTrampoline}; -static const TransformFrameOps QUALIFIED_TYPE_NAME_OPS = {"QualifiedTypeName", - &PEGTransformerFactory::InitializeQualifiedTypeNameTrampoline, - &PEGTransformerFactory::FinalizeQualifiedTypeNameTrampoline}; -static const TransformFrameOps TYPE_NAME_AS_QUALIFIED_NAME_OPS = { - "TypeNameAsQualifiedName", &PEGTransformerFactory::InitializeTypeNameAsQualifiedNameTrampoline, - &PEGTransformerFactory::FinalizeTypeNameAsQualifiedNameTrampoline}; -static const TransformFrameOps CATALOG_RESERVED_SCHEMA_TYPE_NAME_OPS = { - "CatalogReservedSchemaTypeName", &PEGTransformerFactory::InitializeCatalogReservedSchemaTypeNameTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTypeNameTrampoline}; -static const TransformFrameOps SCHEMA_RESERVED_TYPE_NAME_OPS = { - "SchemaReservedTypeName", &PEGTransformerFactory::InitializeSchemaReservedTypeNameTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTypeNameTrampoline}; -static const TransformFrameOps TYPE_MODIFIERS_OPS = {"TypeModifiers", - &PEGTransformerFactory::InitializeTypeModifiersTrampoline, - &PEGTransformerFactory::FinalizeTypeModifiersTrampoline}; -static const TransformFrameOps NESTED_TYPE_OPS = {"NestedType", &PEGTransformerFactory::InitializeNestedTypeTrampoline, - &PEGTransformerFactory::FinalizeNestedTypeTrampoline}; -static const TransformFrameOps ROW_TYPE_OPS = {"RowType", &PEGTransformerFactory::InitializeRowTypeTrampoline, - &PEGTransformerFactory::FinalizeRowTypeTrampoline}; -static const TransformFrameOps SETOF_TYPE_OPS = {"SetofType", &PEGTransformerFactory::InitializeSetofTypeTrampoline, - &PEGTransformerFactory::FinalizeSetofTypeTrampoline}; -static const TransformFrameOps UNION_TYPE_OPS = {"UnionType", &PEGTransformerFactory::InitializeUnionTypeTrampoline, - &PEGTransformerFactory::FinalizeUnionTypeTrampoline}; -static const TransformFrameOps COL_ID_TYPE_LIST_OPS = {"ColIdTypeList", - &PEGTransformerFactory::InitializeColIdTypeListTrampoline, - &PEGTransformerFactory::FinalizeColIdTypeListTrampoline}; -static const TransformFrameOps MAP_TYPE_OPS = {"MapType", &PEGTransformerFactory::InitializeMapTypeTrampoline, - &PEGTransformerFactory::FinalizeMapTypeTrampoline}; -static const TransformFrameOps TUPLE_TYPE_OPS = {"TupleType", &PEGTransformerFactory::InitializeTupleTypeTrampoline, - &PEGTransformerFactory::FinalizeTupleTypeTrampoline}; -static const TransformFrameOps COL_ID_TYPE_OPS = {"ColIdType", &PEGTransformerFactory::InitializeColIdTypeTrampoline, - &PEGTransformerFactory::FinalizeColIdTypeTrampoline}; -static const TransformFrameOps ARRAY_BOUNDS_OPS = {"ArrayBounds", - &PEGTransformerFactory::InitializeArrayBoundsTrampoline, - &PEGTransformerFactory::FinalizeArrayBoundsTrampoline}; -static const TransformFrameOps ARRAY_KEYWORD_OPS = {"ArrayKeyword", - &PEGTransformerFactory::InitializeArrayKeywordTrampoline, - &PEGTransformerFactory::FinalizeArrayKeywordTrampoline}; -static const TransformFrameOps ARRAY_KEYWORD_WITH_BOUNDS_OPS = { - "ArrayKeywordWithBounds", &PEGTransformerFactory::InitializeArrayKeywordWithBoundsTrampoline, - &PEGTransformerFactory::FinalizeArrayKeywordWithBoundsTrampoline}; -static const TransformFrameOps SQUARE_BRACKETS_ARRAY_OPS = { - "SquareBracketsArray", &PEGTransformerFactory::InitializeSquareBracketsArrayTrampoline, - &PEGTransformerFactory::FinalizeSquareBracketsArrayTrampoline}; -static const TransformFrameOps TIME_TYPE_OPS = {"TimeType", &PEGTransformerFactory::InitializeTimeTypeTrampoline, - &PEGTransformerFactory::FinalizeTimeTypeTrampoline}; -static const TransformFrameOps TIME_OR_TIMESTAMP_OPS = {"TimeOrTimestamp", - &PEGTransformerFactory::InitializeTimeOrTimestampTrampoline, - &PEGTransformerFactory::FinalizeTimeOrTimestampTrampoline}; -static const TransformFrameOps TIME_TYPE_ID_OPS = {"TimeTypeId", &PEGTransformerFactory::InitializeTimeTypeIdTrampoline, - &PEGTransformerFactory::FinalizeTimeTypeIdTrampoline}; -static const TransformFrameOps TIMESTAMP_TYPE_ID_OPS = {"TimestampTypeId", - &PEGTransformerFactory::InitializeTimestampTypeIdTrampoline, - &PEGTransformerFactory::FinalizeTimestampTypeIdTrampoline}; -static const TransformFrameOps TIME_ZONE_OPS = {"TimeZone", &PEGTransformerFactory::InitializeTimeZoneTrampoline, - &PEGTransformerFactory::FinalizeTimeZoneTrampoline}; -static const TransformFrameOps WITH_OR_WITHOUT_OPS = {"WithOrWithout", - &PEGTransformerFactory::InitializeWithOrWithoutTrampoline, - &PEGTransformerFactory::FinalizeWithOrWithoutTrampoline}; -static const TransformFrameOps WITH_RULE_OPS = {"WithRule", &PEGTransformerFactory::InitializeWithRuleTrampoline, - &PEGTransformerFactory::FinalizeWithRuleTrampoline}; -static const TransformFrameOps WITHOUT_RULE_OPS = {"WithoutRule", - &PEGTransformerFactory::InitializeWithoutRuleTrampoline, - &PEGTransformerFactory::FinalizeWithoutRuleTrampoline}; -static const TransformFrameOps CONNECT_STATEMENT_OPS = {"ConnectStatement", - &PEGTransformerFactory::InitializeConnectStatementTrampoline, - &PEGTransformerFactory::FinalizeConnectStatementTrampoline}; -static const TransformFrameOps DISCONNECT_STATEMENT_OPS = { - "DisconnectStatement", &PEGTransformerFactory::InitializeDisconnectStatementTrampoline, - &PEGTransformerFactory::FinalizeDisconnectStatementTrampoline}; -static const TransformFrameOps SESSION_TARGET_OPS = {"SessionTarget", - &PEGTransformerFactory::InitializeSessionTargetTrampoline, - &PEGTransformerFactory::FinalizeSessionTargetTrampoline}; -static const TransformFrameOps LOCAL_SESSION_TARGET_OPS = { - "LocalSessionTarget", &PEGTransformerFactory::InitializeLocalSessionTargetTrampoline, - &PEGTransformerFactory::FinalizeLocalSessionTargetTrampoline}; -static const TransformFrameOps STRING_SESSION_TARGET_OPS = { - "StringSessionTarget", &PEGTransformerFactory::InitializeStringSessionTargetTrampoline, - &PEGTransformerFactory::FinalizeStringSessionTargetTrampoline}; -static const TransformFrameOps CATALOG_SESSION_TARGET_OPS = { - "CatalogSessionTarget", &PEGTransformerFactory::InitializeCatalogSessionTargetTrampoline, - &PEGTransformerFactory::FinalizeCatalogSessionTargetTrampoline}; -static const TransformFrameOps COPY_STATEMENT_OPS = {"CopyStatement", - &PEGTransformerFactory::InitializeCopyStatementTrampoline, - &PEGTransformerFactory::FinalizeCopyStatementTrampoline}; -static const TransformFrameOps COPY_VARIATIONS_OPS = {"CopyVariations", - &PEGTransformerFactory::InitializeCopyVariationsTrampoline, - &PEGTransformerFactory::FinalizeCopyVariationsTrampoline}; -static const TransformFrameOps COPY_TABLE_OPS = {"CopyTable", &PEGTransformerFactory::InitializeCopyTableTrampoline, - &PEGTransformerFactory::FinalizeCopyTableTrampoline}; -static const TransformFrameOps FROM_OR_TO_OPS = {"FromOrTo", &PEGTransformerFactory::InitializeFromOrToTrampoline, - &PEGTransformerFactory::FinalizeFromOrToTrampoline}; -static const TransformFrameOps COPY_FROM_OPS = {"CopyFrom", &PEGTransformerFactory::InitializeCopyFromTrampoline, - &PEGTransformerFactory::FinalizeCopyFromTrampoline}; -static const TransformFrameOps COPY_TO_OPS = {"CopyTo", &PEGTransformerFactory::InitializeCopyToTrampoline, - &PEGTransformerFactory::FinalizeCopyToTrampoline}; -static const TransformFrameOps COPY_SELECT_OPS = {"CopySelect", &PEGTransformerFactory::InitializeCopySelectTrampoline, - &PEGTransformerFactory::FinalizeCopySelectTrampoline}; -static const TransformFrameOps COPY_FILE_NAME_OPS = {"CopyFileName", - &PEGTransformerFactory::InitializeCopyFileNameTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameTrampoline}; -static const TransformFrameOps COPY_FILE_NAME_EXPRESSION_OPS = { - "CopyFileNameExpression", &PEGTransformerFactory::InitializeCopyFileNameExpressionTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameExpressionTrampoline}; -static const TransformFrameOps COPY_FILE_NAME_STRING_LITERAL_OPS = { - "CopyFileNameStringLiteral", &PEGTransformerFactory::InitializeCopyFileNameStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameStringLiteralTrampoline}; -static const TransformFrameOps COPY_FILE_NAME_IDENTIFIER_OPS = { - "CopyFileNameIdentifier", &PEGTransformerFactory::InitializeCopyFileNameIdentifierTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameIdentifierTrampoline}; -static const TransformFrameOps COPY_FILE_NAME_IDENTIFIER_COL_ID_OPS = { - "CopyFileNameIdentifierColId", &PEGTransformerFactory::InitializeCopyFileNameIdentifierColIdTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameIdentifierColIdTrampoline}; -static const TransformFrameOps IDENTIFIER_COL_ID_OPS = {"IdentifierColId", - &PEGTransformerFactory::InitializeIdentifierColIdTrampoline, - &PEGTransformerFactory::FinalizeIdentifierColIdTrampoline}; -static const TransformFrameOps COPY_FILE_NAME_SUFFIX_OPS = { - "CopyFileNameSuffix", &PEGTransformerFactory::InitializeCopyFileNameSuffixTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameSuffixTrampoline}; -static const TransformFrameOps COPY_LEGACY_OPTION_OPS = {"CopyLegacyOption", - &PEGTransformerFactory::InitializeCopyLegacyOptionTrampoline, - &PEGTransformerFactory::FinalizeCopyLegacyOptionTrampoline}; -static const TransformFrameOps COPY_OPTIONS_OPS = {"CopyOptions", - &PEGTransformerFactory::InitializeCopyOptionsTrampoline, - &PEGTransformerFactory::FinalizeCopyOptionsTrampoline}; -static const TransformFrameOps COPY_OPTION_LIST_OPS = {"CopyOptionList", - &PEGTransformerFactory::InitializeCopyOptionListTrampoline, - &PEGTransformerFactory::FinalizeCopyOptionListTrampoline}; -static const TransformFrameOps SPECIALIZED_OPTION_LIST_OPS = { - "SpecializedOptionList", &PEGTransformerFactory::InitializeSpecializedOptionListTrampoline, - &PEGTransformerFactory::FinalizeSpecializedOptionListTrampoline}; -static const TransformFrameOps SPECIALIZED_OPTION_TAIL_OPS = { - "SpecializedOptionTail", &PEGTransformerFactory::InitializeSpecializedOptionTailTrampoline, - &PEGTransformerFactory::FinalizeSpecializedOptionTailTrampoline}; -static const TransformFrameOps SPECIALIZED_OPTION_OPS = {"SpecializedOption", - &PEGTransformerFactory::InitializeSpecializedOptionTrampoline, - &PEGTransformerFactory::FinalizeSpecializedOptionTrampoline}; -static const TransformFrameOps SINGLE_OPTION_OPS = {"SingleOption", - &PEGTransformerFactory::InitializeSingleOptionTrampoline, - &PEGTransformerFactory::FinalizeSingleOptionTrampoline}; -static const TransformFrameOps BINARY_OPTION_OPS = {"BinaryOption", - &PEGTransformerFactory::InitializeBinaryOptionTrampoline, - &PEGTransformerFactory::FinalizeBinaryOptionTrampoline}; -static const TransformFrameOps FREEZE_OPTION_OPS = {"FreezeOption", - &PEGTransformerFactory::InitializeFreezeOptionTrampoline, - &PEGTransformerFactory::FinalizeFreezeOptionTrampoline}; -static const TransformFrameOps OIDS_OPTION_OPS = {"OidsOption", &PEGTransformerFactory::InitializeOidsOptionTrampoline, - &PEGTransformerFactory::FinalizeOidsOptionTrampoline}; -static const TransformFrameOps CSV_OPTION_OPS = {"CsvOption", &PEGTransformerFactory::InitializeCsvOptionTrampoline, - &PEGTransformerFactory::FinalizeCsvOptionTrampoline}; -static const TransformFrameOps HEADER_OPTION_OPS = {"HeaderOption", - &PEGTransformerFactory::InitializeHeaderOptionTrampoline, - &PEGTransformerFactory::FinalizeHeaderOptionTrampoline}; -static const TransformFrameOps NULL_AS_OPTION_OPS = {"NullAsOption", - &PEGTransformerFactory::InitializeNullAsOptionTrampoline, - &PEGTransformerFactory::FinalizeNullAsOptionTrampoline}; -static const TransformFrameOps DELIMITER_AS_OPTION_OPS = {"DelimiterAsOption", - &PEGTransformerFactory::InitializeDelimiterAsOptionTrampoline, - &PEGTransformerFactory::FinalizeDelimiterAsOptionTrampoline}; -static const TransformFrameOps QUOTE_AS_OPTION_OPS = {"QuoteAsOption", - &PEGTransformerFactory::InitializeQuoteAsOptionTrampoline, - &PEGTransformerFactory::FinalizeQuoteAsOptionTrampoline}; -static const TransformFrameOps ESCAPE_AS_OPTION_OPS = {"EscapeAsOption", - &PEGTransformerFactory::InitializeEscapeAsOptionTrampoline, - &PEGTransformerFactory::FinalizeEscapeAsOptionTrampoline}; -static const TransformFrameOps ENCODING_OPTION_OPS = {"EncodingOption", - &PEGTransformerFactory::InitializeEncodingOptionTrampoline, - &PEGTransformerFactory::FinalizeEncodingOptionTrampoline}; -static const TransformFrameOps FORCE_QUOTE_OPTION_OPS = {"ForceQuoteOption", - &PEGTransformerFactory::InitializeForceQuoteOptionTrampoline, - &PEGTransformerFactory::FinalizeForceQuoteOptionTrampoline}; -static const TransformFrameOps STAR_SYMBOL_COLUMN_LIST_OPS = { - "StarSymbolColumnList", &PEGTransformerFactory::InitializeStarSymbolColumnListTrampoline, - &PEGTransformerFactory::FinalizeStarSymbolColumnListTrampoline}; -static const TransformFrameOps FORCE_QUOTE_OPS = {"ForceQuote", &PEGTransformerFactory::InitializeForceQuoteTrampoline, - &PEGTransformerFactory::FinalizeForceQuoteTrampoline}; -static const TransformFrameOps PARTITION_BY_OPTION_OPS = {"PartitionByOption", - &PEGTransformerFactory::InitializePartitionByOptionTrampoline, - &PEGTransformerFactory::FinalizePartitionByOptionTrampoline}; -static const TransformFrameOps PARTITION_BY_COLUMN_LIST_OPS = { - "PartitionByColumnList", &PEGTransformerFactory::InitializePartitionByColumnListTrampoline, - &PEGTransformerFactory::FinalizePartitionByColumnListTrampoline}; -static const TransformFrameOps STAR_PARTITION_BY_COLUMN_LIST_OPS = { - "StarPartitionByColumnList", &PEGTransformerFactory::InitializeStarPartitionByColumnListTrampoline, - &PEGTransformerFactory::FinalizeStarPartitionByColumnListTrampoline}; -static const TransformFrameOps PARENTHESIZED_PARTITION_BY_COLUMN_LIST_OPS = { - "ParenthesizedPartitionByColumnList", - &PEGTransformerFactory::InitializeParenthesizedPartitionByColumnListTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedPartitionByColumnListTrampoline}; -static const TransformFrameOps SINGLE_PARTITION_BY_COLUMN_LIST_OPS = { - "SinglePartitionByColumnList", &PEGTransformerFactory::InitializeSinglePartitionByColumnListTrampoline, - &PEGTransformerFactory::FinalizeSinglePartitionByColumnListTrampoline}; -static const TransformFrameOps FORCE_NULL_OPTION_OPS = {"ForceNullOption", - &PEGTransformerFactory::InitializeForceNullOptionTrampoline, - &PEGTransformerFactory::FinalizeForceNullOptionTrampoline}; -static const TransformFrameOps FORCE_NOT_NULL_OPS = {"ForceNotNull", - &PEGTransformerFactory::InitializeForceNotNullTrampoline, - &PEGTransformerFactory::FinalizeForceNotNullTrampoline}; -static const TransformFrameOps COPY_GENERIC_OPTION_LIST_OPS = { - "CopyGenericOptionList", &PEGTransformerFactory::InitializeCopyGenericOptionListTrampoline, - &PEGTransformerFactory::FinalizeCopyGenericOptionListTrampoline}; -static const TransformFrameOps COPY_GENERIC_OPTION_OPS = {"CopyGenericOption", - &PEGTransformerFactory::InitializeCopyGenericOptionTrampoline, - &PEGTransformerFactory::FinalizeCopyGenericOptionTrampoline}; -static const TransformFrameOps ORDER_BY_COPY_OPTION_OPS = { - "OrderByCopyOption", &PEGTransformerFactory::InitializeOrderByCopyOptionTrampoline, - &PEGTransformerFactory::FinalizeOrderByCopyOptionTrampoline}; -static const TransformFrameOps PARTITIONED_BY_COPY_OPTION_OPS = { - "PartitionedByCopyOption", &PEGTransformerFactory::InitializePartitionedByCopyOptionTrampoline, - &PEGTransformerFactory::FinalizePartitionedByCopyOptionTrampoline}; -static const TransformFrameOps GENERIC_COPY_OPTION_LIST_OPS = { - "GenericCopyOptionList", &PEGTransformerFactory::InitializeGenericCopyOptionListTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionListTrampoline}; -static const TransformFrameOps GENERIC_COPY_OPTION_OPS = {"GenericCopyOption", - &PEGTransformerFactory::InitializeGenericCopyOptionTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionTrampoline}; -static const TransformFrameOps GENERIC_COPY_OPTION_VALUE_OPS = { - "GenericCopyOptionValue", &PEGTransformerFactory::InitializeGenericCopyOptionValueTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionValueTrampoline}; -static const TransformFrameOps GENERIC_COPY_OPTION_ORDER_LIST_OPS = { - "GenericCopyOptionOrderList", &PEGTransformerFactory::InitializeGenericCopyOptionOrderListTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionOrderListTrampoline}; -static const TransformFrameOps GENERIC_COPY_OPTION_EXPRESSION_OPS = { - "GenericCopyOptionExpression", &PEGTransformerFactory::InitializeGenericCopyOptionExpressionTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionExpressionTrampoline}; -static const TransformFrameOps GENERIC_COPY_OPTION_PARENTHESIZED_EXPRESSION_LIST_OPS = { - "GenericCopyOptionParenthesizedExpressionList", - &PEGTransformerFactory::InitializeGenericCopyOptionParenthesizedExpressionListTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionParenthesizedExpressionListTrampoline}; -static const TransformFrameOps COPY_FROM_DATABASE_OPS = {"CopyFromDatabase", - &PEGTransformerFactory::InitializeCopyFromDatabaseTrampoline, - &PEGTransformerFactory::FinalizeCopyFromDatabaseTrampoline}; -static const TransformFrameOps COPY_FROM_DATABASE_WITH_FLAG_OPS = { - "CopyFromDatabaseWithFlag", &PEGTransformerFactory::InitializeCopyFromDatabaseWithFlagTrampoline, - &PEGTransformerFactory::FinalizeCopyFromDatabaseWithFlagTrampoline}; -static const TransformFrameOps COPY_FROM_DATABASE_WITHOUT_FLAG_OPS = { - "CopyFromDatabaseWithoutFlag", &PEGTransformerFactory::InitializeCopyFromDatabaseWithoutFlagTrampoline, - &PEGTransformerFactory::FinalizeCopyFromDatabaseWithoutFlagTrampoline}; -static const TransformFrameOps COPY_DATABASE_FLAG_OPS = {"CopyDatabaseFlag", - &PEGTransformerFactory::InitializeCopyDatabaseFlagTrampoline, - &PEGTransformerFactory::FinalizeCopyDatabaseFlagTrampoline}; -static const TransformFrameOps SCHEMA_OR_DATA_OPS = {"SchemaOrData", - &PEGTransformerFactory::InitializeSchemaOrDataTrampoline, - &PEGTransformerFactory::FinalizeSchemaOrDataTrampoline}; -static const TransformFrameOps COPY_SCHEMA_OPS = {"CopySchema", &PEGTransformerFactory::InitializeCopySchemaTrampoline, - &PEGTransformerFactory::FinalizeCopySchemaTrampoline}; -static const TransformFrameOps COPY_DATA_OPS = {"CopyData", &PEGTransformerFactory::InitializeCopyDataTrampoline, - &PEGTransformerFactory::FinalizeCopyDataTrampoline}; -static const TransformFrameOps CREATE_INDEX_STMT_OPS = {"CreateIndexStmt", - &PEGTransformerFactory::InitializeCreateIndexStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateIndexStmtTrampoline}; -static const TransformFrameOps WITH_LIST_OPS = {"WithList", &PEGTransformerFactory::InitializeWithListTrampoline, - &PEGTransformerFactory::FinalizeWithListTrampoline}; -static const TransformFrameOps REL_OPTION_OR_OIDS_OPS = {"RelOptionOrOids", - &PEGTransformerFactory::InitializeRelOptionOrOidsTrampoline, - &PEGTransformerFactory::FinalizeRelOptionOrOidsTrampoline}; -static const TransformFrameOps REL_OPTION_LIST_OPS = {"RelOptionList", - &PEGTransformerFactory::InitializeRelOptionListTrampoline, - &PEGTransformerFactory::FinalizeRelOptionListTrampoline}; -static const TransformFrameOps OIDS_OPS = {"Oids", &PEGTransformerFactory::InitializeOidsTrampoline, - &PEGTransformerFactory::FinalizeOidsTrampoline}; -static const TransformFrameOps WITH_OR_WITHOUT_OIDS_OPS = { - "WithOrWithoutOids", &PEGTransformerFactory::InitializeWithOrWithoutOidsTrampoline, - &PEGTransformerFactory::FinalizeWithOrWithoutOidsTrampoline}; -static const TransformFrameOps WITH_OIDS_OPS = {"WithOids", &PEGTransformerFactory::InitializeWithOidsTrampoline, - &PEGTransformerFactory::FinalizeWithOidsTrampoline}; -static const TransformFrameOps WITHOUT_OIDS_OPS = {"WithoutOids", - &PEGTransformerFactory::InitializeWithoutOidsTrampoline, - &PEGTransformerFactory::FinalizeWithoutOidsTrampoline}; -static const TransformFrameOps INDEX_ELEMENT_OPS = {"IndexElement", - &PEGTransformerFactory::InitializeIndexElementTrampoline, - &PEGTransformerFactory::FinalizeIndexElementTrampoline}; -static const TransformFrameOps UNIQUE_INDEX_OPS = {"UniqueIndex", - &PEGTransformerFactory::InitializeUniqueIndexTrampoline, - &PEGTransformerFactory::FinalizeUniqueIndexTrampoline}; -static const TransformFrameOps INDEX_TYPE_OPS = {"IndexType", &PEGTransformerFactory::InitializeIndexTypeTrampoline, - &PEGTransformerFactory::FinalizeIndexTypeTrampoline}; -static const TransformFrameOps REL_OPTION_OPS = {"RelOption", &PEGTransformerFactory::InitializeRelOptionTrampoline, - &PEGTransformerFactory::FinalizeRelOptionTrampoline}; -static const TransformFrameOps REL_OPTION_NAME_OPS = {"RelOptionName", - &PEGTransformerFactory::InitializeRelOptionNameTrampoline, - &PEGTransformerFactory::FinalizeRelOptionNameTrampoline}; -static const TransformFrameOps DOTTED_COL_LABEL_OPS = {"DottedColLabel", - &PEGTransformerFactory::InitializeDottedColLabelTrampoline, - &PEGTransformerFactory::FinalizeDottedColLabelTrampoline}; -static const TransformFrameOps REL_OPTION_ARGUMENT_OPT_OPS = { - "RelOptionArgumentOpt", &PEGTransformerFactory::InitializeRelOptionArgumentOptTrampoline, - &PEGTransformerFactory::FinalizeRelOptionArgumentOptTrampoline}; -static const TransformFrameOps DEF_ARG_OPS = {"DefArg", &PEGTransformerFactory::InitializeDefArgTrampoline, - &PEGTransformerFactory::FinalizeDefArgTrampoline}; -static const TransformFrameOps DEF_ARG_NULL_OPS = {"DefArgNull", &PEGTransformerFactory::InitializeDefArgNullTrampoline, - &PEGTransformerFactory::FinalizeDefArgNullTrampoline}; -static const TransformFrameOps DEF_ARG_KEYWORD_OPS = {"DefArgKeyword", - &PEGTransformerFactory::InitializeDefArgKeywordTrampoline, - &PEGTransformerFactory::FinalizeDefArgKeywordTrampoline}; -static const TransformFrameOps DEF_ARG_STRING_LITERAL_OPS = { - "DefArgStringLiteral", &PEGTransformerFactory::InitializeDefArgStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeDefArgStringLiteralTrampoline}; -static const TransformFrameOps NONE_LITERAL_OPS = {"NoneLiteral", - &PEGTransformerFactory::InitializeNoneLiteralTrampoline, - &PEGTransformerFactory::FinalizeNoneLiteralTrampoline}; -static const TransformFrameOps CREATE_MACRO_STMT_OPS = {"CreateMacroStmt", - &PEGTransformerFactory::InitializeCreateMacroStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateMacroStmtTrampoline}; -static const TransformFrameOps RETURNS_TYPE_OPS = {"ReturnsType", - &PEGTransformerFactory::InitializeReturnsTypeTrampoline, - &PEGTransformerFactory::FinalizeReturnsTypeTrampoline}; -static const TransformFrameOps MACRO_OR_FUNCTION_OPS = {"MacroOrFunction", - &PEGTransformerFactory::InitializeMacroOrFunctionTrampoline, - &PEGTransformerFactory::FinalizeMacroOrFunctionTrampoline}; -static const TransformFrameOps MACRO_KEYWORD_OPS = {"MacroKeyword", - &PEGTransformerFactory::InitializeMacroKeywordTrampoline, - &PEGTransformerFactory::FinalizeMacroKeywordTrampoline}; -static const TransformFrameOps FUNCTION_KEYWORD_OPS = {"FunctionKeyword", - &PEGTransformerFactory::InitializeFunctionKeywordTrampoline, - &PEGTransformerFactory::FinalizeFunctionKeywordTrampoline}; -static const TransformFrameOps MACRO_DEFINITION_OPS = {"MacroDefinition", - &PEGTransformerFactory::InitializeMacroDefinitionTrampoline, - &PEGTransformerFactory::FinalizeMacroDefinitionTrampoline}; -static const TransformFrameOps MACRO_DEFINITION_BODY_OPS = { - "MacroDefinitionBody", &PEGTransformerFactory::InitializeMacroDefinitionBodyTrampoline, - &PEGTransformerFactory::FinalizeMacroDefinitionBodyTrampoline}; -static const TransformFrameOps MACRO_PARAMETERS_OPS = {"MacroParameters", - &PEGTransformerFactory::InitializeMacroParametersTrampoline, - &PEGTransformerFactory::FinalizeMacroParametersTrampoline}; -static const TransformFrameOps MACRO_PARAMETER_OPS = {"MacroParameter", - &PEGTransformerFactory::InitializeMacroParameterTrampoline, - &PEGTransformerFactory::FinalizeMacroParameterTrampoline}; -static const TransformFrameOps SIMPLE_PARAMETER_OPS = {"SimpleParameter", - &PEGTransformerFactory::InitializeSimpleParameterTrampoline, - &PEGTransformerFactory::FinalizeSimpleParameterTrampoline}; -static const TransformFrameOps SCALAR_MACRO_DEFINITION_OPS = { - "ScalarMacroDefinition", &PEGTransformerFactory::InitializeScalarMacroDefinitionTrampoline, - &PEGTransformerFactory::FinalizeScalarMacroDefinitionTrampoline}; -static const TransformFrameOps TABLE_MACRO_DEFINITION_OPS = { - "TableMacroDefinition", &PEGTransformerFactory::InitializeTableMacroDefinitionTrampoline, - &PEGTransformerFactory::FinalizeTableMacroDefinitionTrampoline}; -static const TransformFrameOps CREATE_SCHEMA_STMT_OPS = {"CreateSchemaStmt", - &PEGTransformerFactory::InitializeCreateSchemaStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateSchemaStmtTrampoline}; -static const TransformFrameOps WITH_OPTION_LIST_OPS = {"WithOptionList", - &PEGTransformerFactory::InitializeWithOptionListTrampoline, - &PEGTransformerFactory::FinalizeWithOptionListTrampoline}; -static const TransformFrameOps CREATE_SECRET_STMT_OPS = {"CreateSecretStmt", - &PEGTransformerFactory::InitializeCreateSecretStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateSecretStmtTrampoline}; -static const TransformFrameOps SECRET_STORAGE_SPECIFIER_OPS = { - "SecretStorageSpecifier", &PEGTransformerFactory::InitializeSecretStorageSpecifierTrampoline, - &PEGTransformerFactory::FinalizeSecretStorageSpecifierTrampoline}; -static const TransformFrameOps SECRET_NAME_OPS = {"SecretName", &PEGTransformerFactory::InitializeSecretNameTrampoline, - &PEGTransformerFactory::FinalizeSecretNameTrampoline}; -static const TransformFrameOps CREATE_SEQUENCE_STMT_OPS = { - "CreateSequenceStmt", &PEGTransformerFactory::InitializeCreateSequenceStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateSequenceStmtTrampoline}; -static const TransformFrameOps SEQUENCE_OPTION_OPS = {"SequenceOption", - &PEGTransformerFactory::InitializeSequenceOptionTrampoline, - &PEGTransformerFactory::FinalizeSequenceOptionTrampoline}; -static const TransformFrameOps SEQ_SET_CYCLE_OPS = {"SeqSetCycle", - &PEGTransformerFactory::InitializeSeqSetCycleTrampoline, - &PEGTransformerFactory::FinalizeSeqSetCycleTrampoline}; -static const TransformFrameOps SEQ_CYCLE_OPS = {"SeqCycle", &PEGTransformerFactory::InitializeSeqCycleTrampoline, - &PEGTransformerFactory::FinalizeSeqCycleTrampoline}; -static const TransformFrameOps SEQ_NO_CYCLE_OPS = {"SeqNoCycle", &PEGTransformerFactory::InitializeSeqNoCycleTrampoline, - &PEGTransformerFactory::FinalizeSeqNoCycleTrampoline}; -static const TransformFrameOps SEQ_SET_INCREMENT_OPS = {"SeqSetIncrement", - &PEGTransformerFactory::InitializeSeqSetIncrementTrampoline, - &PEGTransformerFactory::FinalizeSeqSetIncrementTrampoline}; -static const TransformFrameOps SEQ_SET_MIN_MAX_OPS = {"SeqSetMinMax", - &PEGTransformerFactory::InitializeSeqSetMinMaxTrampoline, - &PEGTransformerFactory::FinalizeSeqSetMinMaxTrampoline}; -static const TransformFrameOps SEQ_NO_MIN_MAX_OPS = {"SeqNoMinMax", - &PEGTransformerFactory::InitializeSeqNoMinMaxTrampoline, - &PEGTransformerFactory::FinalizeSeqNoMinMaxTrampoline}; -static const TransformFrameOps SEQ_START_WITH_OPS = {"SeqStartWith", - &PEGTransformerFactory::InitializeSeqStartWithTrampoline, - &PEGTransformerFactory::FinalizeSeqStartWithTrampoline}; -static const TransformFrameOps SEQ_OWNED_BY_OPS = {"SeqOwnedBy", &PEGTransformerFactory::InitializeSeqOwnedByTrampoline, - &PEGTransformerFactory::FinalizeSeqOwnedByTrampoline}; -static const TransformFrameOps SEQ_MIN_OR_MAX_OPS = {"SeqMinOrMax", - &PEGTransformerFactory::InitializeSeqMinOrMaxTrampoline, - &PEGTransformerFactory::FinalizeSeqMinOrMaxTrampoline}; -static const TransformFrameOps MIN_VALUE_OPS = {"MinValue", &PEGTransformerFactory::InitializeMinValueTrampoline, - &PEGTransformerFactory::FinalizeMinValueTrampoline}; -static const TransformFrameOps MAX_VALUE_OPS = {"MaxValue", &PEGTransformerFactory::InitializeMaxValueTrampoline, - &PEGTransformerFactory::FinalizeMaxValueTrampoline}; -static const TransformFrameOps CREATE_STATEMENT_OPS = {"CreateStatement", - &PEGTransformerFactory::InitializeCreateStatementTrampoline, - &PEGTransformerFactory::FinalizeCreateStatementTrampoline}; -static const TransformFrameOps CREATE_STATEMENT_VARIATION_OPS = { - "CreateStatementVariation", &PEGTransformerFactory::InitializeCreateStatementVariationTrampoline, - &PEGTransformerFactory::FinalizeCreateStatementVariationTrampoline}; -static const TransformFrameOps OR_REPLACE_OPS = {"OrReplace", &PEGTransformerFactory::InitializeOrReplaceTrampoline, - &PEGTransformerFactory::FinalizeOrReplaceTrampoline}; -static const TransformFrameOps TEMPORARY_OPS = {"Temporary", &PEGTransformerFactory::InitializeTemporaryTrampoline, - &PEGTransformerFactory::FinalizeTemporaryTrampoline}; -static const TransformFrameOps PERSISTENT_OPS = {"Persistent", &PEGTransformerFactory::InitializePersistentTrampoline, - &PEGTransformerFactory::FinalizePersistentTrampoline}; -static const TransformFrameOps TEMP_PERSISTENT_OPS = {"TempPersistent", - &PEGTransformerFactory::InitializeTempPersistentTrampoline, - &PEGTransformerFactory::FinalizeTempPersistentTrampoline}; -static const TransformFrameOps TEMPORARY_PERSISTENT_OPS = { - "TemporaryPersistent", &PEGTransformerFactory::InitializeTemporaryPersistentTrampoline, - &PEGTransformerFactory::FinalizeTemporaryPersistentTrampoline}; -static const TransformFrameOps CREATE_TABLE_STMT_OPS = {"CreateTableStmt", - &PEGTransformerFactory::InitializeCreateTableStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateTableStmtTrampoline}; -static const TransformFrameOps CREATE_TABLE_DEFINITION_OPS = { - "CreateTableDefinition", &PEGTransformerFactory::InitializeCreateTableDefinitionTrampoline, - &PEGTransformerFactory::FinalizeCreateTableDefinitionTrampoline}; -static const TransformFrameOps CREATE_TABLE_AS_OPS = {"CreateTableAs", - &PEGTransformerFactory::InitializeCreateTableAsTrampoline, - &PEGTransformerFactory::FinalizeCreateTableAsTrampoline}; -static const TransformFrameOps PARTITION_SORTED_OPTIONS_OPS = { - "PartitionSortedOptions", &PEGTransformerFactory::InitializePartitionSortedOptionsTrampoline, - &PEGTransformerFactory::FinalizePartitionSortedOptionsTrampoline}; -static const TransformFrameOps PARTITION_OPT_SORTED_OPTIONS_OPS = { - "PartitionOptSortedOptions", &PEGTransformerFactory::InitializePartitionOptSortedOptionsTrampoline, - &PEGTransformerFactory::FinalizePartitionOptSortedOptionsTrampoline}; -static const TransformFrameOps SORTED_OPT_PARTITION_OPTIONS_OPS = { - "SortedOptPartitionOptions", &PEGTransformerFactory::InitializeSortedOptPartitionOptionsTrampoline, - &PEGTransformerFactory::FinalizeSortedOptPartitionOptionsTrampoline}; -static const TransformFrameOps PARTITION_OPTIONS_OPS = {"PartitionOptions", - &PEGTransformerFactory::InitializePartitionOptionsTrampoline, - &PEGTransformerFactory::FinalizePartitionOptionsTrampoline}; -static const TransformFrameOps SORTED_OPTIONS_OPS = {"SortedOptions", - &PEGTransformerFactory::InitializeSortedOptionsTrampoline, - &PEGTransformerFactory::FinalizeSortedOptionsTrampoline}; -static const TransformFrameOps WITH_DATA_OPS = {"WithData", &PEGTransformerFactory::InitializeWithDataTrampoline, - &PEGTransformerFactory::FinalizeWithDataTrampoline}; -static const TransformFrameOps WITH_DATA_ONLY_OPS = {"WithDataOnly", - &PEGTransformerFactory::InitializeWithDataOnlyTrampoline, - &PEGTransformerFactory::FinalizeWithDataOnlyTrampoline}; -static const TransformFrameOps WITH_NO_DATA_OPS = {"WithNoData", &PEGTransformerFactory::InitializeWithNoDataTrampoline, - &PEGTransformerFactory::FinalizeWithNoDataTrampoline}; -static const TransformFrameOps IDENTIFIER_LIST_OPS = {"IdentifierList", - &PEGTransformerFactory::InitializeIdentifierListTrampoline, - &PEGTransformerFactory::FinalizeIdentifierListTrampoline}; -static const TransformFrameOps CREATE_COLUMN_LIST_OPS = {"CreateColumnList", - &PEGTransformerFactory::InitializeCreateColumnListTrampoline, - &PEGTransformerFactory::FinalizeCreateColumnListTrampoline}; -static const TransformFrameOps IF_NOT_EXISTS_OPS = {"IfNotExists", - &PEGTransformerFactory::InitializeIfNotExistsTrampoline, - &PEGTransformerFactory::FinalizeIfNotExistsTrampoline}; -static const TransformFrameOps QUALIFIED_NAME_OPS = {"QualifiedName", - &PEGTransformerFactory::InitializeQualifiedNameTrampoline, - &PEGTransformerFactory::FinalizeQualifiedNameTrampoline}; -static const TransformFrameOps SCHEMA_RESERVED_IDENTIFIER_OR_STRING_LITERAL_OPS = { - "SchemaReservedIdentifierOrStringLiteral", - &PEGTransformerFactory::InitializeSchemaReservedIdentifierOrStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline}; -static const TransformFrameOps CATALOG_RESERVED_SCHEMA_IDENTIFIER_OPS = { - "CatalogReservedSchemaIdentifier", &PEGTransformerFactory::InitializeCatalogReservedSchemaIdentifierTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaIdentifierTrampoline}; -static const TransformFrameOps IDENTIFIER_OR_STRING_LITERAL_OPS = { - "IdentifierOrStringLiteral", &PEGTransformerFactory::InitializeIdentifierOrStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrStringLiteralTrampoline}; -static const TransformFrameOps RESERVED_IDENTIFIER_OR_STRING_LITERAL_OPS = { - "ReservedIdentifierOrStringLiteral", &PEGTransformerFactory::InitializeReservedIdentifierOrStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeReservedIdentifierOrStringLiteralTrampoline}; -static const TransformFrameOps CATALOG_QUALIFICATION_OPS = { - "CatalogQualification", &PEGTransformerFactory::InitializeCatalogQualificationTrampoline, - &PEGTransformerFactory::FinalizeCatalogQualificationTrampoline}; -static const TransformFrameOps SCHEMA_QUALIFICATION_OPS = { - "SchemaQualification", &PEGTransformerFactory::InitializeSchemaQualificationTrampoline, - &PEGTransformerFactory::FinalizeSchemaQualificationTrampoline}; -static const TransformFrameOps RESERVED_SCHEMA_QUALIFICATION_OPS = { - "ReservedSchemaQualification", &PEGTransformerFactory::InitializeReservedSchemaQualificationTrampoline, - &PEGTransformerFactory::FinalizeReservedSchemaQualificationTrampoline}; -static const TransformFrameOps TABLE_QUALIFICATION_OPS = { - "TableQualification", &PEGTransformerFactory::InitializeTableQualificationTrampoline, - &PEGTransformerFactory::FinalizeTableQualificationTrampoline}; -static const TransformFrameOps RESERVED_TABLE_QUALIFICATION_OPS = { - "ReservedTableQualification", &PEGTransformerFactory::InitializeReservedTableQualificationTrampoline, - &PEGTransformerFactory::FinalizeReservedTableQualificationTrampoline}; -static const TransformFrameOps CREATE_TABLE_COLUMN_LIST_OPS = { - "CreateTableColumnList", &PEGTransformerFactory::InitializeCreateTableColumnListTrampoline, - &PEGTransformerFactory::FinalizeCreateTableColumnListTrampoline}; -static const TransformFrameOps CREATE_TABLE_COLUMN_ELEMENT_OPS = { - "CreateTableColumnElement", &PEGTransformerFactory::InitializeCreateTableColumnElementTrampoline, - &PEGTransformerFactory::FinalizeCreateTableColumnElementTrampoline}; -static const TransformFrameOps CREATE_TABLE_COLUMN_DEFINITION_OPS = { - "CreateTableColumnDefinition", &PEGTransformerFactory::InitializeCreateTableColumnDefinitionTrampoline, - &PEGTransformerFactory::FinalizeCreateTableColumnDefinitionTrampoline}; -static const TransformFrameOps CREATE_TABLE_CONSTRAINT_OPS = { - "CreateTableConstraint", &PEGTransformerFactory::InitializeCreateTableConstraintTrampoline, - &PEGTransformerFactory::FinalizeCreateTableConstraintTrampoline}; -static const TransformFrameOps COLUMN_DEFINITION_OPS = {"ColumnDefinition", - &PEGTransformerFactory::InitializeColumnDefinitionTrampoline, - &PEGTransformerFactory::FinalizeColumnDefinitionTrampoline}; -static const TransformFrameOps COLUMN_CONSTRAINT_OPS = {"ColumnConstraint", - &PEGTransformerFactory::InitializeColumnConstraintTrampoline, - &PEGTransformerFactory::FinalizeColumnConstraintTrampoline}; -static const TransformFrameOps NAMEABLE_COLUMN_CONSTRAINT_OPS = { - "NameableColumnConstraint", &PEGTransformerFactory::InitializeNameableColumnConstraintTrampoline, - &PEGTransformerFactory::FinalizeNameableColumnConstraintTrampoline}; -static const TransformFrameOps COLUMN_CONSTRAINT_ELEMENT_OPS = { - "ColumnConstraintElement", &PEGTransformerFactory::InitializeColumnConstraintElementTrampoline, - &PEGTransformerFactory::FinalizeColumnConstraintElementTrampoline}; -static const TransformFrameOps NOT_NULL_CONSTRAINT_OPS = {"NotNullConstraint", - &PEGTransformerFactory::InitializeNotNullConstraintTrampoline, - &PEGTransformerFactory::FinalizeNotNullConstraintTrampoline}; -static const TransformFrameOps NULL_CONSTRAINT_OPS = {"NullConstraint", - &PEGTransformerFactory::InitializeNullConstraintTrampoline, - &PEGTransformerFactory::FinalizeNullConstraintTrampoline}; -static const TransformFrameOps NOT_NULL_COLUMN_CONSTRAINT_OPS = { - "NotNullColumnConstraint", &PEGTransformerFactory::InitializeNotNullColumnConstraintTrampoline, - &PEGTransformerFactory::FinalizeNotNullColumnConstraintTrampoline}; -static const TransformFrameOps UNIQUE_CONSTRAINT_OPS = {"UniqueConstraint", - &PEGTransformerFactory::InitializeUniqueConstraintTrampoline, - &PEGTransformerFactory::FinalizeUniqueConstraintTrampoline}; -static const TransformFrameOps PRIMARY_KEY_CONSTRAINT_OPS = { - "PrimaryKeyConstraint", &PEGTransformerFactory::InitializePrimaryKeyConstraintTrampoline, - &PEGTransformerFactory::FinalizePrimaryKeyConstraintTrampoline}; -static const TransformFrameOps CONSTRAINT_TIMING_OPS = {"ConstraintTiming", - &PEGTransformerFactory::InitializeConstraintTimingTrampoline, - &PEGTransformerFactory::FinalizeConstraintTimingTrampoline}; -static const TransformFrameOps IMMEDIATE_CONSTRAINT_OPS = { - "ImmediateConstraint", &PEGTransformerFactory::InitializeImmediateConstraintTrampoline, - &PEGTransformerFactory::FinalizeImmediateConstraintTrampoline}; -static const TransformFrameOps DEFERRED_CONSTRAINT_OPS = { - "DeferredConstraint", &PEGTransformerFactory::InitializeDeferredConstraintTrampoline, - &PEGTransformerFactory::FinalizeDeferredConstraintTrampoline}; -static const TransformFrameOps DEFAULT_VALUE_OPS = {"DefaultValue", - &PEGTransformerFactory::InitializeDefaultValueTrampoline, - &PEGTransformerFactory::FinalizeDefaultValueTrampoline}; -static const TransformFrameOps CHECK_CONSTRAINT_OPS = {"CheckConstraint", - &PEGTransformerFactory::InitializeCheckConstraintTrampoline, - &PEGTransformerFactory::FinalizeCheckConstraintTrampoline}; -static const TransformFrameOps FOREIGN_KEY_CONSTRAINT_OPS = { - "ForeignKeyConstraint", &PEGTransformerFactory::InitializeForeignKeyConstraintTrampoline, - &PEGTransformerFactory::FinalizeForeignKeyConstraintTrampoline}; -static const TransformFrameOps COLUMN_COLLATION_OPS = {"ColumnCollation", - &PEGTransformerFactory::InitializeColumnCollationTrampoline, - &PEGTransformerFactory::FinalizeColumnCollationTrampoline}; -static const TransformFrameOps COLUMN_COMPRESSION_OPS = {"ColumnCompression", - &PEGTransformerFactory::InitializeColumnCompressionTrampoline, - &PEGTransformerFactory::FinalizeColumnCompressionTrampoline}; -static const TransformFrameOps KEY_ACTIONS_OPS = {"KeyActions", &PEGTransformerFactory::InitializeKeyActionsTrampoline, - &PEGTransformerFactory::FinalizeKeyActionsTrampoline}; -static const TransformFrameOps UPDATE_FIRST_KEY_ACTIONS_OPS = { - "UpdateFirstKeyActions", &PEGTransformerFactory::InitializeUpdateFirstKeyActionsTrampoline, - &PEGTransformerFactory::FinalizeUpdateFirstKeyActionsTrampoline}; -static const TransformFrameOps DELETE_FIRST_KEY_ACTIONS_OPS = { - "DeleteFirstKeyActions", &PEGTransformerFactory::InitializeDeleteFirstKeyActionsTrampoline, - &PEGTransformerFactory::FinalizeDeleteFirstKeyActionsTrampoline}; -static const TransformFrameOps UPDATE_ACTION_OPS = {"UpdateAction", - &PEGTransformerFactory::InitializeUpdateActionTrampoline, - &PEGTransformerFactory::FinalizeUpdateActionTrampoline}; -static const TransformFrameOps DELETE_ACTION_OPS = {"DeleteAction", - &PEGTransformerFactory::InitializeDeleteActionTrampoline, - &PEGTransformerFactory::FinalizeDeleteActionTrampoline}; -static const TransformFrameOps KEY_ACTION_OPS = {"KeyAction", &PEGTransformerFactory::InitializeKeyActionTrampoline, - &PEGTransformerFactory::FinalizeKeyActionTrampoline}; -static const TransformFrameOps NO_KEY_ACTION_OPS = {"NoKeyAction", - &PEGTransformerFactory::InitializeNoKeyActionTrampoline, - &PEGTransformerFactory::FinalizeNoKeyActionTrampoline}; -static const TransformFrameOps RESTRICT_KEY_ACTION_OPS = {"RestrictKeyAction", - &PEGTransformerFactory::InitializeRestrictKeyActionTrampoline, - &PEGTransformerFactory::FinalizeRestrictKeyActionTrampoline}; -static const TransformFrameOps CASCADE_KEY_ACTION_OPS = {"CascadeKeyAction", - &PEGTransformerFactory::InitializeCascadeKeyActionTrampoline, - &PEGTransformerFactory::FinalizeCascadeKeyActionTrampoline}; -static const TransformFrameOps SET_NULL_KEY_ACTION_OPS = {"SetNullKeyAction", - &PEGTransformerFactory::InitializeSetNullKeyActionTrampoline, - &PEGTransformerFactory::FinalizeSetNullKeyActionTrampoline}; -static const TransformFrameOps SET_DEFAULT_KEY_ACTION_OPS = { - "SetDefaultKeyAction", &PEGTransformerFactory::InitializeSetDefaultKeyActionTrampoline, - &PEGTransformerFactory::FinalizeSetDefaultKeyActionTrampoline}; -static const TransformFrameOps TOP_LEVEL_CONSTRAINT_OPS = { - "TopLevelConstraint", &PEGTransformerFactory::InitializeTopLevelConstraintTrampoline, - &PEGTransformerFactory::FinalizeTopLevelConstraintTrampoline}; -static const TransformFrameOps TOP_LEVEL_CONSTRAINT_LIST_OPS = { - "TopLevelConstraintList", &PEGTransformerFactory::InitializeTopLevelConstraintListTrampoline, - &PEGTransformerFactory::FinalizeTopLevelConstraintListTrampoline}; -static const TransformFrameOps TOP_CHECK_CONSTRAINT_OPS = { - "TopCheckConstraint", &PEGTransformerFactory::InitializeTopCheckConstraintTrampoline, - &PEGTransformerFactory::FinalizeTopCheckConstraintTrampoline}; -static const TransformFrameOps TOP_PRIMARY_KEY_CONSTRAINT_OPS = { - "TopPrimaryKeyConstraint", &PEGTransformerFactory::InitializeTopPrimaryKeyConstraintTrampoline, - &PEGTransformerFactory::FinalizeTopPrimaryKeyConstraintTrampoline}; -static const TransformFrameOps TOP_UNIQUE_CONSTRAINT_OPS = { - "TopUniqueConstraint", &PEGTransformerFactory::InitializeTopUniqueConstraintTrampoline, - &PEGTransformerFactory::FinalizeTopUniqueConstraintTrampoline}; -static const TransformFrameOps TOP_FOREIGN_KEY_CONSTRAINT_OPS = { - "TopForeignKeyConstraint", &PEGTransformerFactory::InitializeTopForeignKeyConstraintTrampoline, - &PEGTransformerFactory::FinalizeTopForeignKeyConstraintTrampoline}; -static const TransformFrameOps COLUMN_ID_LIST_OPS = {"ColumnIdList", - &PEGTransformerFactory::InitializeColumnIdListTrampoline, - &PEGTransformerFactory::FinalizeColumnIdListTrampoline}; -static const TransformFrameOps DOTTED_IDENTIFIER_OPS = {"DottedIdentifier", - &PEGTransformerFactory::InitializeDottedIdentifierTrampoline, - &PEGTransformerFactory::FinalizeDottedIdentifierTrampoline}; -static const TransformFrameOps DOT_COL_LABEL_OPS = {"DotColLabel", - &PEGTransformerFactory::InitializeDotColLabelTrampoline, - &PEGTransformerFactory::FinalizeDotColLabelTrampoline}; -static const TransformFrameOps IDENTIFIER_OPS = {"Identifier", &PEGTransformerFactory::InitializeIdentifierTrampoline, - &PEGTransformerFactory::FinalizeIdentifierTrampoline}; -static const TransformFrameOps COL_ID_OPS = {"ColId", &PEGTransformerFactory::InitializeColIdTrampoline, - &PEGTransformerFactory::FinalizeColIdTrampoline}; -static const TransformFrameOps COL_ID_OR_STRING_OPS = {"ColIdOrString", - &PEGTransformerFactory::InitializeColIdOrStringTrampoline, - &PEGTransformerFactory::FinalizeColIdOrStringTrampoline}; -static const TransformFrameOps TYPE_FUNC_NAME_OPS = {"TypeFuncName", - &PEGTransformerFactory::InitializeTypeFuncNameTrampoline, - &PEGTransformerFactory::FinalizeTypeFuncNameTrampoline}; -static const TransformFrameOps TYPE_FUNC_KEYWORD_OPS = {"TypeFuncKeyword", - &PEGTransformerFactory::InitializeTypeFuncKeywordTrampoline, - &PEGTransformerFactory::FinalizeTypeFuncKeywordTrampoline}; -static const TransformFrameOps COL_LABEL_OPS = {"ColLabel", &PEGTransformerFactory::InitializeColLabelTrampoline, - &PEGTransformerFactory::FinalizeColLabelTrampoline}; -static const TransformFrameOps COL_LABEL_OR_STRING_OPS = {"ColLabelOrString", - &PEGTransformerFactory::InitializeColLabelOrStringTrampoline, - &PEGTransformerFactory::FinalizeColLabelOrStringTrampoline}; -static const TransformFrameOps COL_LABEL_IDENTIFIER_OPS = { - "ColLabelIdentifier", &PEGTransformerFactory::InitializeColLabelIdentifierTrampoline, - &PEGTransformerFactory::FinalizeColLabelIdentifierTrampoline}; -static const TransformFrameOps STRING_LITERAL_IDENTIFIER_OPS = { - "StringLiteralIdentifier", &PEGTransformerFactory::InitializeStringLiteralIdentifierTrampoline, - &PEGTransformerFactory::FinalizeStringLiteralIdentifierTrampoline}; -static const TransformFrameOps GENERATED_COLUMN_OPS = {"GeneratedColumn", - &PEGTransformerFactory::InitializeGeneratedColumnTrampoline, - &PEGTransformerFactory::FinalizeGeneratedColumnTrampoline}; -static const TransformFrameOps GENERATED_OPS = {"Generated", &PEGTransformerFactory::InitializeGeneratedTrampoline, - &PEGTransformerFactory::FinalizeGeneratedTrampoline}; -static const TransformFrameOps GENERATED_ALWAYS_OPS = {"GeneratedAlways", - &PEGTransformerFactory::InitializeGeneratedAlwaysTrampoline, - &PEGTransformerFactory::FinalizeGeneratedAlwaysTrampoline}; -static const TransformFrameOps GENERATED_BY_DEFAULT_OPS = { - "GeneratedByDefault", &PEGTransformerFactory::InitializeGeneratedByDefaultTrampoline, - &PEGTransformerFactory::FinalizeGeneratedByDefaultTrampoline}; -static const TransformFrameOps GENERATED_COLUMN_TYPE_OPS = { - "GeneratedColumnType", &PEGTransformerFactory::InitializeGeneratedColumnTypeTrampoline, - &PEGTransformerFactory::FinalizeGeneratedColumnTypeTrampoline}; -static const TransformFrameOps COMMIT_ACTION_OPS = {"CommitAction", - &PEGTransformerFactory::InitializeCommitActionTrampoline, - &PEGTransformerFactory::FinalizeCommitActionTrampoline}; -static const TransformFrameOps PRESERVE_OR_DELETE_OPS = {"PreserveOrDelete", - &PEGTransformerFactory::InitializePreserveOrDeleteTrampoline, - &PEGTransformerFactory::FinalizePreserveOrDeleteTrampoline}; -static const TransformFrameOps PRESERVE_ROWS_OPS = {"PreserveRows", - &PEGTransformerFactory::InitializePreserveRowsTrampoline, - &PEGTransformerFactory::FinalizePreserveRowsTrampoline}; -static const TransformFrameOps DELETE_ROWS_OPS = {"DeleteRows", &PEGTransformerFactory::InitializeDeleteRowsTrampoline, - &PEGTransformerFactory::FinalizeDeleteRowsTrampoline}; -static const TransformFrameOps VIRTUAL_GENERATED_COLUMN_OPS = { - "VirtualGeneratedColumn", &PEGTransformerFactory::InitializeVirtualGeneratedColumnTrampoline, - &PEGTransformerFactory::FinalizeVirtualGeneratedColumnTrampoline}; -static const TransformFrameOps STORED_GENERATED_COLUMN_OPS = { - "StoredGeneratedColumn", &PEGTransformerFactory::InitializeStoredGeneratedColumnTrampoline, - &PEGTransformerFactory::FinalizeStoredGeneratedColumnTrampoline}; -static const TransformFrameOps CREATE_TRIGGER_STMT_OPS = {"CreateTriggerStmt", - &PEGTransformerFactory::InitializeCreateTriggerStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateTriggerStmtTrampoline}; -static const TransformFrameOps TRIGGER_BODY_OPS = {"TriggerBody", - &PEGTransformerFactory::InitializeTriggerBodyTrampoline, - &PEGTransformerFactory::FinalizeTriggerBodyTrampoline}; -static const TransformFrameOps TRIGGER_NAME_OPS = {"TriggerName", - &PEGTransformerFactory::InitializeTriggerNameTrampoline, - &PEGTransformerFactory::FinalizeTriggerNameTrampoline}; -static const TransformFrameOps REFERENCING_CLAUSE_OPS = {"ReferencingClause", - &PEGTransformerFactory::InitializeReferencingClauseTrampoline, - &PEGTransformerFactory::FinalizeReferencingClauseTrampoline}; -static const TransformFrameOps REFERENCING_ITEM_OPS = {"ReferencingItem", - &PEGTransformerFactory::InitializeReferencingItemTrampoline, - &PEGTransformerFactory::FinalizeReferencingItemTrampoline}; -static const TransformFrameOps REFERENCING_NEW_TABLE_AS_OPS = { - "ReferencingNewTableAs", &PEGTransformerFactory::InitializeReferencingNewTableAsTrampoline, - &PEGTransformerFactory::FinalizeReferencingNewTableAsTrampoline}; -static const TransformFrameOps REFERENCING_OLD_TABLE_AS_OPS = { - "ReferencingOldTableAs", &PEGTransformerFactory::InitializeReferencingOldTableAsTrampoline, - &PEGTransformerFactory::FinalizeReferencingOldTableAsTrampoline}; -static const TransformFrameOps TRIGGER_TIMING_OPS = {"TriggerTiming", - &PEGTransformerFactory::InitializeTriggerTimingTrampoline, - &PEGTransformerFactory::FinalizeTriggerTimingTrampoline}; -static const TransformFrameOps TRIGGER_BEFORE_OPS = {"TriggerBefore", - &PEGTransformerFactory::InitializeTriggerBeforeTrampoline, - &PEGTransformerFactory::FinalizeTriggerBeforeTrampoline}; -static const TransformFrameOps TRIGGER_AFTER_OPS = {"TriggerAfter", - &PEGTransformerFactory::InitializeTriggerAfterTrampoline, - &PEGTransformerFactory::FinalizeTriggerAfterTrampoline}; -static const TransformFrameOps TRIGGER_INSTEAD_OF_OPS = {"TriggerInsteadOf", - &PEGTransformerFactory::InitializeTriggerInsteadOfTrampoline, - &PEGTransformerFactory::FinalizeTriggerInsteadOfTrampoline}; -static const TransformFrameOps TRIGGER_EVENT_OPS = {"TriggerEvent", - &PEGTransformerFactory::InitializeTriggerEventTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventTrampoline}; -static const TransformFrameOps TRIGGER_EVENT_INSERT_OPS = { - "TriggerEventInsert", &PEGTransformerFactory::InitializeTriggerEventInsertTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventInsertTrampoline}; -static const TransformFrameOps TRIGGER_EVENT_DELETE_OPS = { - "TriggerEventDelete", &PEGTransformerFactory::InitializeTriggerEventDeleteTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventDeleteTrampoline}; -static const TransformFrameOps TRIGGER_EVENT_UPDATE_OPS = { - "TriggerEventUpdate", &PEGTransformerFactory::InitializeTriggerEventUpdateTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventUpdateTrampoline}; -static const TransformFrameOps TRIGGER_EVENT_UPDATE_OF_OPS = { - "TriggerEventUpdateOf", &PEGTransformerFactory::InitializeTriggerEventUpdateOfTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventUpdateOfTrampoline}; -static const TransformFrameOps TRIGGER_COLUMN_LIST_OPS = {"TriggerColumnList", - &PEGTransformerFactory::InitializeTriggerColumnListTrampoline, - &PEGTransformerFactory::FinalizeTriggerColumnListTrampoline}; -static const TransformFrameOps FOR_EACH_CLAUSE_OPS = {"ForEachClause", - &PEGTransformerFactory::InitializeForEachClauseTrampoline, - &PEGTransformerFactory::FinalizeForEachClauseTrampoline}; -static const TransformFrameOps FOR_EACH_ROW_OPS = {"ForEachRow", &PEGTransformerFactory::InitializeForEachRowTrampoline, - &PEGTransformerFactory::FinalizeForEachRowTrampoline}; -static const TransformFrameOps FOR_EACH_STATEMENT_OPS = {"ForEachStatement", - &PEGTransformerFactory::InitializeForEachStatementTrampoline, - &PEGTransformerFactory::FinalizeForEachStatementTrampoline}; -static const TransformFrameOps CREATE_TYPE_STMT_OPS = {"CreateTypeStmt", - &PEGTransformerFactory::InitializeCreateTypeStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateTypeStmtTrampoline}; -static const TransformFrameOps CREATE_TYPE_OPS = {"CreateType", &PEGTransformerFactory::InitializeCreateTypeTrampoline, - &PEGTransformerFactory::FinalizeCreateTypeTrampoline}; -static const TransformFrameOps CREATE_TYPE_FROM_TYPE_OPS = { - "CreateTypeFromType", &PEGTransformerFactory::InitializeCreateTypeFromTypeTrampoline, - &PEGTransformerFactory::FinalizeCreateTypeFromTypeTrampoline}; -static const TransformFrameOps ENUM_SELECT_TYPE_OPS = {"EnumSelectType", - &PEGTransformerFactory::InitializeEnumSelectTypeTrampoline, - &PEGTransformerFactory::FinalizeEnumSelectTypeTrampoline}; -static const TransformFrameOps ENUM_STRING_LITERAL_LIST_OPS = { - "EnumStringLiteralList", &PEGTransformerFactory::InitializeEnumStringLiteralListTrampoline, - &PEGTransformerFactory::FinalizeEnumStringLiteralListTrampoline}; -static const TransformFrameOps CREATE_VIEW_STMT_OPS = {"CreateViewStmt", - &PEGTransformerFactory::InitializeCreateViewStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateViewStmtTrampoline}; -static const TransformFrameOps CREATE_RECURSIVE_OPS = {"CreateRecursive", - &PEGTransformerFactory::InitializeCreateRecursiveTrampoline, - &PEGTransformerFactory::FinalizeCreateRecursiveTrampoline}; -static const TransformFrameOps CREATE_SECURE_OPS = {"CreateSecure", - &PEGTransformerFactory::InitializeCreateSecureTrampoline, - &PEGTransformerFactory::FinalizeCreateSecureTrampoline}; -static const TransformFrameOps DEALLOCATE_STATEMENT_OPS = { - "DeallocateStatement", &PEGTransformerFactory::InitializeDeallocateStatementTrampoline, - &PEGTransformerFactory::FinalizeDeallocateStatementTrampoline}; -static const TransformFrameOps DEALLOCATE_PREPARE_OPS = {"DeallocatePrepare", - &PEGTransformerFactory::InitializeDeallocatePrepareTrampoline, - &PEGTransformerFactory::FinalizeDeallocatePrepareTrampoline}; -static const TransformFrameOps DELETE_STATEMENT_OPS = {"DeleteStatement", - &PEGTransformerFactory::InitializeDeleteStatementTrampoline, - &PEGTransformerFactory::FinalizeDeleteStatementTrampoline}; -static const TransformFrameOps TRUNCATE_STATEMENT_OPS = {"TruncateStatement", - &PEGTransformerFactory::InitializeTruncateStatementTrampoline, - &PEGTransformerFactory::FinalizeTruncateStatementTrampoline}; -static const TransformFrameOps TRUNCATE_OPTIONS_OPS = {"TruncateOptions", - &PEGTransformerFactory::InitializeTruncateOptionsTrampoline, - &PEGTransformerFactory::FinalizeTruncateOptionsTrampoline}; -static const TransformFrameOps TRUNCATE_ALIAS_OPTIONS_OPS = { - "TruncateAliasOptions", &PEGTransformerFactory::InitializeTruncateAliasOptionsTrampoline, - &PEGTransformerFactory::FinalizeTruncateAliasOptionsTrampoline}; -static const TransformFrameOps TRUNCATE_DROP_BEHAVIOR_OPS = { - "TruncateDropBehavior", &PEGTransformerFactory::InitializeTruncateDropBehaviorTrampoline, - &PEGTransformerFactory::FinalizeTruncateDropBehaviorTrampoline}; -static const TransformFrameOps TARGET_OPT_ALIAS_OPS = {"TargetOptAlias", - &PEGTransformerFactory::InitializeTargetOptAliasTrampoline, - &PEGTransformerFactory::FinalizeTargetOptAliasTrampoline}; -static const TransformFrameOps TARGET_ALIAS_OPS = {"TargetAlias", - &PEGTransformerFactory::InitializeTargetAliasTrampoline, - &PEGTransformerFactory::FinalizeTargetAliasTrampoline}; -static const TransformFrameOps DELETE_USING_CLAUSE_OPS = {"DeleteUsingClause", - &PEGTransformerFactory::InitializeDeleteUsingClauseTrampoline, - &PEGTransformerFactory::FinalizeDeleteUsingClauseTrampoline}; -static const TransformFrameOps DESCRIBE_STATEMENT_OPS = {"DescribeStatement", - &PEGTransformerFactory::InitializeDescribeStatementTrampoline, - &PEGTransformerFactory::FinalizeDescribeStatementTrampoline}; -static const TransformFrameOps SHOW_DEPRECATED_SELECT_OPS = { - "ShowDeprecatedSelect", &PEGTransformerFactory::InitializeShowDeprecatedSelectTrampoline, - &PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline}; -static const TransformFrameOps DESCRIBE_SELECT_OPS = {"DescribeSelect", - &PEGTransformerFactory::InitializeDescribeSelectTrampoline, - &PEGTransformerFactory::FinalizeDescribeSelectTrampoline}; -static const TransformFrameOps SHOW_ALL_TABLES_OPS = {"ShowAllTables", - &PEGTransformerFactory::InitializeShowAllTablesTrampoline, - &PEGTransformerFactory::FinalizeShowAllTablesTrampoline}; -static const TransformFrameOps SHOW_TABLES_OPS = {"ShowTables", &PEGTransformerFactory::InitializeShowTablesTrampoline, - &PEGTransformerFactory::FinalizeShowTablesTrampoline}; -static const TransformFrameOps SHOW_BY_NAME_OPS = {"ShowByName", &PEGTransformerFactory::InitializeShowByNameTrampoline, - &PEGTransformerFactory::FinalizeShowByNameTrampoline}; -static const TransformFrameOps DESCRIBE_BY_NAME_OPS = {"DescribeByName", - &PEGTransformerFactory::InitializeDescribeByNameTrampoline, - &PEGTransformerFactory::FinalizeDescribeByNameTrampoline}; -static const TransformFrameOps DESCRIBE_OR_SUMMARIZE_OPS = { - "DescribeOrSummarize", &PEGTransformerFactory::InitializeDescribeOrSummarizeTrampoline, - &PEGTransformerFactory::FinalizeDescribeOrSummarizeTrampoline}; -static const TransformFrameOps SHOW_TARGET_OPS = {"ShowTarget", &PEGTransformerFactory::InitializeShowTargetTrampoline, - &PEGTransformerFactory::FinalizeShowTargetTrampoline}; -static const TransformFrameOps SHOW_DEPRECATED_QUALIFIED_TABLE_NAME_OPS = { - "ShowDeprecatedQualifiedTableName", &PEGTransformerFactory::InitializeShowDeprecatedQualifiedTableNameTrampoline, - &PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline}; -static const TransformFrameOps SHOW_SETTING_NAME_OPS = {"ShowSettingName", - &PEGTransformerFactory::InitializeShowSettingNameTrampoline, - &PEGTransformerFactory::FinalizeShowSettingNameTrampoline}; -static const TransformFrameOps DESCRIBE_TARGET_OPS = {"DescribeTarget", - &PEGTransformerFactory::InitializeDescribeTargetTrampoline, - &PEGTransformerFactory::FinalizeDescribeTargetTrampoline}; -static const TransformFrameOps DESCRIBE_BASE_TABLE_NAME_OPS = { - "DescribeBaseTableName", &PEGTransformerFactory::InitializeDescribeBaseTableNameTrampoline, - &PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline}; -static const TransformFrameOps DESCRIBE_STRING_LITERAL_OPS = { - "DescribeStringLiteral", &PEGTransformerFactory::InitializeDescribeStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline}; -static const TransformFrameOps SUMMARIZE_OPS = {"Summarize", &PEGTransformerFactory::InitializeSummarizeTrampoline, - &PEGTransformerFactory::FinalizeSummarizeTrampoline}; -static const TransformFrameOps SUMMARIZE_RULE_OPS = {"SummarizeRule", - &PEGTransformerFactory::InitializeSummarizeRuleTrampoline, - &PEGTransformerFactory::FinalizeSummarizeRuleTrampoline}; -static const TransformFrameOps SHOW_OR_DESCRIBE_OPS = {"ShowOrDescribe", - &PEGTransformerFactory::InitializeShowOrDescribeTrampoline, - &PEGTransformerFactory::FinalizeShowOrDescribeTrampoline}; -static const TransformFrameOps SHOW_RULE_OPS = {"ShowRule", &PEGTransformerFactory::InitializeShowRuleTrampoline, - &PEGTransformerFactory::FinalizeShowRuleTrampoline}; -static const TransformFrameOps DESCRIBE_RULE_OPS = {"DescribeRule", - &PEGTransformerFactory::InitializeDescribeRuleTrampoline, - &PEGTransformerFactory::FinalizeDescribeRuleTrampoline}; -static const TransformFrameOps DESCRIBE_LONG_RULE_OPS = {"DescribeLongRule", - &PEGTransformerFactory::InitializeDescribeLongRuleTrampoline, - &PEGTransformerFactory::FinalizeDescribeLongRuleTrampoline}; -static const TransformFrameOps DESC_RULE_OPS = {"DescRule", &PEGTransformerFactory::InitializeDescRuleTrampoline, - &PEGTransformerFactory::FinalizeDescRuleTrampoline}; -static const TransformFrameOps DETACH_STATEMENT_OPS = {"DetachStatement", - &PEGTransformerFactory::InitializeDetachStatementTrampoline, - &PEGTransformerFactory::FinalizeDetachStatementTrampoline}; -static const TransformFrameOps DROP_STATEMENT_OPS = {"DropStatement", - &PEGTransformerFactory::InitializeDropStatementTrampoline, - &PEGTransformerFactory::FinalizeDropStatementTrampoline}; -static const TransformFrameOps DROP_ENTRIES_OPS = {"DropEntries", - &PEGTransformerFactory::InitializeDropEntriesTrampoline, - &PEGTransformerFactory::FinalizeDropEntriesTrampoline}; -static const TransformFrameOps DROP_TRIGGER_OPS = {"DropTrigger", - &PEGTransformerFactory::InitializeDropTriggerTrampoline, - &PEGTransformerFactory::FinalizeDropTriggerTrampoline}; -static const TransformFrameOps DROP_TABLE_OPS = {"DropTable", &PEGTransformerFactory::InitializeDropTableTrampoline, - &PEGTransformerFactory::FinalizeDropTableTrampoline}; -static const TransformFrameOps DROP_TABLE_FUNCTION_OPS = {"DropTableFunction", - &PEGTransformerFactory::InitializeDropTableFunctionTrampoline, - &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline}; -static const TransformFrameOps DROP_FUNCTION_OPS = {"DropFunction", - &PEGTransformerFactory::InitializeDropFunctionTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionTrampoline}; -static const TransformFrameOps DROP_SCHEMA_OPS = {"DropSchema", &PEGTransformerFactory::InitializeDropSchemaTrampoline, - &PEGTransformerFactory::FinalizeDropSchemaTrampoline}; -static const TransformFrameOps DROP_INDEX_OPS = {"DropIndex", &PEGTransformerFactory::InitializeDropIndexTrampoline, - &PEGTransformerFactory::FinalizeDropIndexTrampoline}; -static const TransformFrameOps QUALIFIED_INDEX_NAME_OPS = { - "QualifiedIndexName", &PEGTransformerFactory::InitializeQualifiedIndexNameTrampoline, - &PEGTransformerFactory::FinalizeQualifiedIndexNameTrampoline}; -static const TransformFrameOps QUALIFIED_INDEX_NAME_STRING_OPS = { - "QualifiedIndexNameString", &PEGTransformerFactory::InitializeQualifiedIndexNameStringTrampoline, - &PEGTransformerFactory::FinalizeQualifiedIndexNameStringTrampoline}; -static const TransformFrameOps SCHEMA_RESERVED_INDEX_OPS = { - "SchemaReservedIndex", &PEGTransformerFactory::InitializeSchemaReservedIndexTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline}; -static const TransformFrameOps CATALOG_RESERVED_SCHEMA_INDEX_OPS = { - "CatalogReservedSchemaIndex", &PEGTransformerFactory::InitializeCatalogReservedSchemaIndexTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline}; -static const TransformFrameOps DROP_SEQUENCE_OPS = {"DropSequence", - &PEGTransformerFactory::InitializeDropSequenceTrampoline, - &PEGTransformerFactory::FinalizeDropSequenceTrampoline}; -static const TransformFrameOps DROP_COLLATION_OPS = {"DropCollation", - &PEGTransformerFactory::InitializeDropCollationTrampoline, - &PEGTransformerFactory::FinalizeDropCollationTrampoline}; -static const TransformFrameOps DROP_TYPE_OPS = {"DropType", &PEGTransformerFactory::InitializeDropTypeTrampoline, - &PEGTransformerFactory::FinalizeDropTypeTrampoline}; -static const TransformFrameOps DROP_SECRET_OPS = {"DropSecret", &PEGTransformerFactory::InitializeDropSecretTrampoline, - &PEGTransformerFactory::FinalizeDropSecretTrampoline}; -static const TransformFrameOps TABLE_OR_VIEW_OPS = {"TableOrView", - &PEGTransformerFactory::InitializeTableOrViewTrampoline, - &PEGTransformerFactory::FinalizeTableOrViewTrampoline}; -static const TransformFrameOps MATERIALIZED_VIEW_ENTRY_OPS = { - "MaterializedViewEntry", &PEGTransformerFactory::InitializeMaterializedViewEntryTrampoline, - &PEGTransformerFactory::FinalizeMaterializedViewEntryTrampoline}; -static const TransformFrameOps FUNCTION_TYPE_MACRO_OPS = {"FunctionTypeMacro", - &PEGTransformerFactory::InitializeFunctionTypeMacroTrampoline, - &PEGTransformerFactory::FinalizeFunctionTypeMacroTrampoline}; -static const TransformFrameOps FUNCTION_TYPE_MACRO_KEYWORD_OPS = { - "FunctionTypeMacroKeyword", &PEGTransformerFactory::InitializeFunctionTypeMacroKeywordTrampoline, - &PEGTransformerFactory::FinalizeFunctionTypeMacroKeywordTrampoline}; -static const TransformFrameOps FUNCTION_TYPE_FUNCTION_OPS = { - "FunctionTypeFunction", &PEGTransformerFactory::InitializeFunctionTypeFunctionTrampoline, - &PEGTransformerFactory::FinalizeFunctionTypeFunctionTrampoline}; -static const TransformFrameOps DROP_BEHAVIOR_OPS = {"DropBehavior", - &PEGTransformerFactory::InitializeDropBehaviorTrampoline, - &PEGTransformerFactory::FinalizeDropBehaviorTrampoline}; -static const TransformFrameOps CASCADE_DROP_BEHAVIOR_OPS = { - "CascadeDropBehavior", &PEGTransformerFactory::InitializeCascadeDropBehaviorTrampoline, - &PEGTransformerFactory::FinalizeCascadeDropBehaviorTrampoline}; -static const TransformFrameOps RESTRICT_DROP_BEHAVIOR_OPS = { - "RestrictDropBehavior", &PEGTransformerFactory::InitializeRestrictDropBehaviorTrampoline, - &PEGTransformerFactory::FinalizeRestrictDropBehaviorTrampoline}; -static const TransformFrameOps IF_EXISTS_OPS = {"IfExists", &PEGTransformerFactory::InitializeIfExistsTrampoline, - &PEGTransformerFactory::FinalizeIfExistsTrampoline}; -static const TransformFrameOps DROP_SECRET_STORAGE_OPS = {"DropSecretStorage", - &PEGTransformerFactory::InitializeDropSecretStorageTrampoline, - &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline}; -static const TransformFrameOps EXECUTE_STATEMENT_OPS = {"ExecuteStatement", - &PEGTransformerFactory::InitializeExecuteStatementTrampoline, - &PEGTransformerFactory::FinalizeExecuteStatementTrampoline}; -static const TransformFrameOps EXPLAIN_STATEMENT_OPS = {"ExplainStatement", - &PEGTransformerFactory::InitializeExplainStatementTrampoline, - &PEGTransformerFactory::FinalizeExplainStatementTrampoline}; -static const TransformFrameOps EXPLAIN_OPTION_LIST_OPS = {"ExplainOptionList", - &PEGTransformerFactory::InitializeExplainOptionListTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionListTrampoline}; -static const TransformFrameOps EXPLAIN_OPTION_OPS = {"ExplainOption", - &PEGTransformerFactory::InitializeExplainOptionTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionTrampoline}; -static const TransformFrameOps EXPLAIN_OPTION_NAME_OPS = {"ExplainOptionName", - &PEGTransformerFactory::InitializeExplainOptionNameTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline}; -static const TransformFrameOps EXPLAIN_SELECT_STATEMENT_OPS = { - "ExplainSelectStatement", &PEGTransformerFactory::InitializeExplainSelectStatementTrampoline, - &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline}; -static const TransformFrameOps EXPLAINABLE_STATEMENTS_OPS = { - "ExplainableStatements", &PEGTransformerFactory::InitializeExplainableStatementsTrampoline, - &PEGTransformerFactory::FinalizeExplainableStatementsTrampoline}; -static const TransformFrameOps EXPORT_STATEMENT_OPS = {"ExportStatement", - &PEGTransformerFactory::InitializeExportStatementTrampoline, - &PEGTransformerFactory::FinalizeExportStatementTrampoline}; -static const TransformFrameOps EXPORT_SOURCE_OPS = {"ExportSource", - &PEGTransformerFactory::InitializeExportSourceTrampoline, - &PEGTransformerFactory::FinalizeExportSourceTrampoline}; -static const TransformFrameOps EXPORT_OPTIONS_OPS = {"ExportOptions", - &PEGTransformerFactory::InitializeExportOptionsTrampoline, - &PEGTransformerFactory::FinalizeExportOptionsTrampoline}; -static const TransformFrameOps IMPORT_STATEMENT_OPS = {"ImportStatement", - &PEGTransformerFactory::InitializeImportStatementTrampoline, - &PEGTransformerFactory::FinalizeImportStatementTrampoline}; -static const TransformFrameOps COLUMN_REFERENCE_OPS = {"ColumnReference", - &PEGTransformerFactory::InitializeColumnReferenceTrampoline, - &PEGTransformerFactory::FinalizeColumnReferenceTrampoline}; -static const TransformFrameOps NESTED_SCHEMA_TABLE_COLUMN_NAME_OPS = { - "NestedSchemaTableColumnName", &PEGTransformerFactory::InitializeNestedSchemaTableColumnNameTrampoline, - &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline}; -static const TransformFrameOps CATALOG_RESERVED_SCHEMA_TABLE_COLUMN_NAME_OPS = { - "CatalogReservedSchemaTableColumnName", - &PEGTransformerFactory::InitializeCatalogReservedSchemaTableColumnNameTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline}; -static const TransformFrameOps SCHEMA_RESERVED_TABLE_COLUMN_NAME_OPS = { - "SchemaReservedTableColumnName", &PEGTransformerFactory::InitializeSchemaReservedTableColumnNameTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline}; -static const TransformFrameOps TABLE_RESERVED_COLUMN_NAME_OPS = { - "TableReservedColumnName", &PEGTransformerFactory::InitializeTableReservedColumnNameTrampoline, - &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline}; -static const TransformFrameOps FUNCTION_EXPRESSION_OPS = { - "FunctionExpression", &PEGTransformerFactory::InitializeFunctionExpressionTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline}; -static const TransformFrameOps FUNCTION_EXPRESSION_ARGUMENTS_OPS = { - "FunctionExpressionArguments", &PEGTransformerFactory::InitializeFunctionExpressionArgumentsTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline}; -static const TransformFrameOps FUNCTION_EXPRESSION_ARGUMENT_LIST_OPS = { - "FunctionExpressionArgumentList", &PEGTransformerFactory::InitializeFunctionExpressionArgumentListTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline}; -static const TransformFrameOps FUNCTION_ARGUMENT_LIST_OPS = { - "FunctionArgumentList", &PEGTransformerFactory::InitializeFunctionArgumentListTrampoline, - &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline}; -static const TransformFrameOps FUNCTION_IDENTIFIER_OPS = { - "FunctionIdentifier", &PEGTransformerFactory::InitializeFunctionIdentifierTrampoline, - &PEGTransformerFactory::FinalizeFunctionIdentifierTrampoline}; -static const TransformFrameOps FUNCTION_NAME_AS_QUALIFIED_NAME_OPS = { - "FunctionNameAsQualifiedName", &PEGTransformerFactory::InitializeFunctionNameAsQualifiedNameTrampoline, - &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline}; -static const TransformFrameOps CATALOG_RESERVED_SCHEMA_FUNCTION_NAME_OPS = { - "CatalogReservedSchemaFunctionName", &PEGTransformerFactory::InitializeCatalogReservedSchemaFunctionNameTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline}; -static const TransformFrameOps SCHEMA_RESERVED_FUNCTION_NAME_OPS = { - "SchemaReservedFunctionName", &PEGTransformerFactory::InitializeSchemaReservedFunctionNameTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline}; -static const TransformFrameOps DISTINCT_OR_ALL_OPS = {"DistinctOrAll", - &PEGTransformerFactory::InitializeDistinctOrAllTrampoline, - &PEGTransformerFactory::FinalizeDistinctOrAllTrampoline}; -static const TransformFrameOps DISTINCT_KEYWORD_OPS = {"DistinctKeyword", - &PEGTransformerFactory::InitializeDistinctKeywordTrampoline, - &PEGTransformerFactory::FinalizeDistinctKeywordTrampoline}; -static const TransformFrameOps ALL_KEYWORD_OPS = {"AllKeyword", &PEGTransformerFactory::InitializeAllKeywordTrampoline, - &PEGTransformerFactory::FinalizeAllKeywordTrampoline}; -static const TransformFrameOps WITHIN_GROUP_CLAUSE_OPS = {"WithinGroupClause", - &PEGTransformerFactory::InitializeWithinGroupClauseTrampoline, - &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline}; -static const TransformFrameOps FILTER_CLAUSE_OPS = {"FilterClause", - &PEGTransformerFactory::InitializeFilterClauseTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseTrampoline}; -static const TransformFrameOps FILTER_CLAUSE_EXPRESSION_OPS = { - "FilterClauseExpression", &PEGTransformerFactory::InitializeFilterClauseExpressionTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline}; -static const TransformFrameOps FILTER_CLAUSE_CONTENTS_OPS = { - "FilterClauseContents", &PEGTransformerFactory::InitializeFilterClauseContentsTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline}; -static const TransformFrameOps IGNORE_OR_RESPECT_NULLS_OPS = { - "IgnoreOrRespectNulls", &PEGTransformerFactory::InitializeIgnoreOrRespectNullsTrampoline, - &PEGTransformerFactory::FinalizeIgnoreOrRespectNullsTrampoline}; -static const TransformFrameOps IGNORE_NULLS_OPS = {"IgnoreNulls", - &PEGTransformerFactory::InitializeIgnoreNullsTrampoline, - &PEGTransformerFactory::FinalizeIgnoreNullsTrampoline}; -static const TransformFrameOps RESPECT_NULLS_OPS = {"RespectNulls", - &PEGTransformerFactory::InitializeRespectNullsTrampoline, - &PEGTransformerFactory::FinalizeRespectNullsTrampoline}; -static const TransformFrameOps PARENTHESIS_EXPRESSION_OPS = { - "ParenthesisExpression", &PEGTransformerFactory::InitializeParenthesisExpressionTrampoline, - &PEGTransformerFactory::FinalizeParenthesisExpressionTrampoline}; -static const TransformFrameOps LITERAL_EXPRESSION_OPS = {"LiteralExpression", - &PEGTransformerFactory::InitializeLiteralExpressionTrampoline, - &PEGTransformerFactory::FinalizeLiteralExpressionTrampoline}; -static const TransformFrameOps CONSTANT_LITERAL_OPS = {"ConstantLiteral", - &PEGTransformerFactory::InitializeConstantLiteralTrampoline, - &PEGTransformerFactory::FinalizeConstantLiteralTrampoline}; -static const TransformFrameOps NULL_LITERAL_OPS = {"NullLiteral", - &PEGTransformerFactory::InitializeNullLiteralTrampoline, - &PEGTransformerFactory::FinalizeNullLiteralTrampoline}; -static const TransformFrameOps TRUE_LITERAL_OPS = {"TrueLiteral", - &PEGTransformerFactory::InitializeTrueLiteralTrampoline, - &PEGTransformerFactory::FinalizeTrueLiteralTrampoline}; -static const TransformFrameOps FALSE_LITERAL_OPS = {"FalseLiteral", - &PEGTransformerFactory::InitializeFalseLiteralTrampoline, - &PEGTransformerFactory::FinalizeFalseLiteralTrampoline}; -static const TransformFrameOps CAST_EXPRESSION_OPS = {"CastExpression", - &PEGTransformerFactory::InitializeCastExpressionTrampoline, - &PEGTransformerFactory::FinalizeCastExpressionTrampoline}; -static const TransformFrameOps CAST_ARGUMENTS_OPS = {"CastArguments", - &PEGTransformerFactory::InitializeCastArgumentsTrampoline, - &PEGTransformerFactory::FinalizeCastArgumentsTrampoline}; -static const TransformFrameOps CAST_OR_TRY_CAST_OPS = {"CastOrTryCast", - &PEGTransformerFactory::InitializeCastOrTryCastTrampoline, - &PEGTransformerFactory::FinalizeCastOrTryCastTrampoline}; -static const TransformFrameOps CAST_KEYWORD_OPS = {"CastKeyword", - &PEGTransformerFactory::InitializeCastKeywordTrampoline, - &PEGTransformerFactory::FinalizeCastKeywordTrampoline}; -static const TransformFrameOps TRY_CAST_KEYWORD_OPS = {"TryCastKeyword", - &PEGTransformerFactory::InitializeTryCastKeywordTrampoline, - &PEGTransformerFactory::FinalizeTryCastKeywordTrampoline}; -static const TransformFrameOps COL_ID_DOT_OPS = {"ColIdDot", &PEGTransformerFactory::InitializeColIdDotTrampoline, - &PEGTransformerFactory::FinalizeColIdDotTrampoline}; -static const TransformFrameOps STAR_EXPRESSION_OPS = {"StarExpression", - &PEGTransformerFactory::InitializeStarExpressionTrampoline, - &PEGTransformerFactory::FinalizeStarExpressionTrampoline}; -static const TransformFrameOps STAR_QUALIFIER_LIST_OPS = {"StarQualifierList", - &PEGTransformerFactory::InitializeStarQualifierListTrampoline, - &PEGTransformerFactory::FinalizeStarQualifierListTrampoline}; -static const TransformFrameOps EXCLUDE_LIST_OPS = {"ExcludeList", - &PEGTransformerFactory::InitializeExcludeListTrampoline, - &PEGTransformerFactory::FinalizeExcludeListTrampoline}; -static const TransformFrameOps EXCLUDE_NAMES_OPS = {"ExcludeNames", - &PEGTransformerFactory::InitializeExcludeNamesTrampoline, - &PEGTransformerFactory::FinalizeExcludeNamesTrampoline}; -static const TransformFrameOps EXCLUDE_NAME_LIST_OPS = {"ExcludeNameList", - &PEGTransformerFactory::InitializeExcludeNameListTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameListTrampoline}; -static const TransformFrameOps EXCLUDE_NAME_SINGLE_OPS = {"ExcludeNameSingle", - &PEGTransformerFactory::InitializeExcludeNameSingleTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline}; -static const TransformFrameOps EXCLUDE_NAME_OPS = {"ExcludeName", - &PEGTransformerFactory::InitializeExcludeNameTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameTrampoline}; -static const TransformFrameOps EXCLUDE_DOTTED_NAME_OPS = {"ExcludeDottedName", - &PEGTransformerFactory::InitializeExcludeDottedNameTrampoline, - &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline}; -static const TransformFrameOps EXCLUDE_COLUMN_NAME_OPS = {"ExcludeColumnName", - &PEGTransformerFactory::InitializeExcludeColumnNameTrampoline, - &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline}; -static const TransformFrameOps REPLACE_LIST_OPS = {"ReplaceList", - &PEGTransformerFactory::InitializeReplaceListTrampoline, - &PEGTransformerFactory::FinalizeReplaceListTrampoline}; -static const TransformFrameOps REPLACE_ENTRIES_OPS = {"ReplaceEntries", - &PEGTransformerFactory::InitializeReplaceEntriesTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntriesTrampoline}; -static const TransformFrameOps REPLACE_ENTRY_SINGLE_OPS = { - "ReplaceEntrySingle", &PEGTransformerFactory::InitializeReplaceEntrySingleTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline}; -static const TransformFrameOps REPLACE_ENTRY_LIST_OPS = {"ReplaceEntryList", - &PEGTransformerFactory::InitializeReplaceEntryListTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline}; -static const TransformFrameOps REPLACE_ENTRY_OPS = {"ReplaceEntry", - &PEGTransformerFactory::InitializeReplaceEntryTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryTrampoline}; -static const TransformFrameOps RENAME_LIST_OPS = {"RenameList", &PEGTransformerFactory::InitializeRenameListTrampoline, - &PEGTransformerFactory::FinalizeRenameListTrampoline}; -static const TransformFrameOps RENAME_ENTRIES_OPS = {"RenameEntries", - &PEGTransformerFactory::InitializeRenameEntriesTrampoline, - &PEGTransformerFactory::FinalizeRenameEntriesTrampoline}; -static const TransformFrameOps RENAME_ENTRY_LIST_OPS = {"RenameEntryList", - &PEGTransformerFactory::InitializeRenameEntryListTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryListTrampoline}; -static const TransformFrameOps SINGLE_RENAME_ENTRY_OPS = {"SingleRenameEntry", - &PEGTransformerFactory::InitializeSingleRenameEntryTrampoline, - &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline}; -static const TransformFrameOps RENAME_ENTRY_OPS = {"RenameEntry", - &PEGTransformerFactory::InitializeRenameEntryTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryTrampoline}; -static const TransformFrameOps SUBQUERY_EXPRESSION_OPS = { - "SubqueryExpression", &PEGTransformerFactory::InitializeSubqueryExpressionTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline}; -static const TransformFrameOps SUBQUERY_NOT_OPS = {"SubqueryNot", - &PEGTransformerFactory::InitializeSubqueryNotTrampoline, - &PEGTransformerFactory::FinalizeSubqueryNotTrampoline}; -static const TransformFrameOps SUBQUERY_EXISTS_OPS = {"SubqueryExists", - &PEGTransformerFactory::InitializeSubqueryExistsTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExistsTrampoline}; -static const TransformFrameOps CASE_EXPRESSION_OPS = {"CaseExpression", - &PEGTransformerFactory::InitializeCaseExpressionTrampoline, - &PEGTransformerFactory::FinalizeCaseExpressionTrampoline}; -static const TransformFrameOps CASE_WHEN_THEN_OPS = {"CaseWhenThen", - &PEGTransformerFactory::InitializeCaseWhenThenTrampoline, - &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline}; -static const TransformFrameOps CASE_ELSE_OPS = {"CaseElse", &PEGTransformerFactory::InitializeCaseElseTrampoline, - &PEGTransformerFactory::FinalizeCaseElseTrampoline}; -static const TransformFrameOps TYPE_LITERAL_OPS = {"TypeLiteral", - &PEGTransformerFactory::InitializeTypeLiteralTrampoline, - &PEGTransformerFactory::FinalizeTypeLiteralTrampoline}; -static const TransformFrameOps INTERVAL_LITERAL_OPS = {"IntervalLiteral", - &PEGTransformerFactory::InitializeIntervalLiteralTrampoline, - &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline}; -static const TransformFrameOps INTERVAL_PARAMETER_OPS = {"IntervalParameter", - &PEGTransformerFactory::InitializeIntervalParameterTrampoline, - &PEGTransformerFactory::FinalizeIntervalParameterTrampoline}; -static const TransformFrameOps INTERVAL_STRING_PARAMETER_OPS = { - "IntervalStringParameter", &PEGTransformerFactory::InitializeIntervalStringParameterTrampoline, - &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline}; -static const TransformFrameOps FRAME_CLAUSE_OPS = {"FrameClause", - &PEGTransformerFactory::InitializeFrameClauseTrampoline, - &PEGTransformerFactory::FinalizeFrameClauseTrampoline}; -static const TransformFrameOps FRAMING_OPS = {"Framing", &PEGTransformerFactory::InitializeFramingTrampoline, - &PEGTransformerFactory::FinalizeFramingTrampoline}; -static const TransformFrameOps ROWS_FRAMING_OPS = {"RowsFraming", - &PEGTransformerFactory::InitializeRowsFramingTrampoline, - &PEGTransformerFactory::FinalizeRowsFramingTrampoline}; -static const TransformFrameOps RANGE_FRAMING_OPS = {"RangeFraming", - &PEGTransformerFactory::InitializeRangeFramingTrampoline, - &PEGTransformerFactory::FinalizeRangeFramingTrampoline}; -static const TransformFrameOps GROUPS_FRAMING_OPS = {"GroupsFraming", - &PEGTransformerFactory::InitializeGroupsFramingTrampoline, - &PEGTransformerFactory::FinalizeGroupsFramingTrampoline}; -static const TransformFrameOps FRAME_EXTENT_OPS = {"FrameExtent", - &PEGTransformerFactory::InitializeFrameExtentTrampoline, - &PEGTransformerFactory::FinalizeFrameExtentTrampoline}; -static const TransformFrameOps SINGLE_FRAME_EXTENT_OPS = {"SingleFrameExtent", - &PEGTransformerFactory::InitializeSingleFrameExtentTrampoline, - &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline}; -static const TransformFrameOps BETWEEN_FRAME_EXTENT_OPS = { - "BetweenFrameExtent", &PEGTransformerFactory::InitializeBetweenFrameExtentTrampoline, - &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline}; -static const TransformFrameOps FRAME_BOUND_OPS = {"FrameBound", &PEGTransformerFactory::InitializeFrameBoundTrampoline, - &PEGTransformerFactory::FinalizeFrameBoundTrampoline}; -static const TransformFrameOps FRAME_UNBOUNDED_OPS = {"FrameUnbounded", - &PEGTransformerFactory::InitializeFrameUnboundedTrampoline, - &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline}; -static const TransformFrameOps FRAME_EXPRESSION_OPS = {"FrameExpression", - &PEGTransformerFactory::InitializeFrameExpressionTrampoline, - &PEGTransformerFactory::FinalizeFrameExpressionTrampoline}; -static const TransformFrameOps FRAME_CURRENT_ROW_OPS = {"FrameCurrentRow", - &PEGTransformerFactory::InitializeFrameCurrentRowTrampoline, - &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline}; -static const TransformFrameOps PRECEDING_OR_FOLLOWING_OPS = { - "PrecedingOrFollowing", &PEGTransformerFactory::InitializePrecedingOrFollowingTrampoline, - &PEGTransformerFactory::FinalizePrecedingOrFollowingTrampoline}; -static const TransformFrameOps PRECEDING_FRAME_OPS = {"PrecedingFrame", - &PEGTransformerFactory::InitializePrecedingFrameTrampoline, - &PEGTransformerFactory::FinalizePrecedingFrameTrampoline}; -static const TransformFrameOps FOLLOWING_FRAME_OPS = {"FollowingFrame", - &PEGTransformerFactory::InitializeFollowingFrameTrampoline, - &PEGTransformerFactory::FinalizeFollowingFrameTrampoline}; -static const TransformFrameOps WINDOW_EXCLUDE_CLAUSE_OPS = { - "WindowExcludeClause", &PEGTransformerFactory::InitializeWindowExcludeClauseTrampoline, - &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline}; -static const TransformFrameOps WINDOW_EXCLUDE_ELEMENT_OPS = { - "WindowExcludeElement", &PEGTransformerFactory::InitializeWindowExcludeElementTrampoline, - &PEGTransformerFactory::FinalizeWindowExcludeElementTrampoline}; -static const TransformFrameOps EXCLUDE_CURRENT_ROW_OPS = {"ExcludeCurrentRow", - &PEGTransformerFactory::InitializeExcludeCurrentRowTrampoline, - &PEGTransformerFactory::FinalizeExcludeCurrentRowTrampoline}; -static const TransformFrameOps EXCLUDE_GROUP_OPS = {"ExcludeGroup", - &PEGTransformerFactory::InitializeExcludeGroupTrampoline, - &PEGTransformerFactory::FinalizeExcludeGroupTrampoline}; -static const TransformFrameOps EXCLUDE_TIES_OPS = {"ExcludeTies", - &PEGTransformerFactory::InitializeExcludeTiesTrampoline, - &PEGTransformerFactory::FinalizeExcludeTiesTrampoline}; -static const TransformFrameOps EXCLUDE_NO_OTHERS_OPS = {"ExcludeNoOthers", - &PEGTransformerFactory::InitializeExcludeNoOthersTrampoline, - &PEGTransformerFactory::FinalizeExcludeNoOthersTrampoline}; -static const TransformFrameOps OVER_CLAUSE_OPS = {"OverClause", &PEGTransformerFactory::InitializeOverClauseTrampoline, - &PEGTransformerFactory::FinalizeOverClauseTrampoline}; -static const TransformFrameOps WINDOW_FRAME_OPS = {"WindowFrame", - &PEGTransformerFactory::InitializeWindowFrameTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameTrampoline}; -static const TransformFrameOps IDENTIFIER_WINDOW_FRAME_OPS = { - "IdentifierWindowFrame", &PEGTransformerFactory::InitializeIdentifierWindowFrameTrampoline, - &PEGTransformerFactory::FinalizeIdentifierWindowFrameTrampoline}; -static const TransformFrameOps PARENS_IDENTIFIER_OPS = {"ParensIdentifier", - &PEGTransformerFactory::InitializeParensIdentifierTrampoline, - &PEGTransformerFactory::FinalizeParensIdentifierTrampoline}; -static const TransformFrameOps WINDOW_FRAME_DEFINITION_OPS = { - "WindowFrameDefinition", &PEGTransformerFactory::InitializeWindowFrameDefinitionTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameDefinitionTrampoline}; -static const TransformFrameOps WINDOW_FRAME_NAME_CONTENTS_PARENS_OPS = { - "WindowFrameNameContentsParens", &PEGTransformerFactory::InitializeWindowFrameNameContentsParensTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline}; -static const TransformFrameOps WINDOW_FRAME_NAME_CONTENTS_OPS = { - "WindowFrameNameContents", &PEGTransformerFactory::InitializeWindowFrameNameContentsTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline}; -static const TransformFrameOps WINDOW_FRAME_CONTENTS_PARENS_OPS = { - "WindowFrameContentsParens", &PEGTransformerFactory::InitializeWindowFrameContentsParensTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline}; -static const TransformFrameOps WINDOW_FRAME_CONTENTS_OPS = { - "WindowFrameContents", &PEGTransformerFactory::InitializeWindowFrameContentsTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline}; -static const TransformFrameOps BASE_WINDOW_NAME_OPS = {"BaseWindowName", - &PEGTransformerFactory::InitializeBaseWindowNameTrampoline, - &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline}; -static const TransformFrameOps WINDOW_PARTITION_OPS = {"WindowPartition", - &PEGTransformerFactory::InitializeWindowPartitionTrampoline, - &PEGTransformerFactory::FinalizeWindowPartitionTrampoline}; -static const TransformFrameOps LIST_EXPRESSION_OPS = {"ListExpression", - &PEGTransformerFactory::InitializeListExpressionTrampoline, - &PEGTransformerFactory::FinalizeListExpressionTrampoline}; -static const TransformFrameOps ARRAY_BOUNDED_LIST_EXPRESSION_OPS = { - "ArrayBoundedListExpression", &PEGTransformerFactory::InitializeArrayBoundedListExpressionTrampoline, - &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline}; -static const TransformFrameOps ARRAY_PARENS_SELECT_OPS = {"ArrayParensSelect", - &PEGTransformerFactory::InitializeArrayParensSelectTrampoline, - &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline}; -static const TransformFrameOps BOUNDED_LIST_EXPRESSION_OPS = { - "BoundedListExpression", &PEGTransformerFactory::InitializeBoundedListExpressionTrampoline, - &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline}; -static const TransformFrameOps STRUCT_EXPRESSION_OPS = {"StructExpression", - &PEGTransformerFactory::InitializeStructExpressionTrampoline, - &PEGTransformerFactory::FinalizeStructExpressionTrampoline}; -static const TransformFrameOps STRUCT_FIELD_OPS = {"StructField", - &PEGTransformerFactory::InitializeStructFieldTrampoline, - &PEGTransformerFactory::FinalizeStructFieldTrampoline}; -static const TransformFrameOps MAP_EXPRESSION_OPS = {"MapExpression", - &PEGTransformerFactory::InitializeMapExpressionTrampoline, - &PEGTransformerFactory::FinalizeMapExpressionTrampoline}; -static const TransformFrameOps MAP_STRUCT_EXPRESSION_OPS = { - "MapStructExpression", &PEGTransformerFactory::InitializeMapStructExpressionTrampoline, - &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline}; -static const TransformFrameOps MAP_STRUCT_FIELD_OPS = {"MapStructField", - &PEGTransformerFactory::InitializeMapStructFieldTrampoline, - &PEGTransformerFactory::FinalizeMapStructFieldTrampoline}; -static const TransformFrameOps GROUPING_EXPRESSION_OPS = { - "GroupingExpression", &PEGTransformerFactory::InitializeGroupingExpressionTrampoline, - &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline}; -static const TransformFrameOps GROUPING_OR_GROUPING_ID_OPS = { - "GroupingOrGroupingId", &PEGTransformerFactory::InitializeGroupingOrGroupingIdTrampoline, - &PEGTransformerFactory::FinalizeGroupingOrGroupingIdTrampoline}; -static const TransformFrameOps GROUPING_KEYWORD_OPS = {"GroupingKeyword", - &PEGTransformerFactory::InitializeGroupingKeywordTrampoline, - &PEGTransformerFactory::FinalizeGroupingKeywordTrampoline}; -static const TransformFrameOps GROUPING_ID_KEYWORD_OPS = {"GroupingIdKeyword", - &PEGTransformerFactory::InitializeGroupingIdKeywordTrampoline, - &PEGTransformerFactory::FinalizeGroupingIdKeywordTrampoline}; -static const TransformFrameOps PARAMETER_OPS = {"Parameter", &PEGTransformerFactory::InitializeParameterTrampoline, - &PEGTransformerFactory::FinalizeParameterTrampoline}; -static const TransformFrameOps QUESTION_MARK_NUMBERED_PARAMETER_OPS = { - "QuestionMarkNumberedParameter", &PEGTransformerFactory::InitializeQuestionMarkNumberedParameterTrampoline, - &PEGTransformerFactory::FinalizeQuestionMarkNumberedParameterTrampoline}; -static const TransformFrameOps ANONYMOUS_PARAMETER_OPS = { - "AnonymousParameter", &PEGTransformerFactory::InitializeAnonymousParameterTrampoline, - &PEGTransformerFactory::FinalizeAnonymousParameterTrampoline}; -static const TransformFrameOps NUMBERED_PARAMETER_OPS = {"NumberedParameter", - &PEGTransformerFactory::InitializeNumberedParameterTrampoline, - &PEGTransformerFactory::FinalizeNumberedParameterTrampoline}; -static const TransformFrameOps COL_LABEL_PARAMETER_OPS = {"ColLabelParameter", - &PEGTransformerFactory::InitializeColLabelParameterTrampoline, - &PEGTransformerFactory::FinalizeColLabelParameterTrampoline}; -static const TransformFrameOps POSITIONAL_EXPRESSION_OPS = { - "PositionalExpression", &PEGTransformerFactory::InitializePositionalExpressionTrampoline, - &PEGTransformerFactory::FinalizePositionalExpressionTrampoline}; -static const TransformFrameOps DEFAULT_EXPRESSION_OPS = {"DefaultExpression", - &PEGTransformerFactory::InitializeDefaultExpressionTrampoline, - &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline}; -static const TransformFrameOps LIST_COMPREHENSION_EXPRESSION_OPS = { - "ListComprehensionExpression", &PEGTransformerFactory::InitializeListComprehensionExpressionTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline}; -static const TransformFrameOps LIST_COMPREHENSION_FILTER_OPS = { - "ListComprehensionFilter", &PEGTransformerFactory::InitializeListComprehensionFilterTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline}; -static const TransformFrameOps PARENS_EXPRESSION_OPS = {"ParensExpression", - &PEGTransformerFactory::InitializeParensExpressionTrampoline, - &PEGTransformerFactory::FinalizeParensExpressionTrampoline}; -static const TransformFrameOps MEASURE_SEMANTICS_EXPRESSION_OPS = { - "MeasureSemanticsExpression", &PEGTransformerFactory::InitializeMeasureSemanticsExpressionTrampoline, - &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline}; -static const TransformFrameOps SINGLE_EXPRESSION_OPS = {"SingleExpression", - &PEGTransformerFactory::InitializeSingleExpressionTrampoline, - &PEGTransformerFactory::FinalizeSingleExpressionTrampoline}; -static const TransformFrameOps EXPRESSION_OPS = {"Expression", &PEGTransformerFactory::InitializeExpressionTrampoline, - &PEGTransformerFactory::FinalizeExpressionTrampoline}; -static const TransformFrameOps COLUMN_DEFAULT_EXPR_OPS = {"ColumnDefaultExpr", - &PEGTransformerFactory::InitializeColumnDefaultExprTrampoline, - &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline}; -static const TransformFrameOps LAMBDA_ARROW_EXPRESSION_OPS = { - "LambdaArrowExpression", &PEGTransformerFactory::InitializeLambdaArrowExpressionTrampoline, - &PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline}; -static const TransformFrameOps SINGLE_ARROW_PAIR_OPS = {"SingleArrowPair", - &PEGTransformerFactory::InitializeSingleArrowPairTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowPairTrampoline}; -static const TransformFrameOps LOGICAL_OR_EXPRESSION_OPS = { - "LogicalOrExpression", &PEGTransformerFactory::InitializeLogicalOrExpressionTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline}; -static const TransformFrameOps LOGICAL_OR_EXPRESSION_TAIL_OPS = { - "LogicalOrExpressionTail", &PEGTransformerFactory::InitializeLogicalOrExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline}; -static const TransformFrameOps COL_DEF_OR_EXPR_OPS = {"ColDefOrExpr", - &PEGTransformerFactory::InitializeColDefOrExprTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExprTrampoline}; -static const TransformFrameOps COL_DEF_OR_EXPRESSION_TAIL_OPS = { - "ColDefOrExpressionTail", &PEGTransformerFactory::InitializeColDefOrExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline}; -static const TransformFrameOps LOGICAL_AND_EXPRESSION_OPS = { - "LogicalAndExpression", &PEGTransformerFactory::InitializeLogicalAndExpressionTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline}; -static const TransformFrameOps LOGICAL_AND_EXPRESSION_TAIL_OPS = { - "LogicalAndExpressionTail", &PEGTransformerFactory::InitializeLogicalAndExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline}; -static const TransformFrameOps COL_DEF_AND_EXPR_OPS = {"ColDefAndExpr", - &PEGTransformerFactory::InitializeColDefAndExprTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExprTrampoline}; -static const TransformFrameOps COL_DEF_AND_EXPRESSION_TAIL_OPS = { - "ColDefAndExpressionTail", &PEGTransformerFactory::InitializeColDefAndExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline}; -static const TransformFrameOps LOGICAL_NOT_EXPRESSION_OPS = { - "LogicalNotExpression", &PEGTransformerFactory::InitializeLogicalNotExpressionTrampoline, - &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline}; -static const TransformFrameOps NOT_EXPRESSION_OPS = {"NotExpression", - &PEGTransformerFactory::InitializeNotExpressionTrampoline, - &PEGTransformerFactory::FinalizeNotExpressionTrampoline}; -static const TransformFrameOps NOT_KEYWORD_OPS = {"NotKeyword", &PEGTransformerFactory::InitializeNotKeywordTrampoline, - &PEGTransformerFactory::FinalizeNotKeywordTrampoline}; -static const TransformFrameOps IS_EXPRESSION_OPS = {"IsExpression", - &PEGTransformerFactory::InitializeIsExpressionTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTrampoline}; -static const TransformFrameOps IS_EXPRESSION_CONTINUATION_OPS = { - "IsExpressionContinuation", &PEGTransformerFactory::InitializeIsExpressionContinuationTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline}; -static const TransformFrameOps IS_EXPRESSION_TAIL_OPS = {"IsExpressionTail", - &PEGTransformerFactory::InitializeIsExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTailTrampoline}; -static const TransformFrameOps IS_TEST_TAIL_OPS = {"IsTestTail", &PEGTransformerFactory::InitializeIsTestTailTrampoline, - &PEGTransformerFactory::FinalizeIsTestTailTrampoline}; -static const TransformFrameOps IS_DISTINCT_TAIL_OPS = {"IsDistinctTail", - &PEGTransformerFactory::InitializeIsDistinctTailTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline}; -static const TransformFrameOps IS_COMPARISON_TAIL_OPS = {"IsComparisonTail", - &PEGTransformerFactory::InitializeIsComparisonTailTrampoline, - &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline}; -static const TransformFrameOps IS_OTHER_OPERATOR_TAIL_OPS = { - "IsOtherOperatorTail", &PEGTransformerFactory::InitializeIsOtherOperatorTailTrampoline, - &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline}; -static const TransformFrameOps IS_CAST_TAIL_OPS = {"IsCastTail", &PEGTransformerFactory::InitializeIsCastTailTrampoline, - &PEGTransformerFactory::FinalizeIsCastTailTrampoline}; -static const TransformFrameOps IS_TEST_OPS = {"IsTest", &PEGTransformerFactory::InitializeIsTestTrampoline, - &PEGTransformerFactory::FinalizeIsTestTrampoline}; -static const TransformFrameOps IS_LITERAL_OPS = {"IsLiteral", &PEGTransformerFactory::InitializeIsLiteralTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralTrampoline}; -static const TransformFrameOps IS_LITERAL_VALUE_OPS = {"IsLiteralValue", - &PEGTransformerFactory::InitializeIsLiteralValueTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralValueTrampoline}; -static const TransformFrameOps UNKNOWN_LITERAL_OPS = {"UnknownLiteral", - &PEGTransformerFactory::InitializeUnknownLiteralTrampoline, - &PEGTransformerFactory::FinalizeUnknownLiteralTrampoline}; -static const TransformFrameOps NOT_NULL_OPS = {"NotNull", &PEGTransformerFactory::InitializeNotNullTrampoline, - &PEGTransformerFactory::FinalizeNotNullTrampoline}; -static const TransformFrameOps NOT_NULL_KEYWORD_OPS = {"NotNullKeyword", - &PEGTransformerFactory::InitializeNotNullKeywordTrampoline, - &PEGTransformerFactory::FinalizeNotNullKeywordTrampoline}; -static const TransformFrameOps NOT_NULL_OPERATOR_OPS = {"NotNullOperator", - &PEGTransformerFactory::InitializeNotNullOperatorTrampoline, - &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline}; -static const TransformFrameOps IS_NULL_OPS = {"IsNull", &PEGTransformerFactory::InitializeIsNullTrampoline, - &PEGTransformerFactory::FinalizeIsNullTrampoline}; -static const TransformFrameOps IS_NULL_OPERATOR_OPS = {"IsNullOperator", - &PEGTransformerFactory::InitializeIsNullOperatorTrampoline, - &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline}; -static const TransformFrameOps IS_DISTINCT_FROM_EXPRESSION_OPS = { - "IsDistinctFromExpression", &PEGTransformerFactory::InitializeIsDistinctFromExpressionTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline}; -static const TransformFrameOps IS_DISTINCT_FROM_TAIL_OPS = { - "IsDistinctFromTail", &PEGTransformerFactory::InitializeIsDistinctFromTailTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline}; -static const TransformFrameOps IS_DISTINCT_FROM_OP_OPS = {"IsDistinctFromOp", - &PEGTransformerFactory::InitializeIsDistinctFromOpTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline}; -static const TransformFrameOps COMPARISON_EXPRESSION_OPS = { - "ComparisonExpression", &PEGTransformerFactory::InitializeComparisonExpressionTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline}; -static const TransformFrameOps COMPARISON_EXPRESSION_TAIL_OPS = { - "ComparisonExpressionTail", &PEGTransformerFactory::InitializeComparisonExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline}; -static const TransformFrameOps COMPARISON_OPERAND_OPS = {"ComparisonOperand", - &PEGTransformerFactory::InitializeComparisonOperandTrampoline, - &PEGTransformerFactory::FinalizeComparisonOperandTrampoline}; -static const TransformFrameOps NOT_COMPARISON_OPERAND_OPS = { - "NotComparisonOperand", &PEGTransformerFactory::InitializeNotComparisonOperandTrampoline, - &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline}; -static const TransformFrameOps COMPARISON_OPERATOR_OPS = { - "ComparisonOperator", &PEGTransformerFactory::InitializeComparisonOperatorTrampoline, - &PEGTransformerFactory::FinalizeComparisonOperatorTrampoline}; -static const TransformFrameOps OPERATOR_EQUAL_OPS = {"OperatorEqual", - &PEGTransformerFactory::InitializeOperatorEqualTrampoline, - &PEGTransformerFactory::FinalizeOperatorEqualTrampoline}; -static const TransformFrameOps OPERATOR_NOT_EQUAL_OPS = {"OperatorNotEqual", - &PEGTransformerFactory::InitializeOperatorNotEqualTrampoline, - &PEGTransformerFactory::FinalizeOperatorNotEqualTrampoline}; -static const TransformFrameOps OPERATOR_LESS_THAN_OPS = {"OperatorLessThan", - &PEGTransformerFactory::InitializeOperatorLessThanTrampoline, - &PEGTransformerFactory::FinalizeOperatorLessThanTrampoline}; -static const TransformFrameOps OPERATOR_GREATER_THAN_OPS = { - "OperatorGreaterThan", &PEGTransformerFactory::InitializeOperatorGreaterThanTrampoline, - &PEGTransformerFactory::FinalizeOperatorGreaterThanTrampoline}; -static const TransformFrameOps OPERATOR_LESS_THAN_EQUALS_OPS = { - "OperatorLessThanEquals", &PEGTransformerFactory::InitializeOperatorLessThanEqualsTrampoline, - &PEGTransformerFactory::FinalizeOperatorLessThanEqualsTrampoline}; -static const TransformFrameOps OPERATOR_GREATER_THAN_EQUALS_OPS = { - "OperatorGreaterThanEquals", &PEGTransformerFactory::InitializeOperatorGreaterThanEqualsTrampoline, - &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline}; -static const TransformFrameOps BETWEEN_IN_LIKE_EXPRESSION_OPS = { - "BetweenInLikeExpression", &PEGTransformerFactory::InitializeBetweenInLikeExpressionTrampoline, - &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline}; -static const TransformFrameOps IN_PREDICATE_OPS = {"InPredicate", - &PEGTransformerFactory::InitializeInPredicateTrampoline, - &PEGTransformerFactory::FinalizeInPredicateTrampoline}; -static const TransformFrameOps BETWEEN_LIKE_OP_OPS = {"BetweenLikeOp", - &PEGTransformerFactory::InitializeBetweenLikeOpTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline}; -static const TransformFrameOps BETWEEN_LIKE_OP_EXPRESSION_OPS = { - "BetweenLikeOpExpression", &PEGTransformerFactory::InitializeBetweenLikeOpExpressionTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpExpressionTrampoline}; -static const TransformFrameOps LIKE_CLAUSE_OPS = {"LikeClause", &PEGTransformerFactory::InitializeLikeClauseTrampoline, - &PEGTransformerFactory::FinalizeLikeClauseTrampoline}; -static const TransformFrameOps ESCAPE_CLAUSE_OPS = {"EscapeClause", - &PEGTransformerFactory::InitializeEscapeClauseTrampoline, - &PEGTransformerFactory::FinalizeEscapeClauseTrampoline}; -static const TransformFrameOps LIKE_VARIATIONS_OPS = {"LikeVariations", - &PEGTransformerFactory::InitializeLikeVariationsTrampoline, - &PEGTransformerFactory::FinalizeLikeVariationsTrampoline}; -static const TransformFrameOps LIKE_TOKEN_OPS = {"LikeToken", &PEGTransformerFactory::InitializeLikeTokenTrampoline, - &PEGTransformerFactory::FinalizeLikeTokenTrampoline}; -static const TransformFrameOps ILIKE_TOKEN_OPS = {"ILikeToken", &PEGTransformerFactory::InitializeILikeTokenTrampoline, - &PEGTransformerFactory::FinalizeILikeTokenTrampoline}; -static const TransformFrameOps GLOB_TOKEN_OPS = {"GlobToken", &PEGTransformerFactory::InitializeGlobTokenTrampoline, - &PEGTransformerFactory::FinalizeGlobTokenTrampoline}; -static const TransformFrameOps SIMILAR_TO_TOKEN_OPS = {"SimilarToToken", - &PEGTransformerFactory::InitializeSimilarToTokenTrampoline, - &PEGTransformerFactory::FinalizeSimilarToTokenTrampoline}; -static const TransformFrameOps REGEX_MATCH_TOKEN_OPS = {"RegexMatchToken", - &PEGTransformerFactory::InitializeRegexMatchTokenTrampoline, - &PEGTransformerFactory::FinalizeRegexMatchTokenTrampoline}; -static const TransformFrameOps REGEX_INSENSITIVE_MATCH_TOKEN_OPS = { - "RegexInsensitiveMatchToken", &PEGTransformerFactory::InitializeRegexInsensitiveMatchTokenTrampoline, - &PEGTransformerFactory::FinalizeRegexInsensitiveMatchTokenTrampoline}; -static const TransformFrameOps NOT_ILIKE_OP_OPS = {"NotILikeOp", &PEGTransformerFactory::InitializeNotILikeOpTrampoline, - &PEGTransformerFactory::FinalizeNotILikeOpTrampoline}; -static const TransformFrameOps NOT_LIKE_OP_OPS = {"NotLikeOp", &PEGTransformerFactory::InitializeNotLikeOpTrampoline, - &PEGTransformerFactory::FinalizeNotLikeOpTrampoline}; -static const TransformFrameOps NOT_REGEX_INSENSITIVE_MATCH_OP_OPS = { - "NotRegexInsensitiveMatchOp", &PEGTransformerFactory::InitializeNotRegexInsensitiveMatchOpTrampoline, - &PEGTransformerFactory::FinalizeNotRegexInsensitiveMatchOpTrampoline}; -static const TransformFrameOps NOT_SIMILAR_TO_OP_OPS = {"NotSimilarToOp", - &PEGTransformerFactory::InitializeNotSimilarToOpTrampoline, - &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline}; -static const TransformFrameOps IN_CLAUSE_OPS = {"InClause", &PEGTransformerFactory::InitializeInClauseTrampoline, - &PEGTransformerFactory::FinalizeInClauseTrampoline}; -static const TransformFrameOps IN_EXPRESSION_OPS = {"InExpression", - &PEGTransformerFactory::InitializeInExpressionTrampoline, - &PEGTransformerFactory::FinalizeInExpressionTrampoline}; -static const TransformFrameOps IN_CONTAINS_EXPRESSION_OPS = { - "InContainsExpression", &PEGTransformerFactory::InitializeInContainsExpressionTrampoline, - &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline}; -static const TransformFrameOps IN_EXPRESSION_LIST_OPS = {"InExpressionList", - &PEGTransformerFactory::InitializeInExpressionListTrampoline, - &PEGTransformerFactory::FinalizeInExpressionListTrampoline}; -static const TransformFrameOps IN_SELECT_STATEMENT_OPS = {"InSelectStatement", - &PEGTransformerFactory::InitializeInSelectStatementTrampoline, - &PEGTransformerFactory::FinalizeInSelectStatementTrampoline}; -static const TransformFrameOps BETWEEN_CLAUSE_OPS = {"BetweenClause", - &PEGTransformerFactory::InitializeBetweenClauseTrampoline, - &PEGTransformerFactory::FinalizeBetweenClauseTrampoline}; -static const TransformFrameOps OTHER_OPERATOR_EXPRESSION_OPS = { - "OtherOperatorExpression", &PEGTransformerFactory::InitializeOtherOperatorExpressionTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorExpressionTrampoline}; -static const TransformFrameOps INFIX_OTHER_OPERATOR_EXPRESSION_OPS = { - "InfixOtherOperatorExpression", &PEGTransformerFactory::InitializeInfixOtherOperatorExpressionTrampoline, - &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline}; -static const TransformFrameOps OTHER_OPERATOR_TAIL_OPS = {"OtherOperatorTail", - &PEGTransformerFactory::InitializeOtherOperatorTailTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorTailTrampoline}; -static const TransformFrameOps OTHER_OPERATOR_OPS = {"OtherOperator", - &PEGTransformerFactory::InitializeOtherOperatorTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorTrampoline}; -static const TransformFrameOps ANY_ALL_PARSED_OPERATOR_OPS = { - "AnyAllParsedOperator", &PEGTransformerFactory::InitializeAnyAllParsedOperatorTrampoline, - &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline}; -static const TransformFrameOps NAMED_OTHER_OPERATOR_OPS = { - "NamedOtherOperator", &PEGTransformerFactory::InitializeNamedOtherOperatorTrampoline, - &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline}; -static const TransformFrameOps OPERATOR_LITERAL_OPS = {"OperatorLiteral", - &PEGTransformerFactory::InitializeOperatorLiteralTrampoline, - &PEGTransformerFactory::FinalizeOperatorLiteralTrampoline}; -static const TransformFrameOps ANY_OPERATOR_LITERAL_OPS = { - "AnyOperatorLiteral", &PEGTransformerFactory::InitializeAnyOperatorLiteralTrampoline, - &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline}; -static const TransformFrameOps ANY_ALL_OPERATOR_OPS = {"AnyAllOperator", - &PEGTransformerFactory::InitializeAnyAllOperatorTrampoline, - &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline}; -static const TransformFrameOps ANY_OR_ALL_OPS = {"AnyOrAll", &PEGTransformerFactory::InitializeAnyOrAllTrampoline, - &PEGTransformerFactory::FinalizeAnyOrAllTrampoline}; -static const TransformFrameOps SUBQUERY_ANY_OPS = {"SubqueryAny", - &PEGTransformerFactory::InitializeSubqueryAnyTrampoline, - &PEGTransformerFactory::FinalizeSubqueryAnyTrampoline}; -static const TransformFrameOps SUBQUERY_ALL_OPS = {"SubqueryAll", - &PEGTransformerFactory::InitializeSubqueryAllTrampoline, - &PEGTransformerFactory::FinalizeSubqueryAllTrampoline}; -static const TransformFrameOps QUALIFIED_OPERATOR_OPS = {"QualifiedOperator", - &PEGTransformerFactory::InitializeQualifiedOperatorTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline}; -static const TransformFrameOps QUALIFIED_OPERATOR_CONTENTS_OPS = { - "QualifiedOperatorContents", &PEGTransformerFactory::InitializeQualifiedOperatorContentsTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline}; -static const TransformFrameOps BITWISE_EXPRESSION_OPS = {"BitwiseExpression", - &PEGTransformerFactory::InitializeBitwiseExpressionTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline}; -static const TransformFrameOps BITWISE_EXPRESSION_TAIL_OPS = { - "BitwiseExpressionTail", &PEGTransformerFactory::InitializeBitwiseExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline}; -static const TransformFrameOps BIT_OPERATOR_OPS = {"BitOperator", - &PEGTransformerFactory::InitializeBitOperatorTrampoline, - &PEGTransformerFactory::FinalizeBitOperatorTrampoline}; -static const TransformFrameOps TILDE_EXPRESSION_OPS = {"TildeExpression", - &PEGTransformerFactory::InitializeTildeExpressionTrampoline, - &PEGTransformerFactory::FinalizeTildeExpressionTrampoline}; -static const TransformFrameOps ADDITIVE_EXPRESSION_OPS = { - "AdditiveExpression", &PEGTransformerFactory::InitializeAdditiveExpressionTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline}; -static const TransformFrameOps ADDITIVE_EXPRESSION_TAIL_OPS = { - "AdditiveExpressionTail", &PEGTransformerFactory::InitializeAdditiveExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline}; -static const TransformFrameOps TERM_OPS = {"Term", &PEGTransformerFactory::InitializeTermTrampoline, - &PEGTransformerFactory::FinalizeTermTrampoline}; -static const TransformFrameOps MULTIPLICATIVE_EXPRESSION_OPS = { - "MultiplicativeExpression", &PEGTransformerFactory::InitializeMultiplicativeExpressionTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline}; -static const TransformFrameOps MULTIPLICATIVE_EXPRESSION_TAIL_OPS = { - "MultiplicativeExpressionTail", &PEGTransformerFactory::InitializeMultiplicativeExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline}; -static const TransformFrameOps FACTOR_OPS = {"Factor", &PEGTransformerFactory::InitializeFactorTrampoline, - &PEGTransformerFactory::FinalizeFactorTrampoline}; -static const TransformFrameOps EXPONENTIATION_EXPRESSION_OPS = { - "ExponentiationExpression", &PEGTransformerFactory::InitializeExponentiationExpressionTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline}; -static const TransformFrameOps EXPONENTIATION_EXPRESSION_TAIL_OPS = { - "ExponentiationExpressionTail", &PEGTransformerFactory::InitializeExponentiationExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline}; -static const TransformFrameOps EXPONENT_OPERATOR_OPS = {"ExponentOperator", - &PEGTransformerFactory::InitializeExponentOperatorTrampoline, - &PEGTransformerFactory::FinalizeExponentOperatorTrampoline}; -static const TransformFrameOps COLLATE_EXPRESSION_OPS = {"CollateExpression", - &PEGTransformerFactory::InitializeCollateExpressionTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTrampoline}; -static const TransformFrameOps COLLATE_EXPRESSION_TAIL_OPS = { - "CollateExpressionTail", &PEGTransformerFactory::InitializeCollateExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline}; -static const TransformFrameOps AT_TIME_ZONE_EXPRESSION_OPS = { - "AtTimeZoneExpression", &PEGTransformerFactory::InitializeAtTimeZoneExpressionTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline}; -static const TransformFrameOps AT_TIME_ZONE_EXPRESSION_TAIL_OPS = { - "AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializeAtTimeZoneExpressionTailTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline}; -static const TransformFrameOps UNARY_EXPRESSION_OPS = {"UnaryExpression", - &PEGTransformerFactory::InitializeUnaryExpressionTrampoline, - &PEGTransformerFactory::FinalizeUnaryExpressionTrampoline}; -static const TransformFrameOps PREFIX_EXPRESSION_OPS = {"PrefixExpression", - &PEGTransformerFactory::InitializePrefixExpressionTrampoline, - &PEGTransformerFactory::FinalizePrefixExpressionTrampoline}; -static const TransformFrameOps CUSTOM_PREFIX_EXPRESSION_OPS = { - "CustomPrefixExpression", &PEGTransformerFactory::InitializeCustomPrefixExpressionTrampoline, - &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline}; -static const TransformFrameOps PREFIX_OPERATOR_OPS = {"PrefixOperator", - &PEGTransformerFactory::InitializePrefixOperatorTrampoline, - &PEGTransformerFactory::FinalizePrefixOperatorTrampoline}; -static const TransformFrameOps MINUS_PREFIX_OPERATOR_OPS = { - "MinusPrefixOperator", &PEGTransformerFactory::InitializeMinusPrefixOperatorTrampoline, - &PEGTransformerFactory::FinalizeMinusPrefixOperatorTrampoline}; -static const TransformFrameOps PLUS_PREFIX_OPERATOR_OPS = { - "PlusPrefixOperator", &PEGTransformerFactory::InitializePlusPrefixOperatorTrampoline, - &PEGTransformerFactory::FinalizePlusPrefixOperatorTrampoline}; -static const TransformFrameOps TILDE_PREFIX_OPERATOR_OPS = { - "TildePrefixOperator", &PEGTransformerFactory::InitializeTildePrefixOperatorTrampoline, - &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline}; -static const TransformFrameOps BASE_EXPRESSION_OPS = {"BaseExpression", - &PEGTransformerFactory::InitializeBaseExpressionTrampoline, - &PEGTransformerFactory::FinalizeBaseExpressionTrampoline}; -static const TransformFrameOps INDIRECTION_LIST_OPS = {"IndirectionList", - &PEGTransformerFactory::InitializeIndirectionListTrampoline, - &PEGTransformerFactory::FinalizeIndirectionListTrampoline}; -static const TransformFrameOps INDIRECTION_OPS = {"Indirection", - &PEGTransformerFactory::InitializeIndirectionTrampoline, - &PEGTransformerFactory::FinalizeIndirectionTrampoline}; -static const TransformFrameOps CAST_OPERATOR_OPS = {"CastOperator", - &PEGTransformerFactory::InitializeCastOperatorTrampoline, - &PEGTransformerFactory::FinalizeCastOperatorTrampoline}; -static const TransformFrameOps DOT_OPERATOR_OPS = {"DotOperator", - &PEGTransformerFactory::InitializeDotOperatorTrampoline, - &PEGTransformerFactory::FinalizeDotOperatorTrampoline}; -static const TransformFrameOps DOT_METHOD_OPERATOR_OPS = {"DotMethodOperator", - &PEGTransformerFactory::InitializeDotMethodOperatorTrampoline, - &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline}; -static const TransformFrameOps DOT_COLUMN_OPERATOR_OPS = {"DotColumnOperator", - &PEGTransformerFactory::InitializeDotColumnOperatorTrampoline, - &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline}; -static const TransformFrameOps METHOD_EXPRESSION_OPS = {"MethodExpression", - &PEGTransformerFactory::InitializeMethodExpressionTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionTrampoline}; -static const TransformFrameOps METHOD_EXPRESSION_ARGUMENTS_OPS = { - "MethodExpressionArguments", &PEGTransformerFactory::InitializeMethodExpressionArgumentsTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline}; -static const TransformFrameOps METHOD_EXPRESSION_ARGUMENT_LIST_OPS = { - "MethodExpressionArgumentList", &PEGTransformerFactory::InitializeMethodExpressionArgumentListTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline}; -static const TransformFrameOps METHOD_FUNCTION_ARGUMENTS_OPS = { - "MethodFunctionArguments", &PEGTransformerFactory::InitializeMethodFunctionArgumentsTrampoline, - &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline}; -static const TransformFrameOps SLICE_EXPRESSION_OPS = {"SliceExpression", - &PEGTransformerFactory::InitializeSliceExpressionTrampoline, - &PEGTransformerFactory::FinalizeSliceExpressionTrampoline}; -static const TransformFrameOps SLICE_BOUND_OPS = {"SliceBound", &PEGTransformerFactory::InitializeSliceBoundTrampoline, - &PEGTransformerFactory::FinalizeSliceBoundTrampoline}; -static const TransformFrameOps SLICE_UPPER_BOUND_OPS = {"SliceUpperBound", - &PEGTransformerFactory::InitializeSliceUpperBoundTrampoline, - &PEGTransformerFactory::FinalizeSliceUpperBoundTrampoline}; -static const TransformFrameOps MINUS_STEP_SLICE_BOUND_OPS = { - "MinusStepSliceBound", &PEGTransformerFactory::InitializeMinusStepSliceBoundTrampoline, - &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline}; -static const TransformFrameOps END_STEP_SLICE_BOUND_OPS = { - "EndStepSliceBound", &PEGTransformerFactory::InitializeEndStepSliceBoundTrampoline, - &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline}; -static const TransformFrameOps END_SLICE_BOUND_OPS = {"EndSliceBound", - &PEGTransformerFactory::InitializeEndSliceBoundTrampoline, - &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline}; -static const TransformFrameOps STEP_SLICE_BOUND_OPS = {"StepSliceBound", - &PEGTransformerFactory::InitializeStepSliceBoundTrampoline, - &PEGTransformerFactory::FinalizeStepSliceBoundTrampoline}; -static const TransformFrameOps POSTFIX_OPERATOR_OPS = {"PostfixOperator", - &PEGTransformerFactory::InitializePostfixOperatorTrampoline, - &PEGTransformerFactory::FinalizePostfixOperatorTrampoline}; -static const TransformFrameOps SPECIAL_FUNCTION_EXPRESSION_OPS = { - "SpecialFunctionExpression", &PEGTransformerFactory::InitializeSpecialFunctionExpressionTrampoline, - &PEGTransformerFactory::FinalizeSpecialFunctionExpressionTrampoline}; -static const TransformFrameOps COALESCE_EXPRESSION_OPS = { - "CoalesceExpression", &PEGTransformerFactory::InitializeCoalesceExpressionTrampoline, - &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline}; -static const TransformFrameOps UNPACK_EXPRESSION_OPS = {"UnpackExpression", - &PEGTransformerFactory::InitializeUnpackExpressionTrampoline, - &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline}; -static const TransformFrameOps TRY_EXPRESSION_OPS = {"TryExpression", - &PEGTransformerFactory::InitializeTryExpressionTrampoline, - &PEGTransformerFactory::FinalizeTryExpressionTrampoline}; -static const TransformFrameOps COLUMNS_EXPRESSION_OPS = {"ColumnsExpression", - &PEGTransformerFactory::InitializeColumnsExpressionTrampoline, - &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline}; -static const TransformFrameOps EXTRACT_EXPRESSION_OPS = {"ExtractExpression", - &PEGTransformerFactory::InitializeExtractExpressionTrampoline, - &PEGTransformerFactory::FinalizeExtractExpressionTrampoline}; -static const TransformFrameOps EXTRACT_ARGUMENTS_OPS = {"ExtractArguments", - &PEGTransformerFactory::InitializeExtractArgumentsTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline}; -static const TransformFrameOps LAMBDA_EXPRESSION_OPS = {"LambdaExpression", - &PEGTransformerFactory::InitializeLambdaExpressionTrampoline, - &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline}; -static const TransformFrameOps NULL_IF_EXPRESSION_OPS = {"NullIfExpression", - &PEGTransformerFactory::InitializeNullIfExpressionTrampoline, - &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline}; -static const TransformFrameOps NULL_IF_ARGUMENTS_OPS = {"NullIfArguments", - &PEGTransformerFactory::InitializeNullIfArgumentsTrampoline, - &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline}; -static const TransformFrameOps POSITION_EXPRESSION_OPS = { - "PositionExpression", &PEGTransformerFactory::InitializePositionExpressionTrampoline, - &PEGTransformerFactory::FinalizePositionExpressionTrampoline}; -static const TransformFrameOps POSITION_ARGUMENTS_OPS = {"PositionArguments", - &PEGTransformerFactory::InitializePositionArgumentsTrampoline, - &PEGTransformerFactory::FinalizePositionArgumentsTrampoline}; -static const TransformFrameOps ROW_EXPRESSION_OPS = {"RowExpression", - &PEGTransformerFactory::InitializeRowExpressionTrampoline, - &PEGTransformerFactory::FinalizeRowExpressionTrampoline}; -static const TransformFrameOps SUBSTRING_EXPRESSION_OPS = { - "SubstringExpression", &PEGTransformerFactory::InitializeSubstringExpressionTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline}; -static const TransformFrameOps SUBSTRING_ARGUMENTS_OPS = { - "SubstringArguments", &PEGTransformerFactory::InitializeSubstringArgumentsTrampoline, - &PEGTransformerFactory::FinalizeSubstringArgumentsTrampoline}; -static const TransformFrameOps SUBSTRING_EXPRESSION_LIST_OPS = { - "SubstringExpressionList", &PEGTransformerFactory::InitializeSubstringExpressionListTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline}; -static const TransformFrameOps SUBSTRING_PARAMETERS_OPS = { - "SubstringParameters", &PEGTransformerFactory::InitializeSubstringParametersTrampoline, - &PEGTransformerFactory::FinalizeSubstringParametersTrampoline}; -static const TransformFrameOps SUBSTRING_FROM_FOR_OPS = {"SubstringFromFor", - &PEGTransformerFactory::InitializeSubstringFromForTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromForTrampoline}; -static const TransformFrameOps SUBSTRING_FROM_OPTIONAL_FOR_OPS = { - "SubstringFromOptionalFor", &PEGTransformerFactory::InitializeSubstringFromOptionalForTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline}; -static const TransformFrameOps SUBSTRING_FOR_OPS = {"SubstringFor", - &PEGTransformerFactory::InitializeSubstringForTrampoline, - &PEGTransformerFactory::FinalizeSubstringForTrampoline}; -static const TransformFrameOps TRIM_EXPRESSION_OPS = {"TrimExpression", - &PEGTransformerFactory::InitializeTrimExpressionTrampoline, - &PEGTransformerFactory::FinalizeTrimExpressionTrampoline}; -static const TransformFrameOps TRIM_ARGUMENTS_OPS = {"TrimArguments", - &PEGTransformerFactory::InitializeTrimArgumentsTrampoline, - &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline}; -static const TransformFrameOps TRIM_DIRECTION_OPS = {"TrimDirection", - &PEGTransformerFactory::InitializeTrimDirectionTrampoline, - &PEGTransformerFactory::FinalizeTrimDirectionTrampoline}; -static const TransformFrameOps TRIM_BOTH_OPS = {"TrimBoth", &PEGTransformerFactory::InitializeTrimBothTrampoline, - &PEGTransformerFactory::FinalizeTrimBothTrampoline}; -static const TransformFrameOps TRIM_LEADING_OPS = {"TrimLeading", - &PEGTransformerFactory::InitializeTrimLeadingTrampoline, - &PEGTransformerFactory::FinalizeTrimLeadingTrampoline}; -static const TransformFrameOps TRIM_TRAILING_OPS = {"TrimTrailing", - &PEGTransformerFactory::InitializeTrimTrailingTrampoline, - &PEGTransformerFactory::FinalizeTrimTrailingTrampoline}; -static const TransformFrameOps TRIM_SOURCE_OPS = {"TrimSource", &PEGTransformerFactory::InitializeTrimSourceTrampoline, - &PEGTransformerFactory::FinalizeTrimSourceTrampoline}; -static const TransformFrameOps OVERLAY_EXPRESSION_OPS = {"OverlayExpression", - &PEGTransformerFactory::InitializeOverlayExpressionTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline}; -static const TransformFrameOps OVERLAY_ARGUMENTS_OPS = {"OverlayArguments", - &PEGTransformerFactory::InitializeOverlayArgumentsTrampoline, - &PEGTransformerFactory::FinalizeOverlayArgumentsTrampoline}; -static const TransformFrameOps OVERLAY_PARAMETERS_OPS = {"OverlayParameters", - &PEGTransformerFactory::InitializeOverlayParametersTrampoline, - &PEGTransformerFactory::FinalizeOverlayParametersTrampoline}; -static const TransformFrameOps FROM_EXPRESSION_OPS = {"FromExpression", - &PEGTransformerFactory::InitializeFromExpressionTrampoline, - &PEGTransformerFactory::FinalizeFromExpressionTrampoline}; -static const TransformFrameOps FOR_EXPRESSION_OPS = {"ForExpression", - &PEGTransformerFactory::InitializeForExpressionTrampoline, - &PEGTransformerFactory::FinalizeForExpressionTrampoline}; -static const TransformFrameOps OVERLAY_EXPRESSION_LIST_OPS = { - "OverlayExpressionList", &PEGTransformerFactory::InitializeOverlayExpressionListTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline}; -static const TransformFrameOps EXTRACT_ARGUMENT_OPS = {"ExtractArgument", - &PEGTransformerFactory::InitializeExtractArgumentTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentTrampoline}; -static const TransformFrameOps EXTRACT_DATE_PART_ARGUMENT_OPS = { - "ExtractDatePartArgument", &PEGTransformerFactory::InitializeExtractDatePartArgumentTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline}; -static const TransformFrameOps EXTRACT_IDENTIFIER_ARGUMENT_OPS = { - "ExtractIdentifierArgument", &PEGTransformerFactory::InitializeExtractIdentifierArgumentTrampoline, - &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline}; -static const TransformFrameOps EXTRACT_STRING_ARGUMENT_OPS = { - "ExtractStringArgument", &PEGTransformerFactory::InitializeExtractStringArgumentTrampoline, - &PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline}; -static const TransformFrameOps EXTRACT_DATE_PART_OPS = {"ExtractDatePart", - &PEGTransformerFactory::InitializeExtractDatePartTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartTrampoline}; -static const TransformFrameOps EXTERNAL_RESOURCE_STATEMENT_OPS = { - "ExternalResourceStatement", &PEGTransformerFactory::InitializeExternalResourceStatementTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceStatementTrampoline}; -static const TransformFrameOps CREATE_EXTERNAL_RESOURCE_STMT_OPS = { - "CreateExternalResourceStmt", &PEGTransformerFactory::InitializeCreateExternalResourceStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline}; -static const TransformFrameOps REGISTER_EXTERNAL_RESOURCE_STMT_OPS = { - "RegisterExternalResourceStmt", &PEGTransformerFactory::InitializeRegisterExternalResourceStmtTrampoline, - &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline}; -static const TransformFrameOps DESTROY_EXTERNAL_RESOURCE_STMT_OPS = { - "DestroyExternalResourceStmt", &PEGTransformerFactory::InitializeDestroyExternalResourceStmtTrampoline, - &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline}; -static const TransformFrameOps SHOW_EXTERNAL_RESOURCES_STMT_OPS = { - "ShowExternalResourcesStmt", &PEGTransformerFactory::InitializeShowExternalResourcesStmtTrampoline, - &PEGTransformerFactory::FinalizeShowExternalResourcesStmtTrampoline}; -static const TransformFrameOps SHOW_ALL_MODIFIER_OPS = {"ShowAllModifier", - &PEGTransformerFactory::InitializeShowAllModifierTrampoline, - &PEGTransformerFactory::FinalizeShowAllModifierTrampoline}; -static const TransformFrameOps EXTERNAL_RESOURCE_CREATION_OPTIONS_OPS = { - "ExternalResourceCreationOptions", &PEGTransformerFactory::InitializeExternalResourceCreationOptionsTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreationOptionsTrampoline}; -static const TransformFrameOps ATTACH_TO_EXTERNAL_RESOURCE_OPS = { - "AttachToExternalResource", &PEGTransformerFactory::InitializeAttachToExternalResourceTrampoline, - &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline}; -static const TransformFrameOps CONNECT_TO_EXTERNAL_RESOURCE_OPS = { - "ConnectToExternalResource", &PEGTransformerFactory::InitializeConnectToExternalResourceTrampoline, - &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline}; -static const TransformFrameOps EXTERNAL_RESOURCE_SOURCE_OPS = { - "ExternalResourceSource", &PEGTransformerFactory::InitializeExternalResourceSourceTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceSourceTrampoline}; -static const TransformFrameOps EXTERNAL_RESOURCE_CREATE_CLAUSE_OPS = { - "ExternalResourceCreateClause", &PEGTransformerFactory::InitializeExternalResourceCreateClauseTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline}; -static const TransformFrameOps EXTERNAL_RESOURCE_REFERENCE_CLAUSE_OPS = { - "ExternalResourceReferenceClause", &PEGTransformerFactory::InitializeExternalResourceReferenceClauseTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline}; -static const TransformFrameOps INSERT_STATEMENT_OPS = {"InsertStatement", - &PEGTransformerFactory::InitializeInsertStatementTrampoline, - &PEGTransformerFactory::FinalizeInsertStatementTrampoline}; -static const TransformFrameOps OR_ACTION_OPS = {"OrAction", &PEGTransformerFactory::InitializeOrActionTrampoline, - &PEGTransformerFactory::FinalizeOrActionTrampoline}; -static const TransformFrameOps INSERT_OR_REPLACE_OPS = {"InsertOrReplace", - &PEGTransformerFactory::InitializeInsertOrReplaceTrampoline, - &PEGTransformerFactory::FinalizeInsertOrReplaceTrampoline}; -static const TransformFrameOps INSERT_OR_IGNORE_OPS = {"InsertOrIgnore", - &PEGTransformerFactory::InitializeInsertOrIgnoreTrampoline, - &PEGTransformerFactory::FinalizeInsertOrIgnoreTrampoline}; -static const TransformFrameOps BY_NAME_OR_POSITION_OPS = {"ByNameOrPosition", - &PEGTransformerFactory::InitializeByNameOrPositionTrampoline, - &PEGTransformerFactory::FinalizeByNameOrPositionTrampoline}; -static const TransformFrameOps INSERT_BY_NAME_ORDER_OPS = { - "InsertByNameOrder", &PEGTransformerFactory::InitializeInsertByNameOrderTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrderTrampoline}; -static const TransformFrameOps INSERT_BY_POSITION_ORDER_OPS = { - "InsertByPositionOrder", &PEGTransformerFactory::InitializeInsertByPositionOrderTrampoline, - &PEGTransformerFactory::FinalizeInsertByPositionOrderTrampoline}; -static const TransformFrameOps INSERT_BY_NAME_OPS = {"InsertByName", - &PEGTransformerFactory::InitializeInsertByNameTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameTrampoline}; -static const TransformFrameOps INSERT_BY_POSITION_OPS = {"InsertByPosition", - &PEGTransformerFactory::InitializeInsertByPositionTrampoline, - &PEGTransformerFactory::FinalizeInsertByPositionTrampoline}; -static const TransformFrameOps INSERT_TARGET_OPS = {"InsertTarget", - &PEGTransformerFactory::InitializeInsertTargetTrampoline, - &PEGTransformerFactory::FinalizeInsertTargetTrampoline}; -static const TransformFrameOps INSERT_ALIAS_OPS = {"InsertAlias", - &PEGTransformerFactory::InitializeInsertAliasTrampoline, - &PEGTransformerFactory::FinalizeInsertAliasTrampoline}; -static const TransformFrameOps COLUMN_LIST_OPS = {"ColumnList", &PEGTransformerFactory::InitializeColumnListTrampoline, - &PEGTransformerFactory::FinalizeColumnListTrampoline}; -static const TransformFrameOps INSERT_COLUMN_LIST_OPS = {"InsertColumnList", - &PEGTransformerFactory::InitializeInsertColumnListTrampoline, - &PEGTransformerFactory::FinalizeInsertColumnListTrampoline}; -static const TransformFrameOps INSERT_VALUES_OPS = {"InsertValues", - &PEGTransformerFactory::InitializeInsertValuesTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesTrampoline}; -static const TransformFrameOps SELECT_INSERT_VALUES_OPS = { - "SelectInsertValues", &PEGTransformerFactory::InitializeSelectInsertValuesTrampoline, - &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline}; -static const TransformFrameOps DEFAULT_VALUES_OPS = {"DefaultValues", - &PEGTransformerFactory::InitializeDefaultValuesTrampoline, - &PEGTransformerFactory::FinalizeDefaultValuesTrampoline}; -static const TransformFrameOps ON_CONFLICT_CLAUSE_OPS = {"OnConflictClause", - &PEGTransformerFactory::InitializeOnConflictClauseTrampoline, - &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline}; -static const TransformFrameOps ON_CONFLICT_TARGET_OPS = {"OnConflictTarget", - &PEGTransformerFactory::InitializeOnConflictTargetTrampoline, - &PEGTransformerFactory::FinalizeOnConflictTargetTrampoline}; -static const TransformFrameOps ON_CONFLICT_EXPRESSION_TARGET_OPS = { - "OnConflictExpressionTarget", &PEGTransformerFactory::InitializeOnConflictExpressionTargetTrampoline, - &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline}; -static const TransformFrameOps ON_CONFLICT_INDEX_TARGET_OPS = { - "OnConflictIndexTarget", &PEGTransformerFactory::InitializeOnConflictIndexTargetTrampoline, - &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline}; -static const TransformFrameOps ON_CONFLICT_ACTION_OPS = {"OnConflictAction", - &PEGTransformerFactory::InitializeOnConflictActionTrampoline, - &PEGTransformerFactory::FinalizeOnConflictActionTrampoline}; -static const TransformFrameOps ON_CONFLICT_UPDATE_OPS = {"OnConflictUpdate", - &PEGTransformerFactory::InitializeOnConflictUpdateTrampoline, - &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline}; -static const TransformFrameOps ON_CONFLICT_NOTHING_OPS = {"OnConflictNothing", - &PEGTransformerFactory::InitializeOnConflictNothingTrampoline, - &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline}; -static const TransformFrameOps RETURNING_CLAUSE_OPS = {"ReturningClause", - &PEGTransformerFactory::InitializeReturningClauseTrampoline, - &PEGTransformerFactory::FinalizeReturningClauseTrampoline}; -static const TransformFrameOps LOAD_STATEMENT_OPS = {"LoadStatement", - &PEGTransformerFactory::InitializeLoadStatementTrampoline, - &PEGTransformerFactory::FinalizeLoadStatementTrampoline}; -static const TransformFrameOps EXTENSION_ALIAS_OPS = {"ExtensionAlias", - &PEGTransformerFactory::InitializeExtensionAliasTrampoline, - &PEGTransformerFactory::FinalizeExtensionAliasTrampoline}; -static const TransformFrameOps INSTALL_STATEMENT_OPS = {"InstallStatement", - &PEGTransformerFactory::InitializeInstallStatementTrampoline, - &PEGTransformerFactory::FinalizeInstallStatementTrampoline}; -static const TransformFrameOps INSTALL_AND_LOAD_OPS = {"InstallAndLoad", - &PEGTransformerFactory::InitializeInstallAndLoadTrampoline, - &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline}; -static const TransformFrameOps UPDATE_EXTENSIONS_STATEMENT_OPS = { - "UpdateExtensionsStatement", &PEGTransformerFactory::InitializeUpdateExtensionsStatementTrampoline, - &PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline}; -static const TransformFrameOps FROM_SOURCE_OPS = {"FromSource", &PEGTransformerFactory::InitializeFromSourceTrampoline, - &PEGTransformerFactory::FinalizeFromSourceTrampoline}; -static const TransformFrameOps FROM_SOURCE_IDENTIFIER_OPS = { - "FromSourceIdentifier", &PEGTransformerFactory::InitializeFromSourceIdentifierTrampoline, - &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline}; -static const TransformFrameOps FROM_SOURCE_STRING_OPS = {"FromSourceString", - &PEGTransformerFactory::InitializeFromSourceStringTrampoline, - &PEGTransformerFactory::FinalizeFromSourceStringTrampoline}; -static const TransformFrameOps VERSION_NUMBER_OPS = {"VersionNumber", - &PEGTransformerFactory::InitializeVersionNumberTrampoline, - &PEGTransformerFactory::FinalizeVersionNumberTrampoline}; -static const TransformFrameOps EXTENSION_REPOSITORY_STATEMENT_OPS = { - "ExtensionRepositoryStatement", &PEGTransformerFactory::InitializeExtensionRepositoryStatementTrampoline, - &PEGTransformerFactory::FinalizeExtensionRepositoryStatementTrampoline}; -static const TransformFrameOps CREATE_EXTENSION_REPOSITORY_STMT_OPS = { - "CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializeCreateExtensionRepositoryStmtTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline}; -static const TransformFrameOps REPOSITORY_PREFIX_OPS = {"RepositoryPrefix", - &PEGTransformerFactory::InitializeRepositoryPrefixTrampoline, - &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline}; -static const TransformFrameOps REPOSITORY_PUBLIC_KEY_OPS = { - "RepositoryPublicKey", &PEGTransformerFactory::InitializeRepositoryPublicKeyTrampoline, - &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline}; -static const TransformFrameOps DROP_EXTENSION_REPOSITORY_STMT_OPS = { - "DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializeDropExtensionRepositoryStmtTrampoline, - &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline}; -static const TransformFrameOps TABLE_MATCH_RECOGNIZE_CLAUSE_OPS = { - "TableMatchRecognizeClause", &PEGTransformerFactory::InitializeTableMatchRecognizeClauseTrampoline, - &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline}; -static const TransformFrameOps MATCH_RECOGNIZE_BODY_OPS = { - "MatchRecognizeBody", &PEGTransformerFactory::InitializeMatchRecognizeBodyTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline}; -static const TransformFrameOps MATCH_RECOGNIZE_CLAUSE_OPS = { - "MatchRecognizeClause", &PEGTransformerFactory::InitializeMatchRecognizeClauseTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeClauseTrampoline}; -static const TransformFrameOps MRPARTITION_OPS = {"MRPartition", - &PEGTransformerFactory::InitializeMRPartitionTrampoline, - &PEGTransformerFactory::FinalizeMRPartitionTrampoline}; -static const TransformFrameOps MRORDER_BY_OPS = {"MROrderBy", &PEGTransformerFactory::InitializeMROrderByTrampoline, - &PEGTransformerFactory::FinalizeMROrderByTrampoline}; -static const TransformFrameOps MRMEASURES_OPS = {"MRMeasures", &PEGTransformerFactory::InitializeMRMeasuresTrampoline, - &PEGTransformerFactory::FinalizeMRMeasuresTrampoline}; -static const TransformFrameOps MRROWS_OPS = {"MRRows", &PEGTransformerFactory::InitializeMRRowsTrampoline, - &PEGTransformerFactory::FinalizeMRRowsTrampoline}; -static const TransformFrameOps MRSKIP_OPS = {"MRSkip", &PEGTransformerFactory::InitializeMRSkipTrampoline, - &PEGTransformerFactory::FinalizeMRSkipTrampoline}; -static const TransformFrameOps MRPATTERN_OPS = {"MRPattern", &PEGTransformerFactory::InitializeMRPatternTrampoline, - &PEGTransformerFactory::FinalizeMRPatternTrampoline}; -static const TransformFrameOps MRSUBSET_OPS = {"MRSubset", &PEGTransformerFactory::InitializeMRSubsetTrampoline, - &PEGTransformerFactory::FinalizeMRSubsetTrampoline}; -static const TransformFrameOps MRDEFINE_AUTO_OPS = {"MRDefineAuto", - &PEGTransformerFactory::InitializeMRDefineAutoTrampoline, - &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline}; -static const TransformFrameOps MRDEFINE_OPS = {"MRDefine", &PEGTransformerFactory::InitializeMRDefineTrampoline, - &PEGTransformerFactory::FinalizeMRDefineTrampoline}; -static const TransformFrameOps MEASURES_CLAUSE_OPS = {"MeasuresClause", - &PEGTransformerFactory::InitializeMeasuresClauseTrampoline, - &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline}; -static const TransformFrameOps MEASURES_ELEMENT_OPS = {"MeasuresElement", - &PEGTransformerFactory::InitializeMeasuresElementTrampoline, - &PEGTransformerFactory::FinalizeMeasuresElementTrampoline}; -static const TransformFrameOps MEASURE_SEMANTICS_OPS = {"MeasureSemantics", - &PEGTransformerFactory::InitializeMeasureSemanticsTrampoline, - &PEGTransformerFactory::FinalizeMeasureSemanticsTrampoline}; -static const TransformFrameOps RUNNING_SEMANTICS_OPS = {"RunningSemantics", - &PEGTransformerFactory::InitializeRunningSemanticsTrampoline, - &PEGTransformerFactory::FinalizeRunningSemanticsTrampoline}; -static const TransformFrameOps FINAL_SEMANTICS_OPS = {"FinalSemantics", - &PEGTransformerFactory::InitializeFinalSemanticsTrampoline, - &PEGTransformerFactory::FinalizeFinalSemanticsTrampoline}; -static const TransformFrameOps ROWS_PER_MATCH_OPS = {"RowsPerMatch", - &PEGTransformerFactory::InitializeRowsPerMatchTrampoline, - &PEGTransformerFactory::FinalizeRowsPerMatchTrampoline}; -static const TransformFrameOps ONE_ROW_PER_MATCH_OPS = {"OneRowPerMatch", - &PEGTransformerFactory::InitializeOneRowPerMatchTrampoline, - &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline}; -static const TransformFrameOps ALL_ROWS_PER_MATCH_OPS = {"AllRowsPerMatch", - &PEGTransformerFactory::InitializeAllRowsPerMatchTrampoline, - &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline}; -static const TransformFrameOps ALL_ROWS_EMPTY_MATCHES_OPS = { - "AllRowsEmptyMatches", &PEGTransformerFactory::InitializeAllRowsEmptyMatchesTrampoline, - &PEGTransformerFactory::FinalizeAllRowsEmptyMatchesTrampoline}; -static const TransformFrameOps SHOW_EMPTY_MATCHES_OPS = {"ShowEmptyMatches", - &PEGTransformerFactory::InitializeShowEmptyMatchesTrampoline, - &PEGTransformerFactory::FinalizeShowEmptyMatchesTrampoline}; -static const TransformFrameOps OMIT_EMPTY_MATCHES_OPS = {"OmitEmptyMatches", - &PEGTransformerFactory::InitializeOmitEmptyMatchesTrampoline, - &PEGTransformerFactory::FinalizeOmitEmptyMatchesTrampoline}; -static const TransformFrameOps WITH_UNMATCHED_ROWS_OPS = {"WithUnmatchedRows", - &PEGTransformerFactory::InitializeWithUnmatchedRowsTrampoline, - &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline}; -static const TransformFrameOps AFTER_MATCH_SKIP_OPS = {"AfterMatchSkip", - &PEGTransformerFactory::InitializeAfterMatchSkipTrampoline, - &PEGTransformerFactory::FinalizeAfterMatchSkipTrampoline}; -static const TransformFrameOps AFTER_MATCH_SKIP_TARGET_OPS = { - "AfterMatchSkipTarget", &PEGTransformerFactory::InitializeAfterMatchSkipTargetTrampoline, - &PEGTransformerFactory::FinalizeAfterMatchSkipTargetTrampoline}; -static const TransformFrameOps SKIP_TO_NEXT_ROW_OPS = {"SkipToNextRow", - &PEGTransformerFactory::InitializeSkipToNextRowTrampoline, - &PEGTransformerFactory::FinalizeSkipToNextRowTrampoline}; -static const TransformFrameOps SKIP_PAST_LAST_ROW_OPS = {"SkipPastLastRow", - &PEGTransformerFactory::InitializeSkipPastLastRowTrampoline, - &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline}; -static const TransformFrameOps SKIP_TO_FIRST_VAR_OPS = {"SkipToFirstVar", - &PEGTransformerFactory::InitializeSkipToFirstVarTrampoline, - &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline}; -static const TransformFrameOps SKIP_TO_LAST_VAR_OPS = {"SkipToLastVar", - &PEGTransformerFactory::InitializeSkipToLastVarTrampoline, - &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline}; -static const TransformFrameOps SKIP_TO_VAR_OPS = {"SkipToVar", &PEGTransformerFactory::InitializeSkipToVarTrampoline, - &PEGTransformerFactory::FinalizeSkipToVarTrampoline}; -static const TransformFrameOps PATTERN_CLAUSE_OPS = {"PatternClause", - &PEGTransformerFactory::InitializePatternClauseTrampoline, - &PEGTransformerFactory::FinalizePatternClauseTrampoline}; -static const TransformFrameOps ROW_PATTERN_OPS = {"RowPattern", &PEGTransformerFactory::InitializeRowPatternTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTrampoline}; -static const TransformFrameOps ROW_PATTERN_ALTERNATIVE_OPS = { - "RowPatternAlternative", &PEGTransformerFactory::InitializeRowPatternAlternativeTrampoline, - &PEGTransformerFactory::FinalizeRowPatternAlternativeTrampoline}; -static const TransformFrameOps ROW_PATTERN_TERM_OPS = {"RowPatternTerm", - &PEGTransformerFactory::InitializeRowPatternTermTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTermTrampoline}; -static const TransformFrameOps ROW_PATTERN_FACTOR_OPS = {"RowPatternFactor", - &PEGTransformerFactory::InitializeRowPatternFactorTrampoline, - &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline}; -static const TransformFrameOps ROW_PATTERN_PRIMARY_OPS = {"RowPatternPrimary", - &PEGTransformerFactory::InitializeRowPatternPrimaryTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPrimaryTrampoline}; -static const TransformFrameOps ROW_PATTERN_PERMUTE_OPS = {"RowPatternPermute", - &PEGTransformerFactory::InitializeRowPatternPermuteTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline}; -static const TransformFrameOps ROW_PATTERN_ANCHOR_OPS = {"RowPatternAnchor", - &PEGTransformerFactory::InitializeRowPatternAnchorTrampoline, - &PEGTransformerFactory::FinalizeRowPatternAnchorTrampoline}; -static const TransformFrameOps PATTERN_START_OPS = {"PatternStart", - &PEGTransformerFactory::InitializePatternStartTrampoline, - &PEGTransformerFactory::FinalizePatternStartTrampoline}; -static const TransformFrameOps PATTERN_END_OPS = {"PatternEnd", &PEGTransformerFactory::InitializePatternEndTrampoline, - &PEGTransformerFactory::FinalizePatternEndTrampoline}; -static const TransformFrameOps ROW_PATTERN_GROUP_OPS = {"RowPatternGroup", - &PEGTransformerFactory::InitializeRowPatternGroupTrampoline, - &PEGTransformerFactory::FinalizeRowPatternGroupTrampoline}; -static const TransformFrameOps ROW_PATTERN_EMPTY_OPS = {"RowPatternEmpty", - &PEGTransformerFactory::InitializeRowPatternEmptyTrampoline, - &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline}; -static const TransformFrameOps ROW_PATTERN_EXCLUSION_OPS = { - "RowPatternExclusion", &PEGTransformerFactory::InitializeRowPatternExclusionTrampoline, - &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline}; -static const TransformFrameOps ROW_PATTERN_LABEL_OPS = {"RowPatternLabel", - &PEGTransformerFactory::InitializeRowPatternLabelTrampoline, - &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline}; -static const TransformFrameOps ROW_PATTERN_QUANTIFIER_OPS = { - "RowPatternQuantifier", &PEGTransformerFactory::InitializeRowPatternQuantifierTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline}; -static const TransformFrameOps ROW_PATTERN_QUANTIFIER_KIND_OPS = { - "RowPatternQuantifierKind", &PEGTransformerFactory::InitializeRowPatternQuantifierKindTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierKindTrampoline}; -static const TransformFrameOps QUANTIFIER_RELUCTANT_OPS = { - "QuantifierReluctant", &PEGTransformerFactory::InitializeQuantifierReluctantTrampoline, - &PEGTransformerFactory::FinalizeQuantifierReluctantTrampoline}; -static const TransformFrameOps QUANTIFIER_STAR_OPS = {"QuantifierStar", - &PEGTransformerFactory::InitializeQuantifierStarTrampoline, - &PEGTransformerFactory::FinalizeQuantifierStarTrampoline}; -static const TransformFrameOps QUANTIFIER_PLUS_OPS = {"QuantifierPlus", - &PEGTransformerFactory::InitializeQuantifierPlusTrampoline, - &PEGTransformerFactory::FinalizeQuantifierPlusTrampoline}; -static const TransformFrameOps QUANTIFIER_OPTIONAL_OPS = { - "QuantifierOptional", &PEGTransformerFactory::InitializeQuantifierOptionalTrampoline, - &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline}; -static const TransformFrameOps QUANTIFIER_RANGE_OPS = {"QuantifierRange", - &PEGTransformerFactory::InitializeQuantifierRangeTrampoline, - &PEGTransformerFactory::FinalizeQuantifierRangeTrampoline}; -static const TransformFrameOps QUANTIFIER_BOUNDS_OPS = {"QuantifierBounds", - &PEGTransformerFactory::InitializeQuantifierBoundsTrampoline, - &PEGTransformerFactory::FinalizeQuantifierBoundsTrampoline}; -static const TransformFrameOps QUANTIFIER_MIN_MAX_OPS = {"QuantifierMinMax", - &PEGTransformerFactory::InitializeQuantifierMinMaxTrampoline, - &PEGTransformerFactory::FinalizeQuantifierMinMaxTrampoline}; -static const TransformFrameOps QUANTIFIER_MIN_OPS = {"QuantifierMin", - &PEGTransformerFactory::InitializeQuantifierMinTrampoline, - &PEGTransformerFactory::FinalizeQuantifierMinTrampoline}; -static const TransformFrameOps QUANTIFIER_MAX_OPS = {"QuantifierMax", - &PEGTransformerFactory::InitializeQuantifierMaxTrampoline, - &PEGTransformerFactory::FinalizeQuantifierMaxTrampoline}; -static const TransformFrameOps QUANTIFIER_EXACT_OPS = {"QuantifierExact", - &PEGTransformerFactory::InitializeQuantifierExactTrampoline, - &PEGTransformerFactory::FinalizeQuantifierExactTrampoline}; -static const TransformFrameOps SUBSET_CLAUSE_OPS = {"SubsetClause", - &PEGTransformerFactory::InitializeSubsetClauseTrampoline, - &PEGTransformerFactory::FinalizeSubsetClauseTrampoline}; -static const TransformFrameOps SUBSET_ELEMENT_OPS = {"SubsetElement", - &PEGTransformerFactory::InitializeSubsetElementTrampoline, - &PEGTransformerFactory::FinalizeSubsetElementTrampoline}; -static const TransformFrameOps DEFINE_CLAUSE_OPS = {"DefineClause", - &PEGTransformerFactory::InitializeDefineClauseTrampoline, - &PEGTransformerFactory::FinalizeDefineClauseTrampoline}; -static const TransformFrameOps DEFINE_ELEMENT_OPS = {"DefineElement", - &PEGTransformerFactory::InitializeDefineElementTrampoline, - &PEGTransformerFactory::FinalizeDefineElementTrampoline}; -static const TransformFrameOps MERGE_INTO_STATEMENT_OPS = { - "MergeIntoStatement", &PEGTransformerFactory::InitializeMergeIntoStatementTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline}; -static const TransformFrameOps MERGE_INTO_USING_CLAUSE_OPS = { - "MergeIntoUsingClause", &PEGTransformerFactory::InitializeMergeIntoUsingClauseTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline}; -static const TransformFrameOps MERGE_MATCH_OPS = {"MergeMatch", &PEGTransformerFactory::InitializeMergeMatchTrampoline, - &PEGTransformerFactory::FinalizeMergeMatchTrampoline}; -static const TransformFrameOps MATCHED_CLAUSE_OPS = {"MatchedClause", - &PEGTransformerFactory::InitializeMatchedClauseTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseTrampoline}; -static const TransformFrameOps MATCHED_CLAUSE_ACTION_OPS = { - "MatchedClauseAction", &PEGTransformerFactory::InitializeMatchedClauseActionTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseActionTrampoline}; -static const TransformFrameOps UPDATE_MATCH_CLAUSE_OPS = {"UpdateMatchClause", - &PEGTransformerFactory::InitializeUpdateMatchClauseTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline}; -static const TransformFrameOps UPDATE_MATCH_INFO_OPS = {"UpdateMatchInfo", - &PEGTransformerFactory::InitializeUpdateMatchInfoTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchInfoTrampoline}; -static const TransformFrameOps UPDATE_MATCH_SET_ACTION_OPS = { - "UpdateMatchSetAction", &PEGTransformerFactory::InitializeUpdateMatchSetActionTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline}; -static const TransformFrameOps UPDATE_BY_NAME_OR_POSITION_OPS = { - "UpdateByNameOrPosition", &PEGTransformerFactory::InitializeUpdateByNameOrPositionTrampoline, - &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline}; -static const TransformFrameOps DELETE_MATCH_CLAUSE_OPS = {"DeleteMatchClause", - &PEGTransformerFactory::InitializeDeleteMatchClauseTrampoline, - &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline}; -static const TransformFrameOps INSERT_MATCH_CLAUSE_OPS = {"InsertMatchClause", - &PEGTransformerFactory::InitializeInsertMatchClauseTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline}; -static const TransformFrameOps INSERT_MATCH_INFO_OPS = {"InsertMatchInfo", - &PEGTransformerFactory::InitializeInsertMatchInfoTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchInfoTrampoline}; -static const TransformFrameOps INSERT_DEFAULT_VALUES_OPS = { - "InsertDefaultValues", &PEGTransformerFactory::InitializeInsertDefaultValuesTrampoline, - &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline}; -static const TransformFrameOps INSERT_BY_NAME_OR_POSITION_OPS = { - "InsertByNameOrPosition", &PEGTransformerFactory::InitializeInsertByNameOrPositionTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline}; -static const TransformFrameOps INSERT_VALUES_LIST_OPS = {"InsertValuesList", - &PEGTransformerFactory::InitializeInsertValuesListTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesListTrampoline}; -static const TransformFrameOps DO_NOTHING_MATCH_CLAUSE_OPS = { - "DoNothingMatchClause", &PEGTransformerFactory::InitializeDoNothingMatchClauseTrampoline, - &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline}; -static const TransformFrameOps ERROR_MATCH_CLAUSE_OPS = {"ErrorMatchClause", - &PEGTransformerFactory::InitializeErrorMatchClauseTrampoline, - &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline}; -static const TransformFrameOps UPDATE_MATCH_SET_CLAUSE_OPS = { - "UpdateMatchSetClause", &PEGTransformerFactory::InitializeUpdateMatchSetClauseTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetClauseTrampoline}; -static const TransformFrameOps UPDATE_MATCH_SET_INFO_OPS = { - "UpdateMatchSetInfo", &PEGTransformerFactory::InitializeUpdateMatchSetInfoTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline}; -static const TransformFrameOps AND_EXPRESSION_OPS = {"AndExpression", - &PEGTransformerFactory::InitializeAndExpressionTrampoline, - &PEGTransformerFactory::FinalizeAndExpressionTrampoline}; -static const TransformFrameOps NOT_MATCHED_CLAUSE_OPS = {"NotMatchedClause", - &PEGTransformerFactory::InitializeNotMatchedClauseTrampoline, - &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline}; -static const TransformFrameOps BY_SOURCE_OR_TARGET_OPS = {"BySourceOrTarget", - &PEGTransformerFactory::InitializeBySourceOrTargetTrampoline, - &PEGTransformerFactory::FinalizeBySourceOrTargetTrampoline}; -static const TransformFrameOps BY_SOURCE_OPS = {"BySource", &PEGTransformerFactory::InitializeBySourceTrampoline, - &PEGTransformerFactory::FinalizeBySourceTrampoline}; -static const TransformFrameOps BY_TARGET_OPS = {"ByTarget", &PEGTransformerFactory::InitializeByTargetTrampoline, - &PEGTransformerFactory::FinalizeByTargetTrampoline}; -static const TransformFrameOps PIVOT_STATEMENT_OPS = {"PivotStatement", - &PEGTransformerFactory::InitializePivotStatementTrampoline, - &PEGTransformerFactory::FinalizePivotStatementTrampoline}; -static const TransformFrameOps PIVOT_ON_OPS = {"PivotOn", &PEGTransformerFactory::InitializePivotOnTrampoline, - &PEGTransformerFactory::FinalizePivotOnTrampoline}; -static const TransformFrameOps PIVOT_USING_OPS = {"PivotUsing", &PEGTransformerFactory::InitializePivotUsingTrampoline, - &PEGTransformerFactory::FinalizePivotUsingTrampoline}; -static const TransformFrameOps PIVOT_COLUMN_LIST_OPS = {"PivotColumnList", - &PEGTransformerFactory::InitializePivotColumnListTrampoline, - &PEGTransformerFactory::FinalizePivotColumnListTrampoline}; -static const TransformFrameOps PIVOT_COLUMN_ENTRY_OPS = {"PivotColumnEntry", - &PEGTransformerFactory::InitializePivotColumnEntryTrampoline, - &PEGTransformerFactory::FinalizePivotColumnEntryTrampoline}; -static const TransformFrameOps PIVOT_COLUMN_EXPRESSION_OPS = { - "PivotColumnExpression", &PEGTransformerFactory::InitializePivotColumnExpressionTrampoline, - &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline}; -static const TransformFrameOps PIVOT_COLUMN_SUBQUERY_OPS = { - "PivotColumnSubquery", &PEGTransformerFactory::InitializePivotColumnSubqueryTrampoline, - &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline}; -static const TransformFrameOps UNPIVOT_STATEMENT_OPS = {"UnpivotStatement", - &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, - &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline}; -static const TransformFrameOps INTO_NAME_VALUES_OPS = {"IntoNameValues", - &PEGTransformerFactory::InitializeIntoNameValuesTrampoline, - &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline}; -static const TransformFrameOps OPTIONAL_PARENS_NAME_LIST_OPS = { - "OptionalParensNameList", &PEGTransformerFactory::InitializeOptionalParensNameListTrampoline, - &PEGTransformerFactory::FinalizeOptionalParensNameListTrampoline}; -static const TransformFrameOps PARENTHESIZED_NAME_LIST_OPS = { - "ParenthesizedNameList", &PEGTransformerFactory::InitializeParenthesizedNameListTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline}; -static const TransformFrameOps BARE_NAME_LIST_OPS = {"BareNameList", - &PEGTransformerFactory::InitializeBareNameListTrampoline, - &PEGTransformerFactory::FinalizeBareNameListTrampoline}; -static const TransformFrameOps INCLUDE_OR_EXCLUDE_NULLS_OPS = { - "IncludeOrExcludeNulls", &PEGTransformerFactory::InitializeIncludeOrExcludeNullsTrampoline, - &PEGTransformerFactory::FinalizeIncludeOrExcludeNullsTrampoline}; -static const TransformFrameOps INCLUDE_NULLS_OPS = {"IncludeNulls", - &PEGTransformerFactory::InitializeIncludeNullsTrampoline, - &PEGTransformerFactory::FinalizeIncludeNullsTrampoline}; -static const TransformFrameOps EXCLUDE_NULLS_OPS = {"ExcludeNulls", - &PEGTransformerFactory::InitializeExcludeNullsTrampoline, - &PEGTransformerFactory::FinalizeExcludeNullsTrampoline}; -static const TransformFrameOps UNPIVOT_HEADER_OPS = {"UnpivotHeader", - &PEGTransformerFactory::InitializeUnpivotHeaderTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderTrampoline}; -static const TransformFrameOps UNPIVOT_HEADER_SINGLE_OPS = { - "UnpivotHeaderSingle", &PEGTransformerFactory::InitializeUnpivotHeaderSingleTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline}; -static const TransformFrameOps UNPIVOT_HEADER_LIST_OPS = {"UnpivotHeaderList", - &PEGTransformerFactory::InitializeUnpivotHeaderListTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline}; -static const TransformFrameOps PRAGMA_STATEMENT_OPS = {"PragmaStatement", - &PEGTransformerFactory::InitializePragmaStatementTrampoline, - &PEGTransformerFactory::FinalizePragmaStatementTrampoline}; -static const TransformFrameOps PRAGMA_ASSIGN_OR_FUNCTION_OPS = { - "PragmaAssignOrFunction", &PEGTransformerFactory::InitializePragmaAssignOrFunctionTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignOrFunctionTrampoline}; -static const TransformFrameOps PRAGMA_ASSIGN_OPS = {"PragmaAssign", - &PEGTransformerFactory::InitializePragmaAssignTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignTrampoline}; -static const TransformFrameOps PRAGMA_FUNCTION_OPS = {"PragmaFunction", - &PEGTransformerFactory::InitializePragmaFunctionTrampoline, - &PEGTransformerFactory::FinalizePragmaFunctionTrampoline}; -static const TransformFrameOps PRAGMA_PARAMETERS_OPS = {"PragmaParameters", - &PEGTransformerFactory::InitializePragmaParametersTrampoline, - &PEGTransformerFactory::FinalizePragmaParametersTrampoline}; -static const TransformFrameOps PREPARE_STATEMENT_OPS = {"PrepareStatement", - &PEGTransformerFactory::InitializePrepareStatementTrampoline, - &PEGTransformerFactory::FinalizePrepareStatementTrampoline}; -static const TransformFrameOps TYPE_LIST_OPS = {"TypeList", &PEGTransformerFactory::InitializeTypeListTrampoline, - &PEGTransformerFactory::FinalizeTypeListTrampoline}; -static const TransformFrameOps SELECT_STATEMENT_OPS = {"SelectStatement", - &PEGTransformerFactory::InitializeSelectStatementTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementTrampoline}; -static const TransformFrameOps SELECT_STATEMENT_INTERNAL_OPS = { - "SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline}; -static const TransformFrameOps SELECT_SET_OP_CHAIN_OPS = {"SelectSetOpChain", - &PEGTransformerFactory::InitializeSelectSetOpChainTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline}; -static const TransformFrameOps SELECT_SET_OP_CHAIN_TAIL_OPS = { - "SelectSetOpChainTail", &PEGTransformerFactory::InitializeSelectSetOpChainTailTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline}; -static const TransformFrameOps INTERSECT_CHAIN_OPS = {"IntersectChain", - &PEGTransformerFactory::InitializeIntersectChainTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTrampoline}; -static const TransformFrameOps INTERSECT_CHAIN_TAIL_OPS = { - "IntersectChainTail", &PEGTransformerFactory::InitializeIntersectChainTailTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline}; -static const TransformFrameOps SET_INTERSECT_CLAUSE_OPS = { - "SetIntersectClause", &PEGTransformerFactory::InitializeSetIntersectClauseTrampoline, - &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline}; -static const TransformFrameOps SELECT_ATOM_OPS = {"SelectAtom", &PEGTransformerFactory::InitializeSelectAtomTrampoline, - &PEGTransformerFactory::FinalizeSelectAtomTrampoline}; -static const TransformFrameOps SELECT_PARENS_OPS = {"SelectParens", - &PEGTransformerFactory::InitializeSelectParensTrampoline, - &PEGTransformerFactory::FinalizeSelectParensTrampoline}; -static const TransformFrameOps SETOP_CLAUSE_OPS = {"SetopClause", - &PEGTransformerFactory::InitializeSetopClauseTrampoline, - &PEGTransformerFactory::FinalizeSetopClauseTrampoline}; -static const TransformFrameOps SETOP_TYPE_OPS = {"SetopType", &PEGTransformerFactory::InitializeSetopTypeTrampoline, - &PEGTransformerFactory::FinalizeSetopTypeTrampoline}; -static const TransformFrameOps SETOP_UNION_OPS = {"SetopUnion", &PEGTransformerFactory::InitializeSetopUnionTrampoline, - &PEGTransformerFactory::FinalizeSetopUnionTrampoline}; -static const TransformFrameOps SETOP_EXCEPT_OPS = {"SetopExcept", - &PEGTransformerFactory::InitializeSetopExceptTrampoline, - &PEGTransformerFactory::FinalizeSetopExceptTrampoline}; -static const TransformFrameOps SELECT_STATEMENT_TYPE_OPS = { - "SelectStatementType", &PEGTransformerFactory::InitializeSelectStatementTypeTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementTypeTrampoline}; -static const TransformFrameOps RESULT_MODIFIERS_OPS = {"ResultModifiers", - &PEGTransformerFactory::InitializeResultModifiersTrampoline, - &PEGTransformerFactory::FinalizeResultModifiersTrampoline}; -static const TransformFrameOps LIMIT_OFFSET_OPS = {"LimitOffset", - &PEGTransformerFactory::InitializeLimitOffsetTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetTrampoline}; -static const TransformFrameOps LIMIT_OFFSET_CLAUSE_OPS = {"LimitOffsetClause", - &PEGTransformerFactory::InitializeLimitOffsetClauseTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline}; -static const TransformFrameOps OFFSET_LIMIT_CLAUSE_OPS = {"OffsetLimitClause", - &PEGTransformerFactory::InitializeOffsetLimitClauseTrampoline, - &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline}; -static const TransformFrameOps OFFSET_FETCH_CLAUSE_OPS = {"OffsetFetchClause", - &PEGTransformerFactory::InitializeOffsetFetchClauseTrampoline, - &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline}; -static const TransformFrameOps FETCH_OFFSET_CLAUSE_OPS = {"FetchOffsetClause", - &PEGTransformerFactory::InitializeFetchOffsetClauseTrampoline, - &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline}; -static const TransformFrameOps FETCH_ONLY_CLAUSE_OPS = {"FetchOnlyClause", - &PEGTransformerFactory::InitializeFetchOnlyClauseTrampoline, - &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline}; -static const TransformFrameOps TABLE_STATEMENT_OPS = {"TableStatement", - &PEGTransformerFactory::InitializeTableStatementTrampoline, - &PEGTransformerFactory::FinalizeTableStatementTrampoline}; -static const TransformFrameOps OPTIONAL_PARENS_SIMPLE_SELECT_OPS = { - "OptionalParensSimpleSelect", &PEGTransformerFactory::InitializeOptionalParensSimpleSelectTrampoline, - &PEGTransformerFactory::FinalizeOptionalParensSimpleSelectTrampoline}; -static const TransformFrameOps SIMPLE_SELECT_PARENS_OPS = { - "SimpleSelectParens", &PEGTransformerFactory::InitializeSimpleSelectParensTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline}; -static const TransformFrameOps SIMPLE_SELECT_OPS = {"SimpleSelect", - &PEGTransformerFactory::InitializeSimpleSelectTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectTrampoline}; -static const TransformFrameOps SELECT_FROM_OPS = {"SelectFrom", &PEGTransformerFactory::InitializeSelectFromTrampoline, - &PEGTransformerFactory::FinalizeSelectFromTrampoline}; -static const TransformFrameOps SELECT_FROM_CLAUSE_OPS = {"SelectFromClause", - &PEGTransformerFactory::InitializeSelectFromClauseTrampoline, - &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline}; -static const TransformFrameOps FROM_SELECT_CLAUSE_OPS = {"FromSelectClause", - &PEGTransformerFactory::InitializeFromSelectClauseTrampoline, - &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline}; -static const TransformFrameOps WITH_STATEMENT_OPS = {"WithStatement", - &PEGTransformerFactory::InitializeWithStatementTrampoline, - &PEGTransformerFactory::FinalizeWithStatementTrampoline}; -static const TransformFrameOps CTEBODY_OPS = {"CTEBody", &PEGTransformerFactory::InitializeCTEBodyTrampoline, - &PEGTransformerFactory::FinalizeCTEBodyTrampoline}; -static const TransformFrameOps CTESELECT_BODY_OPS = {"CTESelectBody", - &PEGTransformerFactory::InitializeCTESelectBodyTrampoline, - &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline}; -static const TransformFrameOps CTEDMLBODY_OPS = {"CTEDMLBody", &PEGTransformerFactory::InitializeCTEDMLBodyTrampoline, - &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline}; -static const TransformFrameOps USING_KEY_OPS = {"UsingKey", &PEGTransformerFactory::InitializeUsingKeyTrampoline, - &PEGTransformerFactory::FinalizeUsingKeyTrampoline}; -static const TransformFrameOps MATERIALIZED_OPS = {"Materialized", - &PEGTransformerFactory::InitializeMaterializedTrampoline, - &PEGTransformerFactory::FinalizeMaterializedTrampoline}; -static const TransformFrameOps WITH_CLAUSE_OPS = {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, - &PEGTransformerFactory::FinalizeWithClauseTrampoline}; -static const TransformFrameOps SELECT_CLAUSE_OPS = {"SelectClause", - &PEGTransformerFactory::InitializeSelectClauseTrampoline, - &PEGTransformerFactory::FinalizeSelectClauseTrampoline}; -static const TransformFrameOps TARGET_LIST_OPS = {"TargetList", &PEGTransformerFactory::InitializeTargetListTrampoline, - &PEGTransformerFactory::FinalizeTargetListTrampoline}; -static const TransformFrameOps COLUMN_ALIASES_OPS = {"ColumnAliases", - &PEGTransformerFactory::InitializeColumnAliasesTrampoline, - &PEGTransformerFactory::FinalizeColumnAliasesTrampoline}; -static const TransformFrameOps DISTINCT_CLAUSE_OPS = {"DistinctClause", - &PEGTransformerFactory::InitializeDistinctClauseTrampoline, - &PEGTransformerFactory::FinalizeDistinctClauseTrampoline}; -static const TransformFrameOps DISTINCT_ALL_OPS = {"DistinctAll", - &PEGTransformerFactory::InitializeDistinctAllTrampoline, - &PEGTransformerFactory::FinalizeDistinctAllTrampoline}; -static const TransformFrameOps DISTINCT_ON_OPS = {"DistinctOn", &PEGTransformerFactory::InitializeDistinctOnTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTrampoline}; -static const TransformFrameOps DISTINCT_ON_TARGETS_OPS = {"DistinctOnTargets", - &PEGTransformerFactory::InitializeDistinctOnTargetsTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline}; -static const TransformFrameOps INNER_TABLE_REF_OPS = {"InnerTableRef", - &PEGTransformerFactory::InitializeInnerTableRefTrampoline, - &PEGTransformerFactory::FinalizeInnerTableRefTrampoline}; -static const TransformFrameOps TABLE_REF_OPS = {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, - &PEGTransformerFactory::FinalizeTableRefTrampoline}; -static const TransformFrameOps TABLE_SUBQUERY_OPS = {"TableSubquery", - &PEGTransformerFactory::InitializeTableSubqueryTrampoline, - &PEGTransformerFactory::FinalizeTableSubqueryTrampoline}; -static const TransformFrameOps BASE_TABLE_REF_OPS = {"BaseTableRef", - &PEGTransformerFactory::InitializeBaseTableRefTrampoline, - &PEGTransformerFactory::FinalizeBaseTableRefTrampoline}; -static const TransformFrameOps TABLE_ALIAS_COLON_OPS = {"TableAliasColon", - &PEGTransformerFactory::InitializeTableAliasColonTrampoline, - &PEGTransformerFactory::FinalizeTableAliasColonTrampoline}; -static const TransformFrameOps VALUES_REF_OPS = {"ValuesRef", &PEGTransformerFactory::InitializeValuesRefTrampoline, - &PEGTransformerFactory::FinalizeValuesRefTrampoline}; -static const TransformFrameOps PARENS_TABLE_REF_OPS = {"ParensTableRef", - &PEGTransformerFactory::InitializeParensTableRefTrampoline, - &PEGTransformerFactory::FinalizeParensTableRefTrampoline}; -static const TransformFrameOps JOIN_OR_PIVOT_OPS = {"JoinOrPivot", - &PEGTransformerFactory::InitializeJoinOrPivotTrampoline, - &PEGTransformerFactory::FinalizeJoinOrPivotTrampoline}; -static const TransformFrameOps TABLE_PIVOT_CLAUSE_OPS = {"TablePivotClause", - &PEGTransformerFactory::InitializeTablePivotClauseTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline}; -static const TransformFrameOps TABLE_PIVOT_CLAUSE_BODY_OPS = { - "TablePivotClauseBody", &PEGTransformerFactory::InitializeTablePivotClauseBodyTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline}; -static const TransformFrameOps PIVOT_GROUP_BY_LIST_OPS = {"PivotGroupByList", - &PEGTransformerFactory::InitializePivotGroupByListTrampoline, - &PEGTransformerFactory::FinalizePivotGroupByListTrampoline}; -static const TransformFrameOps TABLE_UNPIVOT_CLAUSE_OPS = { - "TableUnpivotClause", &PEGTransformerFactory::InitializeTableUnpivotClauseTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline}; -static const TransformFrameOps TABLE_UNPIVOT_CLAUSE_BODY_OPS = { - "TableUnpivotClauseBody", &PEGTransformerFactory::InitializeTableUnpivotClauseBodyTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline}; -static const TransformFrameOps PIVOT_HEADER_OPS = {"PivotHeader", - &PEGTransformerFactory::InitializePivotHeaderTrampoline, - &PEGTransformerFactory::FinalizePivotHeaderTrampoline}; -static const TransformFrameOps PIVOT_VALUE_LIST_OPS = {"PivotValueList", - &PEGTransformerFactory::InitializePivotValueListTrampoline, - &PEGTransformerFactory::FinalizePivotValueListTrampoline}; -static const TransformFrameOps PIVOT_VALUE_TARGET_OPS = {"PivotValueTarget", - &PEGTransformerFactory::InitializePivotValueTargetTrampoline, - &PEGTransformerFactory::FinalizePivotValueTargetTrampoline}; -static const TransformFrameOps PIVOT_ENUM_TARGET_OPS = {"PivotEnumTarget", - &PEGTransformerFactory::InitializePivotEnumTargetTrampoline, - &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline}; -static const TransformFrameOps PIVOT_LIST_TARGET_OPS = {"PivotListTarget", - &PEGTransformerFactory::InitializePivotListTargetTrampoline, - &PEGTransformerFactory::FinalizePivotListTargetTrampoline}; -static const TransformFrameOps UNPIVOT_VALUE_LIST_OPS = {"UnpivotValueList", - &PEGTransformerFactory::InitializeUnpivotValueListTrampoline, - &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline}; -static const TransformFrameOps PIVOT_TARGET_LIST_OPS = {"PivotTargetList", - &PEGTransformerFactory::InitializePivotTargetListTrampoline, - &PEGTransformerFactory::FinalizePivotTargetListTrampoline}; -static const TransformFrameOps UNPIVOT_TARGET_LIST_OPS = {"UnpivotTargetList", - &PEGTransformerFactory::InitializeUnpivotTargetListTrampoline, - &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline}; -static const TransformFrameOps LATERAL_OPS = {"Lateral", &PEGTransformerFactory::InitializeLateralTrampoline, - &PEGTransformerFactory::FinalizeLateralTrampoline}; -static const TransformFrameOps BASE_TABLE_NAME_OPS = {"BaseTableName", - &PEGTransformerFactory::InitializeBaseTableNameTrampoline, - &PEGTransformerFactory::FinalizeBaseTableNameTrampoline}; -static const TransformFrameOps UNQUALIFIED_BASE_TABLE_NAME_OPS = { - "UnqualifiedBaseTableName", &PEGTransformerFactory::InitializeUnqualifiedBaseTableNameTrampoline, - &PEGTransformerFactory::FinalizeUnqualifiedBaseTableNameTrampoline}; -static const TransformFrameOps QUALIFIED_TABLE_NAME_OPS = { - "QualifiedTableName", &PEGTransformerFactory::InitializeQualifiedTableNameTrampoline, - &PEGTransformerFactory::FinalizeQualifiedTableNameTrampoline}; -static const TransformFrameOps SCHEMA_RESERVED_TABLE_OPS = { - "SchemaReservedTable", &PEGTransformerFactory::InitializeSchemaReservedTableTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableTrampoline}; -static const TransformFrameOps CATALOG_RESERVED_SCHEMA_TABLE_OPS = { - "CatalogReservedSchemaTable", &PEGTransformerFactory::InitializeCatalogReservedSchemaTableTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableTrampoline}; -static const TransformFrameOps TABLE_FUNCTION_OPS = {"TableFunction", - &PEGTransformerFactory::InitializeTableFunctionTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionTrampoline}; -static const TransformFrameOps TABLE_FUNCTION_LATERAL_OPT_OPS = { - "TableFunctionLateralOpt", &PEGTransformerFactory::InitializeTableFunctionLateralOptTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline}; -static const TransformFrameOps TABLE_FUNCTION_ALIAS_COLON_OPS = { - "TableFunctionAliasColon", &PEGTransformerFactory::InitializeTableFunctionAliasColonTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline}; -static const TransformFrameOps WITH_ORDINALITY_OPS = {"WithOrdinality", - &PEGTransformerFactory::InitializeWithOrdinalityTrampoline, - &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline}; -static const TransformFrameOps QUALIFIED_TABLE_FUNCTION_OPS = { - "QualifiedTableFunction", &PEGTransformerFactory::InitializeQualifiedTableFunctionTrampoline, - &PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline}; -static const TransformFrameOps TABLE_FUNCTION_ARGUMENTS_OPS = { - "TableFunctionArguments", &PEGTransformerFactory::InitializeTableFunctionArgumentsTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline}; -static const TransformFrameOps FUNCTION_ARGUMENT_OPS = {"FunctionArgument", - &PEGTransformerFactory::InitializeFunctionArgumentTrampoline, - &PEGTransformerFactory::FinalizeFunctionArgumentTrampoline}; -static const TransformFrameOps NAMED_FUNCTION_ARGUMENT_OPS = { - "NamedFunctionArgument", &PEGTransformerFactory::InitializeNamedFunctionArgumentTrampoline, - &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline}; -static const TransformFrameOps POSITIONAL_FUNCTION_ARGUMENT_OPS = { - "PositionalFunctionArgument", &PEGTransformerFactory::InitializePositionalFunctionArgumentTrampoline, - &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline}; -static const TransformFrameOps NAMED_PARAMETER_OPS = {"NamedParameter", - &PEGTransformerFactory::InitializeNamedParameterTrampoline, - &PEGTransformerFactory::FinalizeNamedParameterTrampoline}; -static const TransformFrameOps TABLE_ALIAS_OPS = {"TableAlias", &PEGTransformerFactory::InitializeTableAliasTrampoline, - &PEGTransformerFactory::FinalizeTableAliasTrampoline}; -static const TransformFrameOps TABLE_ALIAS_AS_OPS = {"TableAliasAs", - &PEGTransformerFactory::InitializeTableAliasAsTrampoline, - &PEGTransformerFactory::FinalizeTableAliasAsTrampoline}; -static const TransformFrameOps TABLE_ALIAS_WITHOUT_AS_OPS = { - "TableAliasWithoutAs", &PEGTransformerFactory::InitializeTableAliasWithoutAsTrampoline, - &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline}; -static const TransformFrameOps AT_CLAUSE_OPS = {"AtClause", &PEGTransformerFactory::InitializeAtClauseTrampoline, - &PEGTransformerFactory::FinalizeAtClauseTrampoline}; -static const TransformFrameOps AT_SPECIFIER_OPS = {"AtSpecifier", - &PEGTransformerFactory::InitializeAtSpecifierTrampoline, - &PEGTransformerFactory::FinalizeAtSpecifierTrampoline}; -static const TransformFrameOps AT_UNIT_OPS = {"AtUnit", &PEGTransformerFactory::InitializeAtUnitTrampoline, - &PEGTransformerFactory::FinalizeAtUnitTrampoline}; -static const TransformFrameOps VERSION_AT_UNIT_OPS = {"VersionAtUnit", - &PEGTransformerFactory::InitializeVersionAtUnitTrampoline, - &PEGTransformerFactory::FinalizeVersionAtUnitTrampoline}; -static const TransformFrameOps TIMESTAMP_AT_UNIT_OPS = {"TimestampAtUnit", - &PEGTransformerFactory::InitializeTimestampAtUnitTrampoline, - &PEGTransformerFactory::FinalizeTimestampAtUnitTrampoline}; -static const TransformFrameOps JOIN_CLAUSE_OPS = {"JoinClause", &PEGTransformerFactory::InitializeJoinClauseTrampoline, - &PEGTransformerFactory::FinalizeJoinClauseTrampoline}; -static const TransformFrameOps NEAREST_JOIN_CLAUSE_OPS = {"NearestJoinClause", - &PEGTransformerFactory::InitializeNearestJoinClauseTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinClauseTrampoline}; -static const TransformFrameOps NEAREST_JOIN_ALIASED_OPS = { - "NearestJoinAliased", &PEGTransformerFactory::InitializeNearestJoinAliasedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline}; -static const TransformFrameOps NEAREST_JOIN_BARE_OPS = {"NearestJoinBare", - &PEGTransformerFactory::InitializeNearestJoinBareTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline}; -static const TransformFrameOps NEAREST_BARE_TABLE_REF_OPS = { - "NearestBareTableRef", &PEGTransformerFactory::InitializeNearestBareTableRefTrampoline, - &PEGTransformerFactory::FinalizeNearestBareTableRefTrampoline}; -static const TransformFrameOps NEAREST_VALUES_REF_OPS = {"NearestValuesRef", - &PEGTransformerFactory::InitializeNearestValuesRefTrampoline, - &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline}; -static const TransformFrameOps NEAREST_TABLE_FUNCTION_OPS = { - "NearestTableFunction", &PEGTransformerFactory::InitializeNearestTableFunctionTrampoline, - &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline}; -static const TransformFrameOps NEAREST_TABLE_SUBQUERY_OPS = { - "NearestTableSubquery", &PEGTransformerFactory::InitializeNearestTableSubqueryTrampoline, - &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline}; -static const TransformFrameOps NEAREST_BASE_TABLE_REF_OPS = { - "NearestBaseTableRef", &PEGTransformerFactory::InitializeNearestBaseTableRefTrampoline, - &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline}; -static const TransformFrameOps NEAREST_PARENS_TABLE_REF_OPS = { - "NearestParensTableRef", &PEGTransformerFactory::InitializeNearestParensTableRefTrampoline, - &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline}; -static const TransformFrameOps APPROX_OR_EXACT_OPS = {"ApproxOrExact", - &PEGTransformerFactory::InitializeApproxOrExactTrampoline, - &PEGTransformerFactory::FinalizeApproxOrExactTrampoline}; -static const TransformFrameOps NEAREST_APPROX_OPS = {"NearestApprox", - &PEGTransformerFactory::InitializeNearestApproxTrampoline, - &PEGTransformerFactory::FinalizeNearestApproxTrampoline}; -static const TransformFrameOps NEAREST_EXACT_OPS = {"NearestExact", - &PEGTransformerFactory::InitializeNearestExactTrampoline, - &PEGTransformerFactory::FinalizeNearestExactTrampoline}; -static const TransformFrameOps DISTANCE_OR_SIMILARITY_OPS = { - "DistanceOrSimilarity", &PEGTransformerFactory::InitializeDistanceOrSimilarityTrampoline, - &PEGTransformerFactory::FinalizeDistanceOrSimilarityTrampoline}; -static const TransformFrameOps NEAREST_DISTANCE_OPS = {"NearestDistance", - &PEGTransformerFactory::InitializeNearestDistanceTrampoline, - &PEGTransformerFactory::FinalizeNearestDistanceTrampoline}; -static const TransformFrameOps NEAREST_SIMILARITY_OPS = {"NearestSimilarity", - &PEGTransformerFactory::InitializeNearestSimilarityTrampoline, - &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline}; -static const TransformFrameOps REGULAR_JOIN_CLAUSE_OPS = {"RegularJoinClause", - &PEGTransformerFactory::InitializeRegularJoinClauseTrampoline, - &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline}; -static const TransformFrameOps JOIN_BY_CLAUSE_OPS = {"JoinByClause", - &PEGTransformerFactory::InitializeJoinByClauseTrampoline, - &PEGTransformerFactory::FinalizeJoinByClauseTrampoline}; -static const TransformFrameOps ASOF_OPS = {"Asof", &PEGTransformerFactory::InitializeAsofTrampoline, - &PEGTransformerFactory::FinalizeAsofTrampoline}; -static const TransformFrameOps JOIN_WITHOUT_ON_CLAUSE_OPS = { - "JoinWithoutOnClause", &PEGTransformerFactory::InitializeJoinWithoutOnClauseTrampoline, - &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline}; -static const TransformFrameOps JOIN_QUALIFIER_OPS = {"JoinQualifier", - &PEGTransformerFactory::InitializeJoinQualifierTrampoline, - &PEGTransformerFactory::FinalizeJoinQualifierTrampoline}; -static const TransformFrameOps ON_CLAUSE_OPS = {"OnClause", &PEGTransformerFactory::InitializeOnClauseTrampoline, - &PEGTransformerFactory::FinalizeOnClauseTrampoline}; -static const TransformFrameOps USING_CLAUSE_OPS = {"UsingClause", - &PEGTransformerFactory::InitializeUsingClauseTrampoline, - &PEGTransformerFactory::FinalizeUsingClauseTrampoline}; -static const TransformFrameOps USING_COLUMN_NAME_OPS = {"UsingColumnName", - &PEGTransformerFactory::InitializeUsingColumnNameTrampoline, - &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline}; -static const TransformFrameOps JOIN_TYPE_OPS = {"JoinType", &PEGTransformerFactory::InitializeJoinTypeTrampoline, - &PEGTransformerFactory::FinalizeJoinTypeTrampoline}; -static const TransformFrameOps JOIN_PREFIX_OPS = {"JoinPrefix", &PEGTransformerFactory::InitializeJoinPrefixTrampoline, - &PEGTransformerFactory::FinalizeJoinPrefixTrampoline}; -static const TransformFrameOps CROSS_JOIN_PREFIX_OPS = {"CrossJoinPrefix", - &PEGTransformerFactory::InitializeCrossJoinPrefixTrampoline, - &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline}; -static const TransformFrameOps NATURAL_JOIN_PREFIX_OPS = {"NaturalJoinPrefix", - &PEGTransformerFactory::InitializeNaturalJoinPrefixTrampoline, - &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline}; -static const TransformFrameOps POSITIONAL_JOIN_PREFIX_OPS = { - "PositionalJoinPrefix", &PEGTransformerFactory::InitializePositionalJoinPrefixTrampoline, - &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline}; -static const TransformFrameOps FULL_JOIN_OPS = {"FullJoin", &PEGTransformerFactory::InitializeFullJoinTrampoline, - &PEGTransformerFactory::FinalizeFullJoinTrampoline}; -static const TransformFrameOps LEFT_JOIN_OPS = {"LeftJoin", &PEGTransformerFactory::InitializeLeftJoinTrampoline, - &PEGTransformerFactory::FinalizeLeftJoinTrampoline}; -static const TransformFrameOps RIGHT_JOIN_OPS = {"RightJoin", &PEGTransformerFactory::InitializeRightJoinTrampoline, - &PEGTransformerFactory::FinalizeRightJoinTrampoline}; -static const TransformFrameOps SEMI_JOIN_OPS = {"SemiJoin", &PEGTransformerFactory::InitializeSemiJoinTrampoline, - &PEGTransformerFactory::FinalizeSemiJoinTrampoline}; -static const TransformFrameOps ANTI_JOIN_OPS = {"AntiJoin", &PEGTransformerFactory::InitializeAntiJoinTrampoline, - &PEGTransformerFactory::FinalizeAntiJoinTrampoline}; -static const TransformFrameOps INNER_JOIN_OPS = {"InnerJoin", &PEGTransformerFactory::InitializeInnerJoinTrampoline, - &PEGTransformerFactory::FinalizeInnerJoinTrampoline}; -static const TransformFrameOps FROM_CLAUSE_OPS = {"FromClause", &PEGTransformerFactory::InitializeFromClauseTrampoline, - &PEGTransformerFactory::FinalizeFromClauseTrampoline}; -static const TransformFrameOps WHERE_CLAUSE_OPS = {"WhereClause", - &PEGTransformerFactory::InitializeWhereClauseTrampoline, - &PEGTransformerFactory::FinalizeWhereClauseTrampoline}; -static const TransformFrameOps GROUP_BY_CLAUSE_OPS = {"GroupByClause", - &PEGTransformerFactory::InitializeGroupByClauseTrampoline, - &PEGTransformerFactory::FinalizeGroupByClauseTrampoline}; -static const TransformFrameOps HAVING_CLAUSE_OPS = {"HavingClause", - &PEGTransformerFactory::InitializeHavingClauseTrampoline, - &PEGTransformerFactory::FinalizeHavingClauseTrampoline}; -static const TransformFrameOps QUALIFY_CLAUSE_OPS = {"QualifyClause", - &PEGTransformerFactory::InitializeQualifyClauseTrampoline, - &PEGTransformerFactory::FinalizeQualifyClauseTrampoline}; -static const TransformFrameOps SAMPLE_CLAUSE_OPS = {"SampleClause", - &PEGTransformerFactory::InitializeSampleClauseTrampoline, - &PEGTransformerFactory::FinalizeSampleClauseTrampoline}; -static const TransformFrameOps SELECT_SAMPLE_CLAUSE_OPS = { - "SelectSampleClause", &PEGTransformerFactory::InitializeSelectSampleClauseTrampoline, - &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline}; -static const TransformFrameOps WINDOW_CLAUSE_OPS = {"WindowClause", - &PEGTransformerFactory::InitializeWindowClauseTrampoline, - &PEGTransformerFactory::FinalizeWindowClauseTrampoline}; -static const TransformFrameOps WINDOW_DEFINITION_OPS = {"WindowDefinition", - &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, - &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline}; -static const TransformFrameOps SAMPLE_ENTRY_OPS = {"SampleEntry", - &PEGTransformerFactory::InitializeSampleEntryTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryTrampoline}; -static const TransformFrameOps SAMPLE_ENTRY_COUNT_OPS = {"SampleEntryCount", - &PEGTransformerFactory::InitializeSampleEntryCountTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline}; -static const TransformFrameOps SAMPLE_ENTRY_FUNCTION_OPS = { - "SampleEntryFunction", &PEGTransformerFactory::InitializeSampleEntryFunctionTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline}; -static const TransformFrameOps SAMPLE_FUNCTION_OPS = {"SampleFunction", - &PEGTransformerFactory::InitializeSampleFunctionTrampoline, - &PEGTransformerFactory::FinalizeSampleFunctionTrampoline}; -static const TransformFrameOps SAMPLE_PROPERTIES_OPS = {"SampleProperties", - &PEGTransformerFactory::InitializeSamplePropertiesTrampoline, - &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline}; -static const TransformFrameOps REPEATABLE_SAMPLE_OPS = {"RepeatableSample", - &PEGTransformerFactory::InitializeRepeatableSampleTrampoline, - &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline}; -static const TransformFrameOps SAMPLE_SEED_OPS = {"SampleSeed", &PEGTransformerFactory::InitializeSampleSeedTrampoline, - &PEGTransformerFactory::FinalizeSampleSeedTrampoline}; -static const TransformFrameOps SAMPLE_COUNT_OPS = {"SampleCount", - &PEGTransformerFactory::InitializeSampleCountTrampoline, - &PEGTransformerFactory::FinalizeSampleCountTrampoline}; -static const TransformFrameOps SAMPLE_VALUE_OPS = {"SampleValue", - &PEGTransformerFactory::InitializeSampleValueTrampoline, - &PEGTransformerFactory::FinalizeSampleValueTrampoline}; -static const TransformFrameOps SAMPLE_UNIT_OPS = {"SampleUnit", &PEGTransformerFactory::InitializeSampleUnitTrampoline, - &PEGTransformerFactory::FinalizeSampleUnitTrampoline}; -static const TransformFrameOps SAMPLE_PERCENTAGE_OPS = {"SamplePercentage", - &PEGTransformerFactory::InitializeSamplePercentageTrampoline, - &PEGTransformerFactory::FinalizeSamplePercentageTrampoline}; -static const TransformFrameOps SAMPLE_ROWS_OPS = {"SampleRows", &PEGTransformerFactory::InitializeSampleRowsTrampoline, - &PEGTransformerFactory::FinalizeSampleRowsTrampoline}; -static const TransformFrameOps GROUP_BY_EXPRESSIONS_OPS = { - "GroupByExpressions", &PEGTransformerFactory::InitializeGroupByExpressionsTrampoline, - &PEGTransformerFactory::FinalizeGroupByExpressionsTrampoline}; -static const TransformFrameOps GROUP_BY_ALL_OPS = {"GroupByAll", &PEGTransformerFactory::InitializeGroupByAllTrampoline, - &PEGTransformerFactory::FinalizeGroupByAllTrampoline}; -static const TransformFrameOps GROUP_BY_LIST_OPS = {"GroupByList", - &PEGTransformerFactory::InitializeGroupByListTrampoline, - &PEGTransformerFactory::FinalizeGroupByListTrampoline}; -static const TransformFrameOps GROUP_BY_EXPRESSION_OPS = {"GroupByExpression", - &PEGTransformerFactory::InitializeGroupByExpressionTrampoline, - &PEGTransformerFactory::FinalizeGroupByExpressionTrampoline}; -static const TransformFrameOps GROUP_BY_BASE_EXPRESSION_OPS = { - "GroupByBaseExpression", &PEGTransformerFactory::InitializeGroupByBaseExpressionTrampoline, - &PEGTransformerFactory::FinalizeGroupByBaseExpressionTrampoline}; -static const TransformFrameOps EMPTY_GROUPING_ITEM_OPS = {"EmptyGroupingItem", - &PEGTransformerFactory::InitializeEmptyGroupingItemTrampoline, - &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline}; -static const TransformFrameOps CUBE_OR_ROLLUP_CLAUSE_OPS = { - "CubeOrRollupClause", &PEGTransformerFactory::InitializeCubeOrRollupClauseTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline}; -static const TransformFrameOps CUBE_OR_ROLLUP_OPS = {"CubeOrRollup", - &PEGTransformerFactory::InitializeCubeOrRollupTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline}; -static const TransformFrameOps CUBE_KEYWORD_OPS = {"CubeKeyword", - &PEGTransformerFactory::InitializeCubeKeywordTrampoline, - &PEGTransformerFactory::FinalizeCubeKeywordTrampoline}; -static const TransformFrameOps ROLLUP_KEYWORD_OPS = {"RollupKeyword", - &PEGTransformerFactory::InitializeRollupKeywordTrampoline, - &PEGTransformerFactory::FinalizeRollupKeywordTrampoline}; -static const TransformFrameOps GROUPING_SETS_CLAUSE_OPS = { - "GroupingSetsClause", &PEGTransformerFactory::InitializeGroupingSetsClauseTrampoline, - &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline}; -static const TransformFrameOps SUBQUERY_REFERENCE_OPS = {"SubqueryReference", - &PEGTransformerFactory::InitializeSubqueryReferenceTrampoline, - &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline}; -static const TransformFrameOps ORDER_BY_EXPRESSION_OPS = {"OrderByExpression", - &PEGTransformerFactory::InitializeOrderByExpressionTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline}; -static const TransformFrameOps DESC_OR_ASC_OPS = {"DescOrAsc", &PEGTransformerFactory::InitializeDescOrAscTrampoline, - &PEGTransformerFactory::FinalizeDescOrAscTrampoline}; -static const TransformFrameOps DESCENDING_ORDER_OPS = {"DescendingOrder", - &PEGTransformerFactory::InitializeDescendingOrderTrampoline, - &PEGTransformerFactory::FinalizeDescendingOrderTrampoline}; -static const TransformFrameOps ASCENDING_ORDER_OPS = {"AscendingOrder", - &PEGTransformerFactory::InitializeAscendingOrderTrampoline, - &PEGTransformerFactory::FinalizeAscendingOrderTrampoline}; -static const TransformFrameOps NULLS_FIRST_OR_LAST_OPS = {"NullsFirstOrLast", - &PEGTransformerFactory::InitializeNullsFirstOrLastTrampoline, - &PEGTransformerFactory::FinalizeNullsFirstOrLastTrampoline}; -static const TransformFrameOps NULLS_FIRST_OPS = {"NullsFirst", &PEGTransformerFactory::InitializeNullsFirstTrampoline, - &PEGTransformerFactory::FinalizeNullsFirstTrampoline}; -static const TransformFrameOps NULLS_LAST_OPS = {"NullsLast", &PEGTransformerFactory::InitializeNullsLastTrampoline, - &PEGTransformerFactory::FinalizeNullsLastTrampoline}; -static const TransformFrameOps ORDER_BY_CLAUSE_OPS = {"OrderByClause", - &PEGTransformerFactory::InitializeOrderByClauseTrampoline, - &PEGTransformerFactory::FinalizeOrderByClauseTrampoline}; -static const TransformFrameOps ORDER_BY_EXPRESSIONS_OPS = { - "OrderByExpressions", &PEGTransformerFactory::InitializeOrderByExpressionsTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionsTrampoline}; -static const TransformFrameOps ORDER_BY_EXPRESSION_LIST_OPS = { - "OrderByExpressionList", &PEGTransformerFactory::InitializeOrderByExpressionListTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline}; -static const TransformFrameOps ORDER_BY_ALL_OPS = {"OrderByAll", &PEGTransformerFactory::InitializeOrderByAllTrampoline, - &PEGTransformerFactory::FinalizeOrderByAllTrampoline}; -static const TransformFrameOps LIMIT_CLAUSE_OPS = {"LimitClause", - &PEGTransformerFactory::InitializeLimitClauseTrampoline, - &PEGTransformerFactory::FinalizeLimitClauseTrampoline}; -static const TransformFrameOps OFFSET_CLAUSE_OPS = {"OffsetClause", - &PEGTransformerFactory::InitializeOffsetClauseTrampoline, - &PEGTransformerFactory::FinalizeOffsetClauseTrampoline}; -static const TransformFrameOps OFFSET_VALUE_OPS = {"OffsetValue", - &PEGTransformerFactory::InitializeOffsetValueTrampoline, - &PEGTransformerFactory::FinalizeOffsetValueTrampoline}; -static const TransformFrameOps LIMIT_VALUE_OPS = {"LimitValue", &PEGTransformerFactory::InitializeLimitValueTrampoline, - &PEGTransformerFactory::FinalizeLimitValueTrampoline}; -static const TransformFrameOps LIMIT_ALL_OPS = {"LimitAll", &PEGTransformerFactory::InitializeLimitAllTrampoline, - &PEGTransformerFactory::FinalizeLimitAllTrampoline}; -static const TransformFrameOps LIMIT_LITERAL_PERCENT_OPS = { - "LimitLiteralPercent", &PEGTransformerFactory::InitializeLimitLiteralPercentTrampoline, - &PEGTransformerFactory::FinalizeLimitLiteralPercentTrampoline}; -static const TransformFrameOps LIMIT_EXPRESSION_OPS = {"LimitExpression", - &PEGTransformerFactory::InitializeLimitExpressionTrampoline, - &PEGTransformerFactory::FinalizeLimitExpressionTrampoline}; -static const TransformFrameOps FETCH_CLAUSE_OPS = {"FetchClause", - &PEGTransformerFactory::InitializeFetchClauseTrampoline, - &PEGTransformerFactory::FinalizeFetchClauseTrampoline}; -static const TransformFrameOps FETCH_CLAUSE_WITHOUT_VALUE_OPS = { - "FetchClauseWithoutValue", &PEGTransformerFactory::InitializeFetchClauseWithoutValueTrampoline, - &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline}; -static const TransformFrameOps FETCH_CLAUSE_WITH_VALUE_OPS = { - "FetchClauseWithValue", &PEGTransformerFactory::InitializeFetchClauseWithValueTrampoline, - &PEGTransformerFactory::FinalizeFetchClauseWithValueTrampoline}; -static const TransformFrameOps FETCH_VALUE_OPS = {"FetchValue", &PEGTransformerFactory::InitializeFetchValueTrampoline, - &PEGTransformerFactory::FinalizeFetchValueTrampoline}; -static const TransformFrameOps ALIASED_EXPRESSION_OPS = {"AliasedExpression", - &PEGTransformerFactory::InitializeAliasedExpressionTrampoline, - &PEGTransformerFactory::FinalizeAliasedExpressionTrampoline}; -static const TransformFrameOps COL_ID_EXPRESSION_OPS = {"ColIdExpression", - &PEGTransformerFactory::InitializeColIdExpressionTrampoline, - &PEGTransformerFactory::FinalizeColIdExpressionTrampoline}; -static const TransformFrameOps EXPRESSION_AS_COLLABEL_OPS = { - "ExpressionAsCollabel", &PEGTransformerFactory::InitializeExpressionAsCollabelTrampoline, - &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline}; -static const TransformFrameOps EXPRESSION_OPT_IDENTIFIER_OPS = { - "ExpressionOptIdentifier", &PEGTransformerFactory::InitializeExpressionOptIdentifierTrampoline, - &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline}; -static const TransformFrameOps VALUES_CLAUSE_OPS = {"ValuesClause", - &PEGTransformerFactory::InitializeValuesClauseTrampoline, - &PEGTransformerFactory::FinalizeValuesClauseTrampoline}; -static const TransformFrameOps VALUES_EXPRESSIONS_OPS = {"ValuesExpressions", - &PEGTransformerFactory::InitializeValuesExpressionsTrampoline, - &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline}; -static const TransformFrameOps SET_STATEMENT_OPS = {"SetStatement", - &PEGTransformerFactory::InitializeSetStatementTrampoline, - &PEGTransformerFactory::FinalizeSetStatementTrampoline}; -static const TransformFrameOps SET_KEYWORD_STATEMENT_OPS = { - "SetKeywordStatement", &PEGTransformerFactory::InitializeSetKeywordStatementTrampoline, - &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline}; -static const TransformFrameOps VARIABLE_ASSIGNMENT_OPS = { - "VariableAssignment", &PEGTransformerFactory::InitializeVariableAssignmentTrampoline, - &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline}; -static const TransformFrameOps SET_ASSIGNMENT_OR_TIME_ZONE_OPS = { - "SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializeSetAssignmentOrTimeZoneTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentOrTimeZoneTrampoline}; -static const TransformFrameOps RESET_STATEMENT_OPS = {"ResetStatement", - &PEGTransformerFactory::InitializeResetStatementTrampoline, - &PEGTransformerFactory::FinalizeResetStatementTrampoline}; -static const TransformFrameOps RESET_TARGET_OPS = {"ResetTarget", - &PEGTransformerFactory::InitializeResetTargetTrampoline, - &PEGTransformerFactory::FinalizeResetTargetTrampoline}; -static const TransformFrameOps RESET_TIME_ZONE_OPS = {"ResetTimeZone", - &PEGTransformerFactory::InitializeResetTimeZoneTrampoline, - &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline}; -static const TransformFrameOps RESET_VARIABLE_OR_SETTING_OPS = { - "ResetVariableOrSetting", &PEGTransformerFactory::InitializeResetVariableOrSettingTrampoline, - &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline}; -static const TransformFrameOps SET_SCHEMA_OPS = {"SetSchema", &PEGTransformerFactory::InitializeSetSchemaTrampoline, - &PEGTransformerFactory::FinalizeSetSchemaTrampoline}; -static const TransformFrameOps STANDARD_ASSIGNMENT_OPS = { - "StandardAssignment", &PEGTransformerFactory::InitializeStandardAssignmentTrampoline, - &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline}; -static const TransformFrameOps SET_VARIABLE_OR_SETTING_OPS = { - "SetVariableOrSetting", &PEGTransformerFactory::InitializeSetVariableOrSettingTrampoline, - &PEGTransformerFactory::FinalizeSetVariableOrSettingTrampoline}; -static const TransformFrameOps SET_TIME_ZONE_OPS = {"SetTimeZone", - &PEGTransformerFactory::InitializeSetTimeZoneTrampoline, - &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline}; -static const TransformFrameOps ZONE_VALUE_OPS = {"ZoneValue", &PEGTransformerFactory::InitializeZoneValueTrampoline, - &PEGTransformerFactory::FinalizeZoneValueTrampoline}; -static const TransformFrameOps ZONE_LOCAL_OPS = {"ZoneLocal", &PEGTransformerFactory::InitializeZoneLocalTrampoline, - &PEGTransformerFactory::FinalizeZoneLocalTrampoline}; -static const TransformFrameOps ZONE_DEFAULT_OPS = {"ZoneDefault", - &PEGTransformerFactory::InitializeZoneDefaultTrampoline, - &PEGTransformerFactory::FinalizeZoneDefaultTrampoline}; -static const TransformFrameOps ZONE_STRING_LITERAL_OPS = {"ZoneStringLiteral", - &PEGTransformerFactory::InitializeZoneStringLiteralTrampoline, - &PEGTransformerFactory::FinalizeZoneStringLiteralTrampoline}; -static const TransformFrameOps ZONE_IDENTIFIER_OPS = {"ZoneIdentifier", - &PEGTransformerFactory::InitializeZoneIdentifierTrampoline, - &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline}; -static const TransformFrameOps ZONE_INTERVAL_WITH_INTERVAL_OPS = { - "ZoneIntervalWithInterval", &PEGTransformerFactory::InitializeZoneIntervalWithIntervalTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline}; -static const TransformFrameOps ZONE_INTERVAL_WITH_PRECISION_OPS = { - "ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializeZoneIntervalWithPrecisionTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline}; -static const TransformFrameOps SET_SETTING_OPS = {"SetSetting", &PEGTransformerFactory::InitializeSetSettingTrampoline, - &PEGTransformerFactory::FinalizeSetSettingTrampoline}; -static const TransformFrameOps SET_VARIABLE_OPS = {"SetVariable", - &PEGTransformerFactory::InitializeSetVariableTrampoline, - &PEGTransformerFactory::FinalizeSetVariableTrampoline}; -static const TransformFrameOps VARIABLE_SCOPE_OPS = {"VariableScope", - &PEGTransformerFactory::InitializeVariableScopeTrampoline, - &PEGTransformerFactory::FinalizeVariableScopeTrampoline}; -static const TransformFrameOps SETTING_SCOPE_OPS = {"SettingScope", - &PEGTransformerFactory::InitializeSettingScopeTrampoline, - &PEGTransformerFactory::FinalizeSettingScopeTrampoline}; -static const TransformFrameOps LOCAL_SCOPE_OPS = {"LocalScope", &PEGTransformerFactory::InitializeLocalScopeTrampoline, - &PEGTransformerFactory::FinalizeLocalScopeTrampoline}; -static const TransformFrameOps SESSION_SCOPE_OPS = {"SessionScope", - &PEGTransformerFactory::InitializeSessionScopeTrampoline, - &PEGTransformerFactory::FinalizeSessionScopeTrampoline}; -static const TransformFrameOps GLOBAL_SCOPE_OPS = {"GlobalScope", - &PEGTransformerFactory::InitializeGlobalScopeTrampoline, - &PEGTransformerFactory::FinalizeGlobalScopeTrampoline}; -static const TransformFrameOps SET_ASSIGNMENT_OPS = {"SetAssignment", - &PEGTransformerFactory::InitializeSetAssignmentTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentTrampoline}; -static const TransformFrameOps VARIABLE_LIST_OPS = {"VariableList", - &PEGTransformerFactory::InitializeVariableListTrampoline, - &PEGTransformerFactory::FinalizeVariableListTrampoline}; -static const TransformFrameOps TRANSACTION_STATEMENT_OPS = { - "TransactionStatement", &PEGTransformerFactory::InitializeTransactionStatementTrampoline, - &PEGTransformerFactory::FinalizeTransactionStatementTrampoline}; -static const TransformFrameOps BEGIN_TRANSACTION_OPS = {"BeginTransaction", - &PEGTransformerFactory::InitializeBeginTransactionTrampoline, - &PEGTransformerFactory::FinalizeBeginTransactionTrampoline}; -static const TransformFrameOps ROLLBACK_TRANSACTION_OPS = { - "RollbackTransaction", &PEGTransformerFactory::InitializeRollbackTransactionTrampoline, - &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline}; -static const TransformFrameOps COMMIT_TRANSACTION_OPS = {"CommitTransaction", - &PEGTransformerFactory::InitializeCommitTransactionTrampoline, - &PEGTransformerFactory::FinalizeCommitTransactionTrampoline}; -static const TransformFrameOps READ_OR_WRITE_OPS = {"ReadOrWrite", - &PEGTransformerFactory::InitializeReadOrWriteTrampoline, - &PEGTransformerFactory::FinalizeReadOrWriteTrampoline}; -static const TransformFrameOps READ_ONLY_OR_READ_WRITE_OPS = { - "ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializeReadOnlyOrReadWriteTrampoline, - &PEGTransformerFactory::FinalizeReadOnlyOrReadWriteTrampoline}; -static const TransformFrameOps READ_ONLY_OPS = {"ReadOnly", &PEGTransformerFactory::InitializeReadOnlyTrampoline, - &PEGTransformerFactory::FinalizeReadOnlyTrampoline}; -static const TransformFrameOps READ_WRITE_OPS = {"ReadWrite", &PEGTransformerFactory::InitializeReadWriteTrampoline, - &PEGTransformerFactory::FinalizeReadWriteTrampoline}; -static const TransformFrameOps UPDATE_STATEMENT_OPS = {"UpdateStatement", - &PEGTransformerFactory::InitializeUpdateStatementTrampoline, - &PEGTransformerFactory::FinalizeUpdateStatementTrampoline}; -static const TransformFrameOps UPDATE_TARGET_OPS = {"UpdateTarget", - &PEGTransformerFactory::InitializeUpdateTargetTrampoline, - &PEGTransformerFactory::FinalizeUpdateTargetTrampoline}; -static const TransformFrameOps BASE_TABLE_SET_OPS = {"BaseTableSet", - &PEGTransformerFactory::InitializeBaseTableSetTrampoline, - &PEGTransformerFactory::FinalizeBaseTableSetTrampoline}; -static const TransformFrameOps BASE_TABLE_ALIAS_SET_OPS = { - "BaseTableAliasSet", &PEGTransformerFactory::InitializeBaseTableAliasSetTrampoline, - &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline}; -static const TransformFrameOps UPDATE_ALIAS_OPS = {"UpdateAlias", - &PEGTransformerFactory::InitializeUpdateAliasTrampoline, - &PEGTransformerFactory::FinalizeUpdateAliasTrampoline}; -static const TransformFrameOps UPDATE_SET_CLAUSE_LIST_OPS = { - "UpdateSetClauseList", &PEGTransformerFactory::InitializeUpdateSetClauseListTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline}; -static const TransformFrameOps UPDATE_SET_CLAUSE_OPS = {"UpdateSetClause", - &PEGTransformerFactory::InitializeUpdateSetClauseTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseTrampoline}; -static const TransformFrameOps UPDATE_SET_TUPLE_OPS = {"UpdateSetTuple", - &PEGTransformerFactory::InitializeUpdateSetTupleTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline}; -static const TransformFrameOps UPDATE_SET_ELEMENT_OPS = {"UpdateSetElement", - &PEGTransformerFactory::InitializeUpdateSetElementTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline}; -static const TransformFrameOps UPDATE_SET_COLUMN_TARGET_OPS = { - "UpdateSetColumnTarget", &PEGTransformerFactory::InitializeUpdateSetColumnTargetTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline}; -static const TransformFrameOps USE_STATEMENT_OPS = {"UseStatement", - &PEGTransformerFactory::InitializeUseStatementTrampoline, - &PEGTransformerFactory::FinalizeUseStatementTrampoline}; -static const TransformFrameOps USE_TARGET_OPS = {"UseTarget", &PEGTransformerFactory::InitializeUseTargetTrampoline, - &PEGTransformerFactory::FinalizeUseTargetTrampoline}; -static const TransformFrameOps SCHEMA_NAME_AS_USE_TARGET_OPS = { - "SchemaNameAsUseTarget", &PEGTransformerFactory::InitializeSchemaNameAsUseTargetTrampoline, - &PEGTransformerFactory::FinalizeSchemaNameAsUseTargetTrampoline}; -static const TransformFrameOps CATALOG_NAME_AS_USE_TARGET_OPS = { - "CatalogNameAsUseTarget", &PEGTransformerFactory::InitializeCatalogNameAsUseTargetTrampoline, - &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline}; -static const TransformFrameOps USE_TARGET_CATALOG_SCHEMA_OPS = { - "UseTargetCatalogSchema", &PEGTransformerFactory::InitializeUseTargetCatalogSchemaTrampoline, - &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline}; -static const TransformFrameOps DOT_IDENTIFIER_OPS = {"DotIdentifier", - &PEGTransformerFactory::InitializeDotIdentifierTrampoline, - &PEGTransformerFactory::FinalizeDotIdentifierTrampoline}; -static const TransformFrameOps VACUUM_STATEMENT_OPS = {"VacuumStatement", - &PEGTransformerFactory::InitializeVacuumStatementTrampoline, - &PEGTransformerFactory::FinalizeVacuumStatementTrampoline}; -static const TransformFrameOps VACUUM_OPTIONS_OPS = {"VacuumOptions", - &PEGTransformerFactory::InitializeVacuumOptionsTrampoline, - &PEGTransformerFactory::FinalizeVacuumOptionsTrampoline}; -static const TransformFrameOps VACUUM_PARENS_OPTIONS_OPS = { - "VacuumParensOptions", &PEGTransformerFactory::InitializeVacuumParensOptionsTrampoline, - &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline}; -static const TransformFrameOps VACUUM_LEGACY_OPTIONS_OPS = { - "VacuumLegacyOptions", &PEGTransformerFactory::InitializeVacuumLegacyOptionsTrampoline, - &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline}; -static const TransformFrameOps VACUUM_OPTION_OPS = {"VacuumOption", - &PEGTransformerFactory::InitializeVacuumOptionTrampoline, - &PEGTransformerFactory::FinalizeVacuumOptionTrampoline}; -static const TransformFrameOps OPT_ANALYZE_OPS = {"OptAnalyze", &PEGTransformerFactory::InitializeOptAnalyzeTrampoline, - &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline}; -static const TransformFrameOps OPT_FULL_OPS = {"OptFull", &PEGTransformerFactory::InitializeOptFullTrampoline, - &PEGTransformerFactory::FinalizeOptFullTrampoline}; -static const TransformFrameOps OPT_FREEZE_OPS = {"OptFreeze", &PEGTransformerFactory::InitializeOptFreezeTrampoline, - &PEGTransformerFactory::FinalizeOptFreezeTrampoline}; -static const TransformFrameOps OPT_VERBOSE_OPS = {"OptVerbose", &PEGTransformerFactory::InitializeOptVerboseTrampoline, - &PEGTransformerFactory::FinalizeOptVerboseTrampoline}; -static const TransformFrameOps NAME_LIST_OPS = {"NameList", &PEGTransformerFactory::InitializeNameListTrampoline, - &PEGTransformerFactory::FinalizeNameListTrampoline}; +static const TransformChildPlan FRAME_CHILDREN_0[] = {{PEGRuleId::AlterOptions, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_0 = {FRAME_CHILDREN_0, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_1 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 0, nullptr}}; +static const TransformChildPlan FRAME_CHILDREN_1[] = {{PEGRuleId::AlterTableOptions, + TransformChildKind::LIST, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_2 = {FRAME_CHILDREN_1, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_2[] = {{PEGRuleId::AlterSchemaOptions, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_3 = {FRAME_CHILDREN_2, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_3[] = {{PEGRuleId::TopLevelConstraint, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_4 = {FRAME_CHILDREN_3, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_4[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ConstraintName, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_5 = {FRAME_CHILDREN_4, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_5[] = {{PEGRuleId::AddColumnEntry, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_6 = {FRAME_CHILDREN_5, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_6[] = {{PEGRuleId::ColumnConstraint, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::GeneratedColumn, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DottedIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_7 = {FRAME_CHILDREN_6, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_7[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NestedColumnName, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_8 = {FRAME_CHILDREN_7, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_8[] = {{PEGRuleId::AlterColumnEntry, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NestedColumnName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_9 = {FRAME_CHILDREN_8, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_9[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NestedColumnName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_10 = {FRAME_CHILDREN_9, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_10[] = {{PEGRuleId::IdentifierDot, + TransformChildKind::OPTIONAL_REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_11 = {FRAME_CHILDREN_10, 1, 1, true, 0, {}}; +static const TransformFramePlan FRAME_PLAN_12 = {nullptr, 0, 0, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_11[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_13 = {FRAME_CHILDREN_11, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_12[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 3, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_14 = {FRAME_CHILDREN_12, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_13[] = {{PEGRuleId::OrderByExpressions, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_15 = {FRAME_CHILDREN_13, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_14[] = {{PEGRuleId::RelOptionList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_16 = {FRAME_CHILDREN_14, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_15[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_17 = {FRAME_CHILDREN_15, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_16[] = {{PEGRuleId::DropOrSet, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_18 = {FRAME_CHILDREN_16, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_19 = { + nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR), + 0, false, true, 0, nullptr}}; +static const TransformChildPlan FRAME_CHILDREN_17[] = {{PEGRuleId::UsingExpression, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnCollation, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_20 = {FRAME_CHILDREN_17, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_18[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_21 = {FRAME_CHILDREN_18, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_19[] = {{PEGRuleId::RenameAlter, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_22 = {FRAME_CHILDREN_19, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_20[] = {{PEGRuleId::AlterSequenceOptions, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedSequenceName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_23 = {FRAME_CHILDREN_20, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_21[] = {{PEGRuleId::SchemaQualification, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_24 = {FRAME_CHILDREN_21, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_22[] = {{PEGRuleId::RenameAlter, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_25 = {FRAME_CHILDREN_22, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_23[] = {{PEGRuleId::SequenceOption, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_26 = {FRAME_CHILDREN_23, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_24[] = {{PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_27 = {FRAME_CHILDREN_24, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_25[] = {{PEGRuleId::AnalyzeTarget, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnalyzeVerbose, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnalyzeKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_28 = {FRAME_CHILDREN_25, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_26[] = {{PEGRuleId::NameList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_29 = {FRAME_CHILDREN_26, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_27[] = {{PEGRuleId::AttachOptions, + TransformChildKind::OPTIONAL, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DatabasePath, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 2, + 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_30 = {FRAME_CHILDREN_27, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_28[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_31 = {FRAME_CHILDREN_28, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_29[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_32 = {FRAME_CHILDREN_29, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_30[] = {{PEGRuleId::GenericCopyOptionList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_33 = {FRAME_CHILDREN_30, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_31[] = {{PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_34 = {FRAME_CHILDREN_31, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_32[] = {{PEGRuleId::CheckpointForce, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_35 = {FRAME_CHILDREN_32, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_33[] = {{PEGRuleId::CommentValue, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentTarget, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentOnType, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_36 = {FRAME_CHILDREN_33, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_34[] = {{PEGRuleId::StringLiteralIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_37 = {FRAME_CHILDREN_34, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_35[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_38 = {FRAME_CHILDREN_35, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_36[] = {{PEGRuleId::ArrayBounds, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeVariations, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_39 = {FRAME_CHILDREN_36, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_37[] = {{PEGRuleId::TypeModifiers, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_40 = {FRAME_CHILDREN_37, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_38[] = {{PEGRuleId::TypeModifiers, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTypeName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_41 = {FRAME_CHILDREN_38, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_39[] = {{PEGRuleId::IntervalToIntervalAsType, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_42 = {FRAME_CHILDREN_39, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_40[] = {{PEGRuleId::Interval, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_43 = {FRAME_CHILDREN_40, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_44 = {nullptr, 0, 1, false, 0, {0, 0, false, false, 0, nullptr}}; +static const TransformChildPlan FRAME_CHILDREN_41[] = {{PEGRuleId::MonthKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::YearKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_45 = {FRAME_CHILDREN_41, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_42[] = {{PEGRuleId::HourKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DayKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_46 = {FRAME_CHILDREN_42, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_43[] = {{PEGRuleId::MinuteKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DayKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_47 = {FRAME_CHILDREN_43, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_44[] = {{PEGRuleId::SecondKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DayKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_48 = {FRAME_CHILDREN_44, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_45[] = {{PEGRuleId::MinuteKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::HourKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_49 = {FRAME_CHILDREN_45, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_46[] = {{PEGRuleId::SecondKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::HourKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_50 = {FRAME_CHILDREN_46, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_47[] = {{PEGRuleId::SecondKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MinuteKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_51 = {FRAME_CHILDREN_47, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_48[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_52 = {FRAME_CHILDREN_48, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_49[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_53 = {FRAME_CHILDREN_49, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_54 = { + nullptr, + 0, + 1, + false, + 0, + {0, + ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR) | + ParseResultTypeBit(ParseResultType::CHOICE) | ParseResultTypeBit(ParseResultType::LIST), + false, true, 0, nullptr}}; +static const TransformChildPlan FRAME_CHILDREN_50[] = {{PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_55 = {FRAME_CHILDREN_50, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_51[] = {{PEGRuleId::SchemaQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_56 = {FRAME_CHILDREN_51, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_52[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_57 = {FRAME_CHILDREN_52, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_53[] = {{PEGRuleId::ColIdTypeList, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_58 = {FRAME_CHILDREN_53, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_54[] = {{PEGRuleId::NestedType, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_59 = {FRAME_CHILDREN_54, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_55[] = {{PEGRuleId::ColIdTypeList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_60 = {FRAME_CHILDREN_55, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_56[] = {{PEGRuleId::ColIdType, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_61 = {FRAME_CHILDREN_56, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_57[] = {{PEGRuleId::NestedType, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_62 = {FRAME_CHILDREN_57, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_58[] = {{PEGRuleId::NestedType, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_63 = {FRAME_CHILDREN_58, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_59[] = {{PEGRuleId::NestedType, + TransformChildKind::REQUIRED, + 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_64 = {FRAME_CHILDREN_59, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_60[] = {{PEGRuleId::SquareBracketsArray, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_65 = {FRAME_CHILDREN_60, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_61[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_66 = {FRAME_CHILDREN_61, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_62[] = {{PEGRuleId::TimeZone, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeModifiers, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TimeOrTimestamp, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_67 = {FRAME_CHILDREN_62, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_63[] = {{PEGRuleId::WithOrWithout, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_68 = {FRAME_CHILDREN_63, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_64[] = {{PEGRuleId::SessionTarget, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_69 = {FRAME_CHILDREN_64, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_65[] = {{PEGRuleId::GenericCopyOptionList, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_70 = {FRAME_CHILDREN_65, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_66[] = {{PEGRuleId::CopyVariations, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_71 = {FRAME_CHILDREN_66, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_67[] = {{PEGRuleId::CopyOptions, + TransformChildKind::OPTIONAL, + 5, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CopyLegacyOption, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CopyFileName, + TransformChildKind::REQUIRED, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromOrTo, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_72 = {FRAME_CHILDREN_67, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_68[] = {{PEGRuleId::CopyOptions, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CopyFileName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_73 = {FRAME_CHILDREN_68, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_69[] = {{PEGRuleId::IdentifierColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_74 = {FRAME_CHILDREN_69, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_70[] = {{PEGRuleId::CopyFileNameSuffix, + TransformChildKind::REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_75 = {FRAME_CHILDREN_70, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_71[] = {{PEGRuleId::CopyOptionList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_76 = {FRAME_CHILDREN_71, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_72[] = {{PEGRuleId::SpecializedOptionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SpecializedOption, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_77 = {FRAME_CHILDREN_72, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_73[] = {{PEGRuleId::SpecializedOption, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_78 = {FRAME_CHILDREN_73, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_74[] = {{PEGRuleId::StarSymbolColumnList, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ForceQuote, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_79 = {FRAME_CHILDREN_74, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_0[] = {"StarSymbol"}; +static const TransformFramePlan FRAME_PLAN_80 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_0}}; +static const TransformChildPlan FRAME_CHILDREN_75[] = {{PEGRuleId::PartitionByColumnList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_81 = {FRAME_CHILDREN_75, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_76[] = {{PEGRuleId::ColumnList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_82 = {FRAME_CHILDREN_76, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_77[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_83 = {FRAME_CHILDREN_77, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_78[] = {{PEGRuleId::ColumnList, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ForceNotNull, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_84 = {FRAME_CHILDREN_78, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_79[] = {{PEGRuleId::CopyGenericOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_85 = {FRAME_CHILDREN_79, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_80[] = {{PEGRuleId::GenericCopyOptionValue, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_86 = {FRAME_CHILDREN_80, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_81[] = {{PEGRuleId::GenericCopyOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_87 = {FRAME_CHILDREN_81, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_82[] = {{PEGRuleId::GenericCopyOptionValue, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_88 = {FRAME_CHILDREN_82, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_83[] = {{PEGRuleId::GenericCopyOptionParenthesizedExpressionList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_89 = {FRAME_CHILDREN_83, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_84[] = {{PEGRuleId::OrderByExpressionList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_90 = {FRAME_CHILDREN_84, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_85[] = {{PEGRuleId::CopyDatabaseFlag, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_91 = {FRAME_CHILDREN_85, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_86[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_92 = {FRAME_CHILDREN_86, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_87[] = {{PEGRuleId::SchemaOrData, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_93 = {FRAME_CHILDREN_87, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_88[] = {{PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 10, + 6, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 9, + 5, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IndexElement, + TransformChildKind::LIST, + 8, + 4, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IndexType, + TransformChildKind::OPTIONAL, + 7, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 6, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UniqueIndex, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_94 = {FRAME_CHILDREN_88, 7, 7, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_89[] = {{PEGRuleId::RelOptionOrOids, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_95 = {FRAME_CHILDREN_89, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_90[] = {{PEGRuleId::RelOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_96 = {FRAME_CHILDREN_90, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_91[] = {{PEGRuleId::WithOrWithoutOids, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_97 = {FRAME_CHILDREN_91, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_92[] = {{PEGRuleId::NullsFirstOrLast, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescOrAsc, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_98 = {FRAME_CHILDREN_92, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_93[] = {{PEGRuleId::RelOptionArgumentOpt, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RelOptionName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_99 = {FRAME_CHILDREN_93, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_1[] = {"DottedColLabel", "StringLiteral"}; +static const TransformFramePlan FRAME_PLAN_100 = { + nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR) | + ParseResultTypeBit(ParseResultType::CHOICE) | ParseResultTypeBit(ParseResultType::LIST), + true, true, 2, FRAME_NAMES_1}}; +static const TransformChildPlan FRAME_CHILDREN_94[] = {{PEGRuleId::DotColLabel, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_101 = {FRAME_CHILDREN_94, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_95[] = {{PEGRuleId::DefArg, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_102 = {FRAME_CHILDREN_95, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_96[] = {{PEGRuleId::NullLiteral, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_103 = {FRAME_CHILDREN_96, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_97[] = {{PEGRuleId::MacroDefinition, + TransformChildKind::LIST, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MacroOrFunction, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_104 = {FRAME_CHILDREN_97, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_98[] = {{PEGRuleId::Type, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_105 = {FRAME_CHILDREN_98, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_99[] = {{PEGRuleId::MacroDefinitionBody, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReturnsType, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MacroParameters, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_106 = {FRAME_CHILDREN_99, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_100[] = {{PEGRuleId::MacroParameter, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_107 = {FRAME_CHILDREN_100, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_101[] = {{PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeFuncName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_108 = {FRAME_CHILDREN_101, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_102[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_109 = {FRAME_CHILDREN_102, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_103[] = {{PEGRuleId::WithOptionList, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_110 = {FRAME_CHILDREN_103, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_104[] = {{PEGRuleId::GenericCopyOptionList, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SecretStorageSpecifier, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SecretName, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_111 = {FRAME_CHILDREN_104, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_105[] = {{PEGRuleId::SequenceOption, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_112 = {FRAME_CHILDREN_105, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_106[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SeqMinOrMax, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_113 = {FRAME_CHILDREN_106, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_107[] = {{PEGRuleId::SeqMinOrMax, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_114 = {FRAME_CHILDREN_107, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_108[] = {{PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_115 = {FRAME_CHILDREN_108, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_109[] = {{PEGRuleId::CreateStatementVariation, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Temporary, + TransformChildKind::OPTIONAL, + 2, + 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_116 = {FRAME_CHILDREN_109, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_110[] = {{PEGRuleId::CommitAction, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateTableDefinition, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_117 = {FRAME_CHILDREN_110, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_111[] = {{PEGRuleId::WithData, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Statement, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PartitionSortedOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IdentifierList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_118 = {FRAME_CHILDREN_111, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_112[] = {{PEGRuleId::SortedOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PartitionOptions, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_119 = {FRAME_CHILDREN_112, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_113[] = {{PEGRuleId::PartitionOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SortedOptions, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_120 = {FRAME_CHILDREN_113, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_114[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_121 = {FRAME_CHILDREN_114, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_115[] = {{PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PartitionSortedOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateTableColumnList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_122 = {FRAME_CHILDREN_115, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_116[] = {{PEGRuleId::ReservedIdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SchemaQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_123 = {FRAME_CHILDREN_116, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_117[] = {{PEGRuleId::ReservedIdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 2, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_124 = {FRAME_CHILDREN_117, 3, 3, true, 0, {}}; +static const char *const FRAME_NAMES_2[] = {"StringLiteral"}; +static const TransformFramePlan FRAME_PLAN_125 = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 1, FRAME_NAMES_2}}; +static const TransformChildPlan FRAME_CHILDREN_118[] = {{PEGRuleId::CreateTableColumnElement, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_126 = {FRAME_CHILDREN_118, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_119[] = {{PEGRuleId::ColumnDefinition, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_127 = {FRAME_CHILDREN_119, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_120[] = {{PEGRuleId::TopLevelConstraint, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_128 = {FRAME_CHILDREN_120, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_121[] = {{PEGRuleId::ColumnConstraint, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::GeneratedColumn, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_129 = {FRAME_CHILDREN_121, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_122[] = {{PEGRuleId::ColumnConstraintElement, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_130 = {FRAME_CHILDREN_122, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_123[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_131 = {FRAME_CHILDREN_123, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_124[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_132 = {FRAME_CHILDREN_124, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_125[] = {{PEGRuleId::ColumnDefaultExpr, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_133 = {FRAME_CHILDREN_125, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_126[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_134 = {FRAME_CHILDREN_126, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_127[] = {{PEGRuleId::KeyActions, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_135 = {FRAME_CHILDREN_127, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_128[] = {{PEGRuleId::DottedIdentifier, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_136 = {FRAME_CHILDREN_128, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_129[] = {{PEGRuleId::DeleteAction, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateAction, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_137 = {FRAME_CHILDREN_129, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_130[] = {{PEGRuleId::UpdateAction, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DeleteAction, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_138 = {FRAME_CHILDREN_130, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_131[] = {{PEGRuleId::KeyAction, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_139 = {FRAME_CHILDREN_131, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_132[] = {{PEGRuleId::TopLevelConstraintList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_140 = {FRAME_CHILDREN_132, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_133[] = {{PEGRuleId::CheckConstraint, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_141 = {FRAME_CHILDREN_133, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_134[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_142 = {FRAME_CHILDREN_134, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_135[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_143 = {FRAME_CHILDREN_135, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_136[] = {{PEGRuleId::ForeignKeyConstraint, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_144 = {FRAME_CHILDREN_136, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_137[] = { + {PEGRuleId::ColId, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_145 = {FRAME_CHILDREN_137, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_138[] = {{PEGRuleId::DotColLabel, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_146 = {FRAME_CHILDREN_138, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_139[] = {{PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_147 = {FRAME_CHILDREN_139, 1, 1, false, 0, {}}; +static const char *const FRAME_NAMES_3[] = {"UnreservedKeyword", "ColumnNameKeyword", "Identifier"}; +static const TransformFramePlan FRAME_PLAN_148 = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 3, FRAME_NAMES_3}}; +static const TransformFramePlan FRAME_PLAN_149 = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 0, nullptr}}; +static const char *const FRAME_NAMES_4[] = {"UnreservedKeyword", "TypeFuncKeyword", "Identifier"}; +static const TransformFramePlan FRAME_PLAN_150 = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 3, FRAME_NAMES_4}}; +static const char *const FRAME_NAMES_5[] = {"TypeNameKeyword", "FuncNameKeyword"}; +static const TransformFramePlan FRAME_PLAN_151 = { + nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR), + 0, false, true, 2, FRAME_NAMES_5}}; +static const char *const FRAME_NAMES_6[] = {"ReservedKeyword", "UnreservedKeyword", "ColumnNameKeyword", + "FuncNameKeyword", "TypeNameKeyword"}; +static const TransformFramePlan FRAME_PLAN_152 = { + nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR), + 0, false, true, 5, FRAME_NAMES_6}}; +static const TransformChildPlan FRAME_CHILDREN_140[] = {{PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_153 = {FRAME_CHILDREN_140, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_141[] = {{PEGRuleId::GeneratedColumnType, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Generated, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_154 = {FRAME_CHILDREN_141, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_142[] = {{PEGRuleId::PreserveOrDelete, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_155 = {FRAME_CHILDREN_142, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_143[] = {{PEGRuleId::TriggerBody, + TransformChildKind::REQUIRED, + 9, + 7, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ForEachClause, + TransformChildKind::OPTIONAL, + 8, + 6, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReferencingClause, + TransformChildKind::OPTIONAL, + 7, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerEvent, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerTiming, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_156 = {FRAME_CHILDREN_143, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_144[] = {{PEGRuleId::ReferencingItem, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReferencingItem, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_157 = {FRAME_CHILDREN_144, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_145[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_158 = {FRAME_CHILDREN_145, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_146[] = {{PEGRuleId::TriggerColumnList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_159 = {FRAME_CHILDREN_146, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_147[] = { + {PEGRuleId::ColId, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_160 = {FRAME_CHILDREN_147, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_148[] = {{PEGRuleId::CreateType, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_161 = {FRAME_CHILDREN_148, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_149[] = {{PEGRuleId::Type, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_162 = {FRAME_CHILDREN_149, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_150[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_163 = {FRAME_CHILDREN_150, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_151[] = {{PEGRuleId::ArrayBounds, + TransformChildKind::OPTIONAL_REPEAT, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_164 = {FRAME_CHILDREN_151, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_152[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 8, + 6, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 6, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateRecursive, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateSecure, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_165 = {FRAME_CHILDREN_152, 7, 7, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_153[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DeallocatePrepare, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_166 = {FRAME_CHILDREN_153, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_154[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DeleteUsingClause, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetOptAlias, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_167 = {FRAME_CHILDREN_154, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_155[] = {{PEGRuleId::TruncateOptions, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_168 = {FRAME_CHILDREN_155, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_156[] = {{PEGRuleId::TruncateDropBehavior, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetAlias, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_169 = {FRAME_CHILDREN_156, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_157[] = {{PEGRuleId::DropBehavior, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_170 = {FRAME_CHILDREN_157, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_158[] = {{PEGRuleId::TargetAlias, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_171 = {FRAME_CHILDREN_158, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_159[] = {{PEGRuleId::TableRef, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_172 = {FRAME_CHILDREN_159, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_160[] = {{PEGRuleId::ShowExternalResourcesType, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_173 = {FRAME_CHILDREN_160, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_161[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_174 = {FRAME_CHILDREN_161, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_162[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescribeOrSummarize, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_175 = {FRAME_CHILDREN_162, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_163[] = {{PEGRuleId::ShowOrDescribe, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_176 = {FRAME_CHILDREN_163, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_164[] = {{PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowOrDescribe, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_177 = {FRAME_CHILDREN_164, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_165[] = {{PEGRuleId::ShowTarget, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_178 = {FRAME_CHILDREN_165, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_166[] = {{PEGRuleId::DescribeTarget, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescribeOrSummarize, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_179 = {FRAME_CHILDREN_166, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_7[] = {"ShowSpecialForm"}; +static const TransformFramePlan FRAME_PLAN_180 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_7}}; +static const TransformChildPlan FRAME_CHILDREN_167[] = {{PEGRuleId::QualifiedTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_181 = {FRAME_CHILDREN_167, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_168[] = {{PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_182 = {FRAME_CHILDREN_168, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_169[] = {{PEGRuleId::SummarizeRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_183 = {FRAME_CHILDREN_169, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_170[] = {{PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_184 = {FRAME_CHILDREN_170, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_171[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DropEntries, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_185 = {FRAME_CHILDREN_171, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + TransformChildKind::LIST, + 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::TableOrView, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::LIST, + 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_188 = {FRAME_CHILDREN_174, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::FunctionIdentifier, + TransformChildKind::LIST, + 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_189 = {FRAME_CHILDREN_175, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::QualifiedName, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SecretName, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Temporary, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 1, + 0, + 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, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExplainOptionList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnalyzeKeyword, + TransformChildKind::OPTIONAL, + 1, + 0, + 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, + 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, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExplainOptionName, + TransformChildKind::REQUIRED, + 0, + 0, + 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 char *const FRAME_NAMES_8[] = {"FuncNameKeyword", "TypeNameKeyword"}; +static const TransformFramePlan FRAME_PLAN_201 = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, false, 2, FRAME_NAMES_8}}; +static const TransformChildPlan FRAME_CHILDREN_187[] = {{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, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExportSource, + TransformChildKind::OPTIONAL, + 2, + 0, + 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, + TransformChildKind::REPEAT, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SchemaQualification, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FilterClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithinGroupClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionExpressionArguments, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionArgumentList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + 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, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + 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, + 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, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CastOrTryCast, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReplaceList, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExcludeList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::StarQualifierList, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + 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, + 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, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SubqueryExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SubqueryNot, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + TransformChildKind::OPTIONAL, + 3, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SimpleCaseWhenThen, + TransformChildKind::REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + 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, + TransformChildKind::OPTIONAL, + 2, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CaseWhenThen, + TransformChildKind::REPEAT, + 1, + 0, + 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, + TransformChildKind::REQUIRED, + 3, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SimpleCaseWhenOperand, + TransformChildKind::LIST, + 1, + 0, + 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, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + 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, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IntervalParameter, + TransformChildKind::REQUIRED, + 1, + 0, + 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, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FrameExtent, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Framing, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FrameBound, + TransformChildKind::REQUIRED, + 1, + 0, + 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, + 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, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + 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, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseWindowName, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + 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, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WindowPartition, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + 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, + 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, + 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, + 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, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + 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, + 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, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::OPTIONAL_LIST, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::GroupingOrGroupingId, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::OPTIONAL, + 6, + 3, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 5, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + 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, + 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, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MeasureSemantics, + TransformChildKind::REQUIRED, + 0, + 0, + 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::LambdaArrowExpression, + 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, + 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::SingleArrowPair, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LogicalOrExpression, + TransformChildKind::REQUIRED, + 0, + 0, + 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::LogicalOrExpression, + 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::LogicalOrExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LogicalAndExpression, + TransformChildKind::REQUIRED, + 0, + 0, + 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::LogicalAndExpression, + 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::ColDefOrExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColDefAndExpr, + TransformChildKind::REQUIRED, + 0, + 0, + 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::ColDefAndExpr, + 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::LogicalAndExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LogicalNotExpression, + TransformChildKind::REQUIRED, + 0, + 0, + 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::LogicalNotExpression, + 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::ColDefAndExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsDistinctFromExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::IsDistinctFromExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NotExpression, + TransformChildKind::OPTIONAL, + 0, + 0, + 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::NotKeyword, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsExpressionContinuation, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsDistinctFromExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsTest, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsTest, + 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::IsDistinctFromTail, + 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::ComparisonExpressionTail, + 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::OtherOperatorTail, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::CastOperator, + 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::IsLiteralValue, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::IsNullOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::IsDistinctFromTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ComparisonExpression, + TransformChildKind::REQUIRED, + 0, + 0, + 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::ComparisonExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsDistinctFromOp, + TransformChildKind::REQUIRED, + 0, + 0, + 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::ComparisonExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BetweenInLikeExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonOperand, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ComparisonOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::IsExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NotExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::BetweenLikeOp, + TransformChildKind::OPTIONAL, + 2, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InPredicate, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::CastOperator, + TransformChildKind::OPTIONAL_REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InClause, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::BetweenLikeOpExpression, + 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::EscapeClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LikeVariations, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 1, + 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::InExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, 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::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::InfixOtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::OtherOperatorTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BitwiseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnyAllParsedOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::BitwiseExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::AnyAllOperator, + TransformChildKind::REQUIRED, + 0, + 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::AnyOrAll, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::QualifiedOperatorContents, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, 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::ColIdDot, + TransformChildKind::OPTIONAL_REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::BitwiseExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TildeExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::TildeExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BitOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AdditiveExpression, + TransformChildKind::REQUIRED, + 1, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TildePrefixOperator, + TransformChildKind::OPTIONAL_REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AdditiveExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MultiplicativeExpression, + TransformChildKind::REQUIRED, + 0, + 0, + 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::MultiplicativeExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Term, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::MultiplicativeExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExponentiationExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::ExponentiationExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Factor, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::ExponentiationExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CollateExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::CollateExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExponentOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::CollateExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtTimeZoneExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::AtTimeZoneExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::AtTimeZoneExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UnaryExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::UnaryExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::TildeExpression, + 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::IndirectionList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SingleExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::Indirection, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::MethodExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::MethodExpressionArguments, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::MethodExpressionArgumentList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::IgnoreOrRespectNulls, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MethodFunctionArguments, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::SliceBound, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::SliceUpperBound, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::StepSliceBound, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::StepSliceBound, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::EndSliceBound, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::ExtractArguments, + TransformChildKind::REQUIRED, + 1, + 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::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExtractArgument, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::NullIfArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::PositionArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::SubstringArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::SubstringFromFor, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::ForExpression, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromExpression, + TransformChildKind::REQUIRED, + 0, + 0, + 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, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::TrimArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, 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::Expression, + TransformChildKind::LIST, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TrimSource, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TrimDirection, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::OverlayArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, 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::ForExpression, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromExpression, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::ExtractDatePart, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::ExternalResourceCreationOptions, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::OPTIONAL, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 5, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::OPTIONAL, + 3, + 0, + 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::ColId, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::AttachOptions, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceSource, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::AttachOptions, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceSource, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExternalResourceCreationOptions, + TransformChildKind::OPTIONAL, + 4, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 10, + 7, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OnConflictClause, + TransformChildKind::OPTIONAL, + 9, + 6, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertValues, + TransformChildKind::REQUIRED, + 8, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ByNameOrPosition, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertTarget, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrAction, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::InsertByName, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::InsertByPosition, + 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::InsertAlias, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::OnConflictAction, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OnConflictTarget, + TransformChildKind::OPTIONAL, + 2, + 0, + 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::WhereClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 0, + 0, + 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::ConstraintName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateSetClauseList, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::ExtensionAlias, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromSource, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::VersionNumber, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromSource, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InstallAndLoad, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::RepositoryPublicKey, + TransformChildKind::OPTIONAL, + 7, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RepositoryPrefix, + TransformChildKind::REQUIRED, + 6, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + 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_367 = {FRAME_CHILDREN_352, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MatchRecognizeBody, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, 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::MatchRecognizeClause, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::WindowPartition, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::OrderByClause, + 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::MeasuresClause, + 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::RowsPerMatch, + 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::AfterMatchSkip, + 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::PatternClause, + 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::SubsetClause, + 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::DefineClause, + 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::MeasuresElement, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_364, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_365, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::AllRowsEmptyMatches, + TransformChildKind::OPTIONAL, + 4, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::AfterMatchSkipTarget, + TransformChildKind::REQUIRED, + 3, + 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::ColLabelOrString, + TransformChildKind::REQUIRED, + 2, + 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, + TransformChildKind::REQUIRED, + 1, + 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::RowPattern, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, 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::RowPatternAlternative, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RowPatternTerm, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_371, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::RowPatternTerm, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_372, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::RowPatternFactor, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_373, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::RowPatternQuantifier, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RowPatternPrimary, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_374, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::RowPattern, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_375, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::RowPattern, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::RowPattern, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, 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::ColLabelOrString, + TransformChildKind::REQUIRED, + 0, + 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::QuantifierReluctant, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RowPatternQuantifierKind, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_379, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::QuantifierBounds, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_380, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::SubsetElement, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_381, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::LIST, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_382, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::DefineElement, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_383, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_384, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 7, + 5, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MergeMatch, + TransformChildKind::REPEAT, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinQualifier, + TransformChildKind::REQUIRED, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MergeIntoUsingClause, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetOptAlias, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_385, 6, 6, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_386, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::MatchedClauseAction, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AndExpression, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_387, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::UpdateMatchInfo, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_388, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::UpdateMatchSetClause, + TransformChildKind::REQUIRED, + 0, + 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::ByNameOrPosition, + 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::InsertMatchInfo, + TransformChildKind::OPTIONAL, + 1, + 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::ByNameOrPosition, + TransformChildKind::OPTIONAL, + 0, + 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::Expression, + TransformChildKind::LIST, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_393, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::UpdateMatchSetInfo, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_394, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::MatchedClauseAction, + TransformChildKind::REQUIRED, + 6, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AndExpression, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BySourceOrTarget, + TransformChildKind::OPTIONAL, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_395, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::PivotColumnList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_396, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::PivotColumnEntry, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_397, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_398, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::OptionalParensNameList, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 2, + 0, + 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::ColIdOrString, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_400, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 0, + 0, + false, + {0, 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::PragmaAssignOrFunction, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_402, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::VariableList, + TransformChildKind::REQUIRED, + 2, + 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::PragmaParameters, + TransformChildKind::OPTIONAL, + 1, + 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::Statement, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_405, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_406[] = { + {PEGRuleId::Type, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_406, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::SelectSetOpChainTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IntersectChain, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_407, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::IntersectChain, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetopClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_408, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::IntersectChainTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SelectAtom, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_409, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::SelectAtom, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetIntersectClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_410, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetopType, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_412, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::LimitOffset, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 0, + 0, + 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::OffsetClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LimitClause, + TransformChildKind::REQUIRED, + 0, + 0, + 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::LimitClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OffsetClause, + TransformChildKind::REQUIRED, + 0, + 0, + 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::FetchClause, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OffsetClause, + TransformChildKind::REQUIRED, + 0, + 0, + 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::OffsetClause, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FetchClause, + TransformChildKind::REQUIRED, + 0, + 0, + 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::FetchClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_418, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 1, + 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::SimpleSelect, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, 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::FromClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SelectClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::SelectClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromClause, + TransformChildKind::REQUIRED, + 0, + 0, + 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::CTEBody, + TransformChildKind::REQUIRED, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Materialized, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UsingKey, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnAliases, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_423, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::Statement, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_424, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 2, + 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, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistinctClause, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_426, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::AliasedExpression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_427, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::DistinctOnTargets, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_428, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_429, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + 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, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ValuesClause, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_431, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + 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::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TablePivotClauseBody, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_433, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::PivotGroupByList, + TransformChildKind::OPTIONAL, + 3, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PivotValueList, + TransformChildKind::REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_434, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::OptionalParensNameList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_435, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableUnpivotClauseBody, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IncludeOrExcludeNulls, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_436, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::UnpivotValueList, + TransformChildKind::REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UnpivotHeader, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_437, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::BaseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_438, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::PivotValueTarget, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PivotHeader, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_439, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::PivotTargetList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_440, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::UnpivotTargetList, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UnpivotHeader, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_441, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_442, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 5, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithOrdinality, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_443, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithOrdinality, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_444, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::SchemaQualification, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_445, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::FunctionArgument, + TransformChildKind::OPTIONAL_LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_446, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeFuncName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_447, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeFuncName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_448, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::ColumnAliases, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_449, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::ColumnAliases, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_450, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::AtSpecifier, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, 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::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtUnit, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_452, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 8, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistanceOrSimilarity, + TransformChildKind::REQUIRED, + 7, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ApproxOrExact, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_453, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 8, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistanceOrSimilarity, + TransformChildKind::REQUIRED, + 7, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ApproxOrExact, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NearestBareTableRef, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 0, + 0, + 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::ValuesClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_455, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::WithOrdinality, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_456, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_457, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_458, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_459, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::JoinQualifier, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Asof, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_460, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_461[] = { + {PEGRuleId::JoinQualifier, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {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_476 = {FRAME_CHILDREN_461, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::InnerTableRef, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinPrefix, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_462, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::UsingColumnName, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_463, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_464, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::GroupByExpressions, + TransformChildKind::REQUIRED, + 2, + 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::SampleEntry, + TransformChildKind::REQUIRED, + 1, + 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::WindowDefinition, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_467, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleProperties, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleCount, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_468, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::RepeatableSample, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleCount, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleFunction, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_469, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_470[] = { + {PEGRuleId::SampleSeed, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, 1, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_470, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::SampleSeed, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_471, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::SampleUnit, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleValue, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_472, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::GroupByExpression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_473, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CubeOrRollup, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_474, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::GroupByExpression, + TransformChildKind::LIST, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_475, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::OrderByExpressions, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_476, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::OrderByExpression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_477, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::NullsFirstOrLast, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescOrAsc, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_478, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::LimitValue, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_479, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::OffsetValue, + 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::FetchValue, + TransformChildKind::REQUIRED, + 2, + 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::Expression, + TransformChildKind::REQUIRED, + 2, + 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_497 = {FRAME_CHILDREN_482, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::ValuesExpressions, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_483, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::SetAssignmentOrTimeZone, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_484, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 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::ResetTarget, + TransformChildKind::REQUIRED, + 1, + 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::SettingScope, + TransformChildKind::OPTIONAL, + 0, + 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::SetVariableOrSetting, + TransformChildKind::REQUIRED, + 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::SetAssignment, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {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, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::ZoneValue, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SettingScope, + TransformChildKind::OPTIONAL, + 0, + 0, + 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::Interval, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_491, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::VariableScope, + TransformChildKind::REQUIRED, + 0, + 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::VariableList, + TransformChildKind::REQUIRED, + 1, + 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::ReadOrWrite, + TransformChildKind::OPTIONAL, + 2, + 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::ReadOnlyOrReadWrite, + TransformChildKind::REQUIRED, + 1, + 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::ReturningClause, + TransformChildKind::OPTIONAL, + 6, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromClause, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateSetClauseList, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateTarget, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_496, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::UpdateAlias, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_497, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::UpdateSetClause, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_498, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateSetColumnTarget, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_499, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::DotIdentifier, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_500, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::UseTarget, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::DotIdentifier, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_502, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::AnalyzeTarget, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::VacuumOptions, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_503, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::VacuumOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_504, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::OptAnalyze, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OptVerbose, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OptFreeze, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OptFull, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_505, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::AnalyzeKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_506, 1, 1, false, 0, {}}; + +static const TransformFrameOps GENERATED_FRAME_OPS[] = { + {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, + &PEGTransformerFactory::FinalizeStatementTrampoline, nullptr}, + {"PragmaName", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"TypeName", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"PlainIdentifier", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"QuotedIdentifier", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"ReservedKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"UnreservedKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"ColumnNameKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"FuncNameKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"TypeNameKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"BareLabelKeyword", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"SettingName", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, + {"AlterStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterStatementTrampoline, &FRAME_PLAN_0}, + {"AlterOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AlterTableStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterTableStmtTrampoline, &FRAME_PLAN_2}, + {"AlterSchemaStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterSchemaStmtTrampoline, &FRAME_PLAN_3}, + {"AlterSchemaOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AlterTableOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AddConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAddConstraintTrampoline, &FRAME_PLAN_4}, + {"DropConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropConstraintTrampoline, &FRAME_PLAN_5}, + {"AddColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAddColumnTrampoline, &FRAME_PLAN_6}, + {"AddColumnEntry", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAddColumnEntryTrampoline, &FRAME_PLAN_7}, + {"DropColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropColumnTrampoline, &FRAME_PLAN_8}, + {"AlterColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterColumnTrampoline, &FRAME_PLAN_9}, + {"RenameColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRenameColumnTrampoline, &FRAME_PLAN_10}, + {"NestedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNestedColumnNameTrampoline, &FRAME_PLAN_11}, + {"IdentifierDot", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIdentifierDotTrampoline, &FRAME_PLAN_12}, + {"RenameAlter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRenameAlterTrampoline, &FRAME_PLAN_13}, + {"SetPartitionedBy", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetPartitionedByTrampoline, &FRAME_PLAN_14}, + {"ResetPartitionedBy", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResetPartitionedByTrampoline, &FRAME_PLAN_12}, + {"SetSortedBy", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetSortedByTrampoline, &FRAME_PLAN_15}, + {"ResetSortedBy", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResetSortedByTrampoline, &FRAME_PLAN_12}, + {"SetOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetOptionsTrampoline, &FRAME_PLAN_16}, + {"ResetOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResetOptionsTrampoline, &FRAME_PLAN_16}, + {"AlterColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AddOrDropDefault", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AddDefault", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAddDefaultTrampoline, &FRAME_PLAN_17}, + {"DropDefault", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropDefaultTrampoline, &FRAME_PLAN_12}, + {"ChangeNullability", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeChangeNullabilityTrampoline, &FRAME_PLAN_18}, + {"DropOrSet", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeDropOrSetTrampoline, &FRAME_PLAN_19}, + {"DropNullability", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropNullabilityTrampoline, &FRAME_PLAN_12}, + {"SetNullability", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetNullabilityTrampoline, &FRAME_PLAN_12}, + {"AlterType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterTypeTrampoline, &FRAME_PLAN_20}, + {"UsingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUsingExpressionTrampoline, &FRAME_PLAN_21}, + {"AlterViewStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterViewStmtTrampoline, &FRAME_PLAN_22}, + {"AlterSequenceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterSequenceStmtTrampoline, &FRAME_PLAN_23}, + {"QualifiedSequenceName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline, &FRAME_PLAN_24}, + {"AlterSequenceOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"RenameAlterSequenceOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRenameAlterSequenceOptionsTrampoline, &FRAME_PLAN_25}, + {"SetSequenceOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetSequenceOptionTrampoline, &FRAME_PLAN_26}, + {"AlterDatabaseStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAlterDatabaseStmtTrampoline, &FRAME_PLAN_27}, + {"AnalyzeStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnalyzeStatementTrampoline, &FRAME_PLAN_28}, + {"AnalyzeTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnalyzeTargetTrampoline, &FRAME_PLAN_29}, + {"AnalyzeVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnalyzeVerboseTrampoline, &FRAME_PLAN_12}, + {"AttachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAttachStatementTrampoline, &FRAME_PLAN_30}, + {"DatabasePath", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDatabasePathTrampoline, &FRAME_PLAN_31}, + {"AttachAlias", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAttachAliasTrampoline, &FRAME_PLAN_32}, + {"AttachOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAttachOptionsTrampoline, &FRAME_PLAN_33}, + {"CallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCallStatementTrampoline, &FRAME_PLAN_34}, + {"CheckpointStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCheckpointStatementTrampoline, &FRAME_PLAN_35}, + {"CheckpointForce", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCheckpointForceTrampoline, &FRAME_PLAN_12}, + {"CommentStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentStatementTrampoline, &FRAME_PLAN_36}, + {"CommentTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CommentStringLiteralIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentStringLiteralIdentifierTrampoline, &FRAME_PLAN_37}, + {"CommentOnType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CommentTable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentTableTrampoline, &FRAME_PLAN_12}, + {"CommentSequence", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentSequenceTrampoline, &FRAME_PLAN_12}, + {"CommentFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentFunctionTrampoline, &FRAME_PLAN_12}, + {"CommentMacroTable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentMacroTableTrampoline, &FRAME_PLAN_12}, + {"CommentMacro", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentMacroTrampoline, &FRAME_PLAN_12}, + {"CommentView", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentViewTrampoline, &FRAME_PLAN_12}, + {"CommentDatabase", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentDatabaseTrampoline, &FRAME_PLAN_12}, + {"CommentIndex", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentIndexTrampoline, &FRAME_PLAN_12}, + {"CommentSchema", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentSchemaTrampoline, &FRAME_PLAN_12}, + {"CommentType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentTypeTrampoline, &FRAME_PLAN_12}, + {"CommentColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommentColumnTrampoline, &FRAME_PLAN_12}, + {"CommentValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"StringLiteralValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStringLiteralValueTrampoline, &FRAME_PLAN_12}, + {"AnalyzeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnalyzeKeywordTrampoline, &FRAME_PLAN_12}, + {"IndexName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIndexNameTrampoline, &FRAME_PLAN_12}, + {"ConstraintName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeConstraintNameTrampoline, &FRAME_PLAN_38}, + {"SequenceName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSequenceNameTrampoline, &FRAME_PLAN_12}, + {"CollationName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCollationNameTrampoline, &FRAME_PLAN_12}, + {"NumberLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNumberLiteralTrampoline, &FRAME_PLAN_12}, + {"StringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStringLiteralTrampoline, &FRAME_PLAN_12}, + {"Type", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTypeTrampoline, + &FRAME_PLAN_39}, + {"TypeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SimpleType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CharacterSimpleType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCharacterSimpleTypeTrampoline, &FRAME_PLAN_40}, + {"QualifiedSimpleType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifiedSimpleTypeTrampoline, &FRAME_PLAN_41}, + {"IntervalType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IntervalInterval", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IntervalWithSpecifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IntervalWithRangeSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntervalWithRangeSpecifierTrampoline, &FRAME_PLAN_42}, + {"IntervalWithSimpleSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntervalWithSimpleSpecifierTrampoline, &FRAME_PLAN_43}, + {"IntervalWithoutSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntervalWithoutSpecifierTrampoline, &FRAME_PLAN_12}, + {"IntervalToIntervalAsType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeIntervalToIntervalAsTypeTrampoline, &FRAME_PLAN_44}, + {"YearKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeYearKeywordTrampoline, &FRAME_PLAN_12}, + {"MonthKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMonthKeywordTrampoline, &FRAME_PLAN_12}, + {"DayKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDayKeywordTrampoline, &FRAME_PLAN_12}, + {"HourKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeHourKeywordTrampoline, &FRAME_PLAN_12}, + {"MinuteKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMinuteKeywordTrampoline, &FRAME_PLAN_12}, + {"SecondKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSecondKeywordTrampoline, &FRAME_PLAN_12}, + {"MillisecondKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMillisecondKeywordTrampoline, &FRAME_PLAN_12}, + {"MicrosecondKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMicrosecondKeywordTrampoline, &FRAME_PLAN_12}, + {"WeekKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWeekKeywordTrampoline, &FRAME_PLAN_12}, + {"QuarterKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuarterKeywordTrampoline, &FRAME_PLAN_12}, + {"DecadeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDecadeKeywordTrampoline, &FRAME_PLAN_12}, + {"CenturyKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCenturyKeywordTrampoline, &FRAME_PLAN_12}, + {"MillenniumKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMillenniumKeywordTrampoline, &FRAME_PLAN_12}, + {"Interval", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IntervalToInterval", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"YearToMonth", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeYearToMonthTrampoline, &FRAME_PLAN_45}, + {"DayToHour", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDayToHourTrampoline, &FRAME_PLAN_46}, + {"DayToMinute", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDayToMinuteTrampoline, &FRAME_PLAN_47}, + {"DayToSecond", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDayToSecondTrampoline, &FRAME_PLAN_48}, + {"HourToMinute", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeHourToMinuteTrampoline, &FRAME_PLAN_49}, + {"HourToSecond", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeHourToSecondTrampoline, &FRAME_PLAN_50}, + {"MinuteToSecond", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMinuteToSecondTrampoline, &FRAME_PLAN_51}, + {"BitType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBitTypeTrampoline, + &FRAME_PLAN_52}, + {"GeometryType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGeometryTypeTrampoline, &FRAME_PLAN_53}, + {"VariantType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVariantTypeTrampoline, &FRAME_PLAN_12}, + {"NumericType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SimpleNumericType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeSimpleNumericTypeTrampoline, &FRAME_PLAN_54}, + {"DecimalNumericType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IntType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIntTypeTrampoline, + &FRAME_PLAN_12}, + {"IntegerType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntegerTypeTrampoline, &FRAME_PLAN_12}, + {"SmallintType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSmallintTypeTrampoline, &FRAME_PLAN_12}, + {"BigintType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBigintTypeTrampoline, &FRAME_PLAN_12}, + {"RealType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRealTypeTrampoline, &FRAME_PLAN_12}, + {"BooleanType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBooleanTypeTrampoline, &FRAME_PLAN_12}, + {"DoubleType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDoubleTypeTrampoline, &FRAME_PLAN_12}, + {"FloatType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFloatTypeTrampoline, &FRAME_PLAN_12}, + {"DecimalType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDecimalTypeTrampoline, &FRAME_PLAN_40}, + {"DecType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDecTypeTrampoline, + &FRAME_PLAN_40}, + {"NumericModType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNumericModTypeTrampoline, &FRAME_PLAN_40}, + {"QualifiedTypeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TypeNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTypeNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, + {"CatalogReservedSchemaTypeName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTypeNameTrampoline, &FRAME_PLAN_55}, + {"SchemaReservedTypeName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaReservedTypeNameTrampoline, &FRAME_PLAN_56}, + {"TypeModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTypeModifiersTrampoline, &FRAME_PLAN_57}, + {"NestedType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNestedTypeTrampoline, &FRAME_PLAN_39}, + {"RowType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRowTypeTrampoline, + &FRAME_PLAN_58}, + {"SetofType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetofTypeTrampoline, &FRAME_PLAN_59}, + {"UnionType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnionTypeTrampoline, &FRAME_PLAN_60}, + {"ColIdTypeList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColIdTypeListTrampoline, &FRAME_PLAN_61}, + {"MapType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMapTypeTrampoline, + &FRAME_PLAN_62}, + {"TupleType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTupleTypeTrampoline, &FRAME_PLAN_63}, + {"ColIdType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColIdTypeTrampoline, &FRAME_PLAN_64}, + {"ArrayBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ArrayKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeArrayKeywordTrampoline, &FRAME_PLAN_12}, + {"ArrayKeywordWithBounds", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeArrayKeywordWithBoundsTrampoline, &FRAME_PLAN_65}, + {"SquareBracketsArray", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSquareBracketsArrayTrampoline, &FRAME_PLAN_66}, + {"TimeType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTimeTypeTrampoline, &FRAME_PLAN_67}, + {"TimeOrTimestamp", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TimeTypeId", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTimeTypeIdTrampoline, &FRAME_PLAN_12}, + {"TimestampTypeId", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTimestampTypeIdTrampoline, &FRAME_PLAN_12}, + {"TimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTimeZoneTrampoline, &FRAME_PLAN_68}, + {"WithOrWithout", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"WithRule", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithRuleTrampoline, &FRAME_PLAN_12}, + {"WithoutRule", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithoutRuleTrampoline, &FRAME_PLAN_12}, + {"ConnectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeConnectStatementTrampoline, &FRAME_PLAN_69}, + {"DisconnectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDisconnectStatementTrampoline, &FRAME_PLAN_12}, + {"SessionTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"LocalSessionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLocalSessionTargetTrampoline, &FRAME_PLAN_12}, + {"StringSessionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStringSessionTargetTrampoline, &FRAME_PLAN_70}, + {"CatalogSessionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogSessionTargetTrampoline, &FRAME_PLAN_12}, + {"CopyStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyStatementTrampoline, &FRAME_PLAN_71}, + {"CopyVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CopyTable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyTableTrampoline, &FRAME_PLAN_72}, + {"FromOrTo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CopyFrom", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyFromTrampoline, &FRAME_PLAN_12}, + {"CopyTo", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCopyToTrampoline, + &FRAME_PLAN_12}, + {"CopySelect", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopySelectTrampoline, &FRAME_PLAN_73}, + {"CopyFileName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CopyFileNameExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CopyFileNameStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyFileNameStringLiteralTrampoline, &FRAME_PLAN_12}, + {"CopyFileNameIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyFileNameIdentifierTrampoline, &FRAME_PLAN_12}, + {"CopyFileNameIdentifierColId", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyFileNameIdentifierColIdTrampoline, &FRAME_PLAN_74}, + {"IdentifierColId", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIdentifierColIdTrampoline, &FRAME_PLAN_75}, + {"CopyFileNameSuffix", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_32}, + {"CopyLegacyOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyLegacyOptionTrampoline, &FRAME_PLAN_12}, + {"CopyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyOptionsTrampoline, &FRAME_PLAN_76}, + {"CopyOptionList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SpecializedOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSpecializedOptionListTrampoline, &FRAME_PLAN_77}, + {"SpecializedOptionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSpecializedOptionTailTrampoline, &FRAME_PLAN_78}, + {"SpecializedOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SingleOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"BinaryOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBinaryOptionTrampoline, &FRAME_PLAN_12}, + {"FreezeOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFreezeOptionTrampoline, &FRAME_PLAN_12}, + {"OidsOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOidsOptionTrampoline, &FRAME_PLAN_12}, + {"CsvOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCsvOptionTrampoline, &FRAME_PLAN_12}, + {"HeaderOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeHeaderOptionTrampoline, &FRAME_PLAN_12}, + {"NullAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullAsOptionTrampoline, &FRAME_PLAN_12}, + {"DelimiterAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDelimiterAsOptionTrampoline, &FRAME_PLAN_12}, + {"QuoteAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuoteAsOptionTrampoline, &FRAME_PLAN_12}, + {"EscapeAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEscapeAsOptionTrampoline, &FRAME_PLAN_12}, + {"EncodingOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEncodingOptionTrampoline, &FRAME_PLAN_12}, + {"ForceQuoteOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForceQuoteOptionTrampoline, &FRAME_PLAN_79}, + {"StarSymbolColumnList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeStarSymbolColumnListTrampoline, &FRAME_PLAN_80}, + {"ForceQuote", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForceQuoteTrampoline, &FRAME_PLAN_12}, + {"PartitionByOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePartitionByOptionTrampoline, &FRAME_PLAN_81}, + {"PartitionByColumnList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"StarPartitionByColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStarPartitionByColumnListTrampoline, &FRAME_PLAN_12}, + {"ParenthesizedPartitionByColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeParenthesizedPartitionByColumnListTrampoline, &FRAME_PLAN_82}, + {"SinglePartitionByColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSinglePartitionByColumnListTrampoline, &FRAME_PLAN_83}, + {"ForceNullOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForceNullOptionTrampoline, &FRAME_PLAN_84}, + {"ForceNotNull", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForceNotNullTrampoline, &FRAME_PLAN_12}, + {"CopyGenericOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyGenericOptionListTrampoline, &FRAME_PLAN_85}, + {"CopyGenericOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OrderByCopyOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOrderByCopyOptionTrampoline, &FRAME_PLAN_86}, + {"PartitionedByCopyOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePartitionedByCopyOptionTrampoline, &FRAME_PLAN_86}, + {"GenericCopyOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGenericCopyOptionListTrampoline, &FRAME_PLAN_87}, + {"GenericCopyOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGenericCopyOptionTrampoline, &FRAME_PLAN_88}, + {"GenericCopyOptionValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"GenericCopyOptionOrderList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGenericCopyOptionOrderListTrampoline, &FRAME_PLAN_89}, + {"GenericCopyOptionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGenericCopyOptionExpressionTrampoline, &FRAME_PLAN_31}, + {"GenericCopyOptionParenthesizedExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGenericCopyOptionParenthesizedExpressionListTrampoline, &FRAME_PLAN_90}, + {"CopyFromDatabase", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CopyFromDatabaseWithFlag", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyFromDatabaseWithFlagTrampoline, &FRAME_PLAN_91}, + {"CopyFromDatabaseWithoutFlag", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyFromDatabaseWithoutFlagTrampoline, &FRAME_PLAN_92}, + {"CopyDatabaseFlag", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyDatabaseFlagTrampoline, &FRAME_PLAN_93}, + {"SchemaOrData", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CopySchema", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopySchemaTrampoline, &FRAME_PLAN_12}, + {"CopyData", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCopyDataTrampoline, &FRAME_PLAN_12}, + {"CreateIndexStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateIndexStmtTrampoline, &FRAME_PLAN_94}, + {"WithList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithListTrampoline, &FRAME_PLAN_95}, + {"RelOptionOrOids", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"RelOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRelOptionListTrampoline, &FRAME_PLAN_96}, + {"Oids", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOidsTrampoline, + &FRAME_PLAN_97}, + {"WithOrWithoutOids", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"WithOids", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithOidsTrampoline, &FRAME_PLAN_12}, + {"WithoutOids", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithoutOidsTrampoline, &FRAME_PLAN_12}, + {"IndexElement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIndexElementTrampoline, &FRAME_PLAN_98}, + {"UniqueIndex", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUniqueIndexTrampoline, &FRAME_PLAN_12}, + {"IndexType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIndexTypeTrampoline, &FRAME_PLAN_12}, + {"RelOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRelOptionTrampoline, &FRAME_PLAN_99}, + {"RelOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeRelOptionNameTrampoline, &FRAME_PLAN_100}, + {"DottedColLabel", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDottedColLabelTrampoline, &FRAME_PLAN_101}, + {"RelOptionArgumentOpt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRelOptionArgumentOptTrampoline, &FRAME_PLAN_102}, + {"DefArg", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DefArgNull", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefArgNullTrampoline, &FRAME_PLAN_103}, + {"DefArgKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefArgKeywordTrampoline, &FRAME_PLAN_12}, + {"DefArgStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefArgStringLiteralTrampoline, &FRAME_PLAN_12}, + {"NoneLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNoneLiteralTrampoline, &FRAME_PLAN_12}, + {"CreateMacroStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateMacroStmtTrampoline, &FRAME_PLAN_104}, + {"ReturnsType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_105}, + {"MacroOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"MacroKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMacroKeywordTrampoline, &FRAME_PLAN_12}, + {"FunctionKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionKeywordTrampoline, &FRAME_PLAN_12}, + {"MacroDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMacroDefinitionTrampoline, &FRAME_PLAN_106}, + {"MacroDefinitionBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"MacroParameters", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMacroParametersTrampoline, &FRAME_PLAN_107}, + {"MacroParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SimpleParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSimpleParameterTrampoline, &FRAME_PLAN_108}, + {"ScalarMacroDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeScalarMacroDefinitionTrampoline, &FRAME_PLAN_31}, + {"TableMacroDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableMacroDefinitionTrampoline, &FRAME_PLAN_109}, + {"CreateSchemaStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateSchemaStmtTrampoline, &FRAME_PLAN_110}, + {"WithOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithOptionListTrampoline, &FRAME_PLAN_16}, + {"CreateSecretStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateSecretStmtTrampoline, &FRAME_PLAN_111}, + {"SecretStorageSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSecretStorageSpecifierTrampoline, &FRAME_PLAN_12}, + {"SecretName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSecretNameTrampoline, &FRAME_PLAN_83}, + {"CreateSequenceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateSequenceStmtTrampoline, &FRAME_PLAN_112}, + {"SequenceOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SeqSetCycle", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SeqCycle", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqCycleTrampoline, &FRAME_PLAN_12}, + {"SeqNoCycle", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqNoCycleTrampoline, &FRAME_PLAN_12}, + {"SeqSetIncrement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqSetIncrementTrampoline, &FRAME_PLAN_17}, + {"SeqSetMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqSetMinMaxTrampoline, &FRAME_PLAN_113}, + {"SeqNoMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqNoMinMaxTrampoline, &FRAME_PLAN_114}, + {"SeqStartWith", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqStartWithTrampoline, &FRAME_PLAN_17}, + {"SeqOwnedBy", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSeqOwnedByTrampoline, &FRAME_PLAN_115}, + {"SeqMinOrMax", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeSeqMinOrMaxTrampoline, &FRAME_PLAN_19}, + {"MinValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMinValueTrampoline, &FRAME_PLAN_12}, + {"MaxValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMaxValueTrampoline, &FRAME_PLAN_12}, + {"CreateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateStatementTrampoline, &FRAME_PLAN_116}, + {"CreateStatementVariation", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOrReplaceTrampoline, &FRAME_PLAN_12}, + {"Temporary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"Persistent", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePersistentTrampoline, &FRAME_PLAN_12}, + {"TempPersistent", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTempPersistentTrampoline, &FRAME_PLAN_12}, + {"TemporaryPersistent", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTemporaryPersistentTrampoline, &FRAME_PLAN_12}, + {"CreateTableStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTableStmtTrampoline, &FRAME_PLAN_117}, + {"CreateTableDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CreateTableAs", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTableAsTrampoline, &FRAME_PLAN_118}, + {"PartitionSortedOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PartitionOptSortedOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePartitionOptSortedOptionsTrampoline, &FRAME_PLAN_119}, + {"SortedOptPartitionOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSortedOptPartitionOptionsTrampoline, &FRAME_PLAN_120}, + {"PartitionOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePartitionOptionsTrampoline, &FRAME_PLAN_121}, + {"SortedOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSortedOptionsTrampoline, &FRAME_PLAN_121}, + {"WithData", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"WithDataOnly", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithDataOnlyTrampoline, &FRAME_PLAN_12}, + {"WithNoData", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithNoDataTrampoline, &FRAME_PLAN_12}, + {"IdentifierList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIdentifierListTrampoline, &FRAME_PLAN_12}, + {"CreateColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateColumnListTrampoline, &FRAME_PLAN_122}, + {"IfNotExists", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIfNotExistsTrampoline, &FRAME_PLAN_12}, + {"QualifiedName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SchemaReservedIdentifierOrStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline, &FRAME_PLAN_123}, + {"CatalogReservedSchemaIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaIdentifierTrampoline, &FRAME_PLAN_124}, + {"IdentifierOrStringLiteral", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeIdentifierOrStringLiteralTrampoline, &FRAME_PLAN_54}, + {"ReservedIdentifierOrStringLiteral", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeReservedIdentifierOrStringLiteralTrampoline, &FRAME_PLAN_125}, + {"CatalogQualification", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogQualificationTrampoline, &FRAME_PLAN_12}, + {"SchemaQualification", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaQualificationTrampoline, &FRAME_PLAN_12}, + {"ReservedSchemaQualification", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReservedSchemaQualificationTrampoline, &FRAME_PLAN_12}, + {"TableQualification", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableQualificationTrampoline, &FRAME_PLAN_12}, + {"ReservedTableQualification", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReservedTableQualificationTrampoline, &FRAME_PLAN_12}, + {"CreateTableColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTableColumnListTrampoline, &FRAME_PLAN_126}, + {"CreateTableColumnElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CreateTableColumnDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTableColumnDefinitionTrampoline, &FRAME_PLAN_127}, + {"CreateTableConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTableConstraintTrampoline, &FRAME_PLAN_128}, + {"ColumnDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnDefinitionTrampoline, &FRAME_PLAN_129}, + {"ColumnConstraint", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NameableColumnConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNameableColumnConstraintTrampoline, &FRAME_PLAN_130}, + {"ColumnConstraintElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NotNullConstraint", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeNotNullConstraintTrampoline, &FRAME_PLAN_1}, + {"NullConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullConstraintTrampoline, &FRAME_PLAN_12}, + {"NotNullColumnConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotNullColumnConstraintTrampoline, &FRAME_PLAN_12}, + {"UniqueConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUniqueConstraintTrampoline, &FRAME_PLAN_131}, + {"PrimaryKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePrimaryKeyConstraintTrampoline, &FRAME_PLAN_132}, + {"ConstraintTiming", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ImmediateConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeImmediateConstraintTrampoline, &FRAME_PLAN_12}, + {"DeferredConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeferredConstraintTrampoline, &FRAME_PLAN_12}, + {"DefaultValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefaultValueTrampoline, &FRAME_PLAN_133}, + {"CheckConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCheckConstraintTrampoline, &FRAME_PLAN_134}, + {"ForeignKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForeignKeyConstraintTrampoline, &FRAME_PLAN_135}, + {"ColumnCollation", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnCollationTrampoline, &FRAME_PLAN_136}, + {"ColumnCompression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnCompressionTrampoline, &FRAME_PLAN_13}, + {"KeyActions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UpdateFirstKeyActions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateFirstKeyActionsTrampoline, &FRAME_PLAN_137}, + {"DeleteFirstKeyActions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeleteFirstKeyActionsTrampoline, &FRAME_PLAN_138}, + {"UpdateAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateActionTrampoline, &FRAME_PLAN_139}, + {"DeleteAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeleteActionTrampoline, &FRAME_PLAN_139}, + {"KeyAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeKeyActionTrampoline, &FRAME_PLAN_19}, + {"NoKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNoKeyActionTrampoline, &FRAME_PLAN_12}, + {"RestrictKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRestrictKeyActionTrampoline, &FRAME_PLAN_12}, + {"CascadeKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCascadeKeyActionTrampoline, &FRAME_PLAN_12}, + {"SetNullKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetNullKeyActionTrampoline, &FRAME_PLAN_12}, + {"SetDefaultKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetDefaultKeyActionTrampoline, &FRAME_PLAN_12}, + {"TopLevelConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTopLevelConstraintTrampoline, &FRAME_PLAN_140}, + {"TopLevelConstraintList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TopCheckConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTopCheckConstraintTrampoline, &FRAME_PLAN_141}, + {"TopPrimaryKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTopPrimaryKeyConstraintTrampoline, &FRAME_PLAN_142}, + {"TopUniqueConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTopUniqueConstraintTrampoline, &FRAME_PLAN_143}, + {"TopForeignKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTopForeignKeyConstraintTrampoline, &FRAME_PLAN_144}, + {"ColumnIdList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnIdListTrampoline, &FRAME_PLAN_145}, + {"DottedIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDottedIdentifierTrampoline, &FRAME_PLAN_146}, + {"DotColLabel", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDotColLabelTrampoline, &FRAME_PLAN_147}, + {"Identifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIdentifierTrampoline, &FRAME_PLAN_12}, + {"ColId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeColIdTrampoline, &FRAME_PLAN_148}, + {"ColIdOrString", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeColIdOrStringTrampoline, &FRAME_PLAN_149}, + {"TypeFuncName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeTypeFuncNameTrampoline, &FRAME_PLAN_150}, + {"TypeFuncKeyword", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeTypeFuncKeywordTrampoline, &FRAME_PLAN_151}, + {"ColLabel", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeColLabelTrampoline, &FRAME_PLAN_152}, + {"ColLabelOrString", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeColLabelOrStringTrampoline, &FRAME_PLAN_149}, + {"ColLabelIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColLabelIdentifierTrampoline, &FRAME_PLAN_153}, + {"StringLiteralIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStringLiteralIdentifierTrampoline, &FRAME_PLAN_12}, + {"GeneratedColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGeneratedColumnTrampoline, &FRAME_PLAN_154}, + {"Generated", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"GeneratedAlways", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGeneratedAlwaysTrampoline, &FRAME_PLAN_12}, + {"GeneratedByDefault", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGeneratedByDefaultTrampoline, &FRAME_PLAN_12}, + {"GeneratedColumnType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CommitAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommitActionTrampoline, &FRAME_PLAN_155}, + {"PreserveOrDelete", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PreserveRows", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePreserveRowsTrampoline, &FRAME_PLAN_12}, + {"DeleteRows", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeleteRowsTrampoline, &FRAME_PLAN_12}, + {"VirtualGeneratedColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVirtualGeneratedColumnTrampoline, &FRAME_PLAN_12}, + {"StoredGeneratedColumn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStoredGeneratedColumnTrampoline, &FRAME_PLAN_12}, + {"CreateTriggerStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTriggerStmtTrampoline, &FRAME_PLAN_156}, + {"TriggerBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TriggerName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerNameTrampoline, &FRAME_PLAN_12}, + {"ReferencingClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReferencingClauseTrampoline, &FRAME_PLAN_157}, + {"ReferencingItem", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ReferencingNewTableAs", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReferencingNewTableAsTrampoline, &FRAME_PLAN_158}, + {"ReferencingOldTableAs", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReferencingOldTableAsTrampoline, &FRAME_PLAN_158}, + {"TriggerTiming", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TriggerBefore", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerBeforeTrampoline, &FRAME_PLAN_12}, + {"TriggerAfter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerAfterTrampoline, &FRAME_PLAN_12}, + {"TriggerInsteadOf", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerInsteadOfTrampoline, &FRAME_PLAN_12}, + {"TriggerEvent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TriggerEventInsert", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerEventInsertTrampoline, &FRAME_PLAN_12}, + {"TriggerEventDelete", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerEventDeleteTrampoline, &FRAME_PLAN_12}, + {"TriggerEventUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerEventUpdateTrampoline, &FRAME_PLAN_12}, + {"TriggerEventUpdateOf", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerEventUpdateOfTrampoline, &FRAME_PLAN_159}, + {"TriggerColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTriggerColumnListTrampoline, &FRAME_PLAN_160}, + {"ForEachClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ForEachRow", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForEachRowTrampoline, &FRAME_PLAN_12}, + {"ForEachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForEachStatementTrampoline, &FRAME_PLAN_12}, + {"CreateTypeStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTypeStmtTrampoline, &FRAME_PLAN_161}, + {"CreateType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CreateTypeFromType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateTypeFromTypeTrampoline, &FRAME_PLAN_162}, + {"EnumSelectType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEnumSelectTypeTrampoline, &FRAME_PLAN_163}, + {"EnumStringLiteralList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEnumStringLiteralListTrampoline, &FRAME_PLAN_164}, + {"CreateViewStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateViewStmtTrampoline, &FRAME_PLAN_165}, + {"CreateRecursive", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateRecursiveTrampoline, &FRAME_PLAN_12}, + {"CreateSecure", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateSecureTrampoline, &FRAME_PLAN_12}, + {"DeallocateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeallocateStatementTrampoline, &FRAME_PLAN_166}, + {"DeallocatePrepare", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeallocatePrepareTrampoline, &FRAME_PLAN_12}, + {"DeleteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeleteStatementTrampoline, &FRAME_PLAN_167}, + {"TruncateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTruncateStatementTrampoline, &FRAME_PLAN_168}, + {"TruncateOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TruncateAliasOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTruncateAliasOptionsTrampoline, &FRAME_PLAN_169}, + {"TruncateDropBehavior", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTruncateDropBehaviorTrampoline, &FRAME_PLAN_170}, + {"TargetOptAlias", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTargetOptAliasTrampoline, &FRAME_PLAN_171}, + {"TargetAlias", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTargetAliasTrampoline, &FRAME_PLAN_32}, + {"DeleteUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeleteUsingClauseTrampoline, &FRAME_PLAN_172}, + {"DescribeStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeDescribeStatementTrampoline, &FRAME_PLAN_1}, + {"ShowExternalResources", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowExternalResourcesTrampoline, &FRAME_PLAN_173}, + {"ShowExternalResourcesType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_13}, + {"ShowDeprecatedSelect", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline, &FRAME_PLAN_174}, + {"DescribeSelect", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescribeSelectTrampoline, &FRAME_PLAN_175}, + {"ShowAllTables", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowAllTablesTrampoline, &FRAME_PLAN_176}, + {"ShowTables", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowTablesTrampoline, &FRAME_PLAN_177}, + {"ShowByName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowByNameTrampoline, &FRAME_PLAN_178}, + {"DescribeByName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescribeByNameTrampoline, &FRAME_PLAN_179}, + {"DescribeOrSummarize", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ShowTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeShowTargetTrampoline, &FRAME_PLAN_180}, + {"ShowDeprecatedQualifiedTableName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline, &FRAME_PLAN_181}, + {"ShowSettingName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowSettingNameTrampoline, &FRAME_PLAN_12}, + {"DescribeTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DescribeBaseTableName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline, &FRAME_PLAN_182}, + {"DescribeStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline, &FRAME_PLAN_12}, + {"Summarize", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSummarizeTrampoline, &FRAME_PLAN_183}, + {"SummarizeRule", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSummarizeRuleTrampoline, &FRAME_PLAN_12}, + {"ShowOrDescribe", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ShowRule", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowRuleTrampoline, &FRAME_PLAN_12}, + {"DescribeRule", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DescribeLongRule", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescribeLongRuleTrampoline, &FRAME_PLAN_12}, + {"DescRule", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescRuleTrampoline, &FRAME_PLAN_12}, + {"DetachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDetachStatementTrampoline, &FRAME_PLAN_184}, + {"DropStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropStatementTrampoline, &FRAME_PLAN_185}, + {"DropEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DropTrigger", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_186}, + {"DropTable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_187}, + {"DropTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_188}, + {"DropFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_189}, + {"DropSchema", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_190}, + {"DropIndex", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_191}, + {"QualifiedIndexName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"QualifiedIndexNameString", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifiedIndexNameStringTrampoline, &FRAME_PLAN_12}, + {"SchemaReservedIndex", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline, &FRAME_PLAN_56}, + {"CatalogReservedSchemaIndex", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_192}, + {"DropSequence", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_193}, + {"DropCollation", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_194}, + {"DropType", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_195}, + {"DropSecret", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_196}, + {"TableOrView", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"MaterializedViewEntry", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMaterializedViewEntryTrampoline, &FRAME_PLAN_12}, + {"FunctionTypeMacro", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"FunctionTypeMacroKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionTypeMacroKeywordTrampoline, &FRAME_PLAN_12}, + {"FunctionTypeFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionTypeFunctionTrampoline, &FRAME_PLAN_12}, + {"DropBehavior", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CascadeDropBehavior", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCascadeDropBehaviorTrampoline, &FRAME_PLAN_12}, + {"RestrictDropBehavior", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRestrictDropBehaviorTrampoline, &FRAME_PLAN_12}, + {"IfExists", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIfExistsTrampoline, &FRAME_PLAN_12}, + {"DropSecretStorage", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline, &FRAME_PLAN_12}, + {"ExecuteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_197}, + {"ExplainStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_198}, + {"ExplainOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_199}, + {"ExplainOption", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_200}, + {"ExplainOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_201}, + {"ExplainSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_202}, + {"ExplainableStatements", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_203}, + {"ExportSource", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExportSourceTrampoline, &FRAME_PLAN_12}, + {"ExportOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ImportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeImportStatementTrampoline, &FRAME_PLAN_12}, + {"ColumnReference", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeColumnReferenceTrampoline, &FRAME_PLAN_1}, + {"NestedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_204}, + {"CatalogReservedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_205}, + {"SchemaReservedTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_206}, + {"TableReservedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_207}, + {"FunctionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_208}, + {"FunctionExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_209}, + {"FunctionExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_210}, + {"FunctionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_211}, + {"FunctionIdentifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"FunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, + {"CatalogReservedSchemaFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_212}, + {"SchemaReservedFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline, &FRAME_PLAN_56}, + {"DistinctOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DistinctKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDistinctKeywordTrampoline, &FRAME_PLAN_12}, + {"AllKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAllKeywordTrampoline, &FRAME_PLAN_12}, + {"WithinGroupClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_213}, + {"FilterClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_214}, + {"FilterClauseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_215}, + {"FilterClauseContents", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline, &FRAME_PLAN_21}, + {"IgnoreOrRespectNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IgnoreNulls", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIgnoreNullsTrampoline, &FRAME_PLAN_12}, + {"RespectNulls", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRespectNullsTrampoline, &FRAME_PLAN_12}, + {"ParenthesisExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeParenthesisExpressionTrampoline, &FRAME_PLAN_57}, + {"LiteralExpression", &PEGTransformerFactory::InitializeLiteralExpressionTrampoline, + &PEGTransformerFactory::FinalizeLiteralExpressionTrampoline, nullptr}, + {"ConstantLiteral", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeConstantLiteralTrampoline, &FRAME_PLAN_1}, + {"NullLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullLiteralTrampoline, &FRAME_PLAN_12}, + {"TrueLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrueLiteralTrampoline, &FRAME_PLAN_12}, + {"FalseLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFalseLiteralTrampoline, &FRAME_PLAN_12}, + {"CastExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_216}, + {"CastArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_217}, + {"CastOrTryCast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCastKeywordTrampoline, &FRAME_PLAN_12}, + {"TryCastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTryCastKeywordTrampoline, &FRAME_PLAN_12}, + {"ColIdDot", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColIdDotTrampoline, &FRAME_PLAN_83}, + {"StarExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_218}, + {"StarQualifierList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_219}, + {"ExcludeList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_220}, + {"ExcludeNames", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExcludeNameList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_221}, + {"ExcludeNameSingle", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_222}, + {"ExcludeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExcludeDottedName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_223}, + {"ExcludeColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline, &FRAME_PLAN_38}, + {"ReplaceList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_224}, + {"ReplaceEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ReplaceEntrySingle", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_225}, + {"ReplaceEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_226}, + {"ReplaceEntry", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_227}, + {"RenameList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_228}, + {"RenameEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"RenameEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_229}, + {"SingleRenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_230}, + {"RenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_222}, + {"SubqueryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_231}, + {"SubqueryNot", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubqueryNotTrampoline, &FRAME_PLAN_12}, + {"SubqueryExists", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubqueryExistsTrampoline, &FRAME_PLAN_12}, + {"CaseExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SimpleCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_232}, + {"SearchedCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_233}, + {"SimpleCaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_234}, + {"SimpleCaseWhenOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SimpleCaseWhenEquals", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline, &FRAME_PLAN_31}, + {"CaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_235}, + {"CaseElse", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCaseElseTrampoline, &FRAME_PLAN_21}, + {"TypeLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTypeLiteralTrampoline, &FRAME_PLAN_162}, + {"IntervalLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_236}, + {"IntervalParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IntervalStringParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline, &FRAME_PLAN_12}, + {"FrameClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_237}, + {"Framing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeFramingTrampoline, &FRAME_PLAN_19}, + {"RowsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowsFramingTrampoline, &FRAME_PLAN_12}, + {"RangeFraming", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRangeFramingTrampoline, &FRAME_PLAN_12}, + {"GroupsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupsFramingTrampoline, &FRAME_PLAN_12}, + {"FrameExtent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SingleFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_238}, + {"BetweenFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_239}, + {"FrameBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"FrameUnbounded", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_240}, + {"FrameExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_241}, + {"FrameCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline, &FRAME_PLAN_12}, + {"PrecedingOrFollowing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PrecedingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePrecedingFrameTrampoline, &FRAME_PLAN_12}, + {"FollowingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFollowingFrameTrampoline, &FRAME_PLAN_12}, + {"WindowExcludeClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_242}, + {"WindowExcludeElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExcludeCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeCurrentRowTrampoline, &FRAME_PLAN_12}, + {"ExcludeGroup", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeGroupTrampoline, &FRAME_PLAN_12}, + {"ExcludeTies", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeTiesTrampoline, &FRAME_PLAN_12}, + {"ExcludeNoOthers", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeNoOthersTrampoline, &FRAME_PLAN_12}, + {"OverClause", &PEGTransformerFactory::InitializeOverClauseTrampoline, + &PEGTransformerFactory::FinalizeOverClauseTrampoline, nullptr}, + {"WindowFrame", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IdentifierWindowFrame", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIdentifierWindowFrameTrampoline, &FRAME_PLAN_12}, + {"ParensIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeParensIdentifierTrampoline, &FRAME_PLAN_12}, + {"WindowFrameDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"WindowFrameNameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_243}, + {"WindowFrameNameContents", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_244}, + {"WindowFrameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_245}, + {"WindowFrameContents", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_246}, + {"BaseWindowName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline, &FRAME_PLAN_12}, + {"WindowPartition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_247}, + {"ListExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ArrayBoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_248}, + {"ArrayParensSelect", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline, &FRAME_PLAN_163}, + {"BoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_249}, + {"StructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_250}, + {"StructField", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_251}, + {"MapExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_252}, + {"MapStructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_253}, + {"MapStructField", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_254}, + {"GroupingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_255}, + {"GroupingOrGroupingId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"GroupingKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupingKeywordTrampoline, &FRAME_PLAN_12}, + {"GroupingIdKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupingIdKeywordTrampoline, &FRAME_PLAN_12}, + {"Parameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"QuestionMarkNumberedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuestionMarkNumberedParameterTrampoline, &FRAME_PLAN_12}, + {"AnonymousParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnonymousParameterTrampoline, &FRAME_PLAN_12}, + {"NumberedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNumberedParameterTrampoline, &FRAME_PLAN_12}, + {"ColLabelParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColLabelParameterTrampoline, &FRAME_PLAN_147}, + {"PositionalExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePositionalExpressionTrampoline, &FRAME_PLAN_12}, + {"DefaultExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline, &FRAME_PLAN_12}, + {"ListComprehensionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_256}, + {"ListComprehensionFilter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline, &FRAME_PLAN_21}, + {"ParensExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_257}, + {"MeasureSemanticsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_258}, + {"SingleExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"Expression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_259}, + {"ColumnDefaultExpr", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_260}, + {"LambdaArrowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline, &FRAME_PLAN_261}, + {"SingleArrowPair", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSingleArrowPairTrampoline, &FRAME_PLAN_262}, + {"LogicalOrExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_263}, + {"LogicalOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_264}, + {"ColDefOrExpr", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_265}, + {"ColDefOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_266}, + {"LogicalAndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_267}, + {"LogicalAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_268}, + {"ColDefAndExpr", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_269}, + {"ColDefAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_270}, + {"LogicalNotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_271}, + {"NotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_272}, + {"NotKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_12}, + {"IsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_273}, + {"IsExpressionContinuation", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_274}, + {"IsExpressionTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IsTestTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_275}, + {"IsDistinctTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_276}, + {"IsComparisonTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_277}, + {"IsOtherOperatorTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_278}, + {"IsCastTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_279}, + {"IsTest", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IsLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_280}, + {"IsLiteralValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UnknownLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnknownLiteralTrampoline, &FRAME_PLAN_12}, + {"NotNull", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NotNullKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotNullKeywordTrampoline, &FRAME_PLAN_12}, + {"NotNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_12}, + {"IsNull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullTrampoline, + &FRAME_PLAN_281}, + {"IsNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_12}, + {"IsDistinctFromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_282}, + {"IsDistinctFromTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_283}, + {"IsDistinctFromOp", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_12}, + {"ComparisonExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_284}, + {"ComparisonExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_285}, + {"ComparisonOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NotComparisonOperand", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_286}, + {"ComparisonOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OperatorEqual", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorEqualTrampoline, &FRAME_PLAN_12}, + {"OperatorNotEqual", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorNotEqualTrampoline, &FRAME_PLAN_12}, + {"OperatorLessThan", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorLessThanTrampoline, &FRAME_PLAN_12}, + {"OperatorGreaterThan", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorGreaterThanTrampoline, &FRAME_PLAN_12}, + {"OperatorLessThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorLessThanEqualsTrampoline, &FRAME_PLAN_12}, + {"OperatorGreaterThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_12}, + {"BetweenInLikeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_287}, + {"InPredicate", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_288}, + {"BetweenLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_289}, + {"BetweenLikeOpExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"LikeClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_290}, + {"EscapeClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_291}, + {"LikeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, &FRAME_PLAN_19}, + {"LikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLikeTokenTrampoline, &FRAME_PLAN_12}, + {"ILikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeILikeTokenTrampoline, &FRAME_PLAN_12}, + {"GlobToken", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGlobTokenTrampoline, &FRAME_PLAN_12}, + {"SimilarToToken", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSimilarToTokenTrampoline, &FRAME_PLAN_12}, + {"RegexMatchToken", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRegexMatchTokenTrampoline, &FRAME_PLAN_12}, + {"RegexInsensitiveMatchToken", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRegexInsensitiveMatchTokenTrampoline, &FRAME_PLAN_12}, + {"NotILikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotILikeOpTrampoline, &FRAME_PLAN_12}, + {"NotLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotLikeOpTrampoline, &FRAME_PLAN_12}, + {"NotRegexInsensitiveMatchOp", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotRegexInsensitiveMatchOpTrampoline, &FRAME_PLAN_12}, + {"NotSimilarToOp", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_12}, + {"InClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_292}, + {"InExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"InContainsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_293}, + {"InExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_294}, + {"InSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_295}, + {"BetweenClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_296}, + {"OtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_297}, + {"InfixOtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_298}, + {"OtherOperatorTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AnyAllSubqueryTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_299}, + {"OtherOperatorExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_300}, + {"OtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"AnyAllParsedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_301}, + {"NamedOtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, &FRAME_PLAN_54}, + {"OperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOperatorLiteralTrampoline, &FRAME_PLAN_12}, + {"AnyOperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_12}, + {"AnyAllOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_302}, + {"AnyOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SubqueryAny", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubqueryAnyTrampoline, &FRAME_PLAN_12}, + {"SubqueryAll", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_12}, + {"QualifiedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_303}, + {"QualifiedOperatorContents", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_304}, + {"BitwiseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_305}, + {"BitwiseExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_306}, + {"BitOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_12}, + {"TildeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_307}, + {"AdditiveExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_308}, + {"AdditiveExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_309}, + {"Term", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTermTrampoline, + &FRAME_PLAN_12}, + {"MultiplicativeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_310}, + {"MultiplicativeExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_311}, + {"Factor", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFactorTrampoline, + &FRAME_PLAN_12}, + {"ExponentiationExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_312}, + {"ExponentiationExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_313}, + {"ExponentOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_12}, + {"CollateExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_314}, + {"CollateExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_315}, + {"AtTimeZoneExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_316}, + {"AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_317}, + {"UnaryExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, + &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, + {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_318}, + {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_19}, + {"MinusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMinusPrefixOperatorTrampoline, &FRAME_PLAN_12}, + {"PlusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePlusPrefixOperatorTrampoline, &FRAME_PLAN_12}, + {"TildePrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_12}, + {"BaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_319}, + {"IndirectionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_320}, + {"Indirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CastOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCastOperatorTrampoline, &FRAME_PLAN_105}, + {"DotOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DotMethodOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_321}, + {"DotColumnOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_147}, + {"MethodExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_322}, + {"MethodExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_323}, + {"MethodExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_324}, + {"MethodFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_211}, + {"SliceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_325}, + {"SliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_326}, + {"SliceUpperBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"MinusStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_327}, + {"EndStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_328}, + {"EndSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_66}, + {"StepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStepSliceBoundTrampoline, &FRAME_PLAN_66}, + {"PostfixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePostfixOperatorTrampoline, &FRAME_PLAN_12}, + {"SpecialFunctionExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CoalesceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_329}, + {"UnpackExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_134}, + {"TryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_134}, + {"ColumnsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_330}, + {"ExtractExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_331}, + {"ExtractArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_332}, + {"LambdaExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_333}, + {"NullIfExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_334}, + {"NullIfArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_254}, + {"PositionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_335}, + {"PositionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_336}, + {"RowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_337}, + {"SubstringExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_338}, + {"SubstringArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SubstringExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_339}, + {"SubstringParameters", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_340}, + {"SubstringFromFor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SubstringFromOptionalFor", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_341}, + {"SubstringFor", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_342}, + {"TrimExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_343}, + {"TrimArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_344}, + {"TrimDirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, &FRAME_PLAN_19}, + {"TrimBoth", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrimBothTrampoline, &FRAME_PLAN_12}, + {"TrimLeading", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrimLeadingTrampoline, &FRAME_PLAN_12}, + {"TrimTrailing", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_12}, + {"TrimSource", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_345}, + {"OverlayExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_346}, + {"OverlayArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OverlayParameters", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_347}, + {"FromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_21}, + {"ForExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_21}, + {"OverlayExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_339}, + {"ExtractArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExtractDatePartArgument", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_348}, + {"ExtractIdentifierArgument", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_12}, + {"ExtractStringArgument", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline, &FRAME_PLAN_12}, + {"ExtractDatePart", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExternalResourceStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CreateExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_349}, + {"RegisterExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_350}, + {"DestroyExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_351}, + {"ExternalResourceCreationOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_33}, + {"AttachToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_352}, + {"ConnectToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_353}, + {"ExternalResourceSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ExternalResourceCreateClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_354}, + {"ExternalResourceReferenceClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_32}, + {"InsertStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_355}, + {"OrAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"InsertOrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertOrReplaceTrampoline, &FRAME_PLAN_12}, + {"InsertOrIgnore", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertOrIgnoreTrampoline, &FRAME_PLAN_12}, + {"ByNameOrPosition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"InsertByNameOrder", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_356}, + {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_357}, + {"InsertByName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_12}, + {"InsertByPosition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_12}, + {"InsertTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_358}, + {"InsertAlias", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_12}, + {"ColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnListTrampoline, &FRAME_PLAN_160}, + {"InsertColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertColumnListTrampoline, &FRAME_PLAN_82}, + {"InsertValues", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SelectInsertValues", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_202}, + {"DefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_12}, + {"OnConflictClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_359}, + {"OnConflictTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OnConflictExpressionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_360}, + {"OnConflictIndexTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_361}, + {"OnConflictAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OnConflictUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_362}, + {"OnConflictNothing", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_12}, + {"ReturningClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_363}, + {"LoadStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_364}, + {"ExtensionAlias", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_12}, + {"InstallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_365}, + {"InstallAndLoad", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_12}, + {"UpdateExtensionsStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline, &FRAME_PLAN_12}, + {"FromSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"FromSourceIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_12}, + {"FromSourceString", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_12}, + {"VersionNumber", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_366}, + {"ExtensionRepositoryStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_367}, + {"RepositoryPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_12}, + {"RepositoryPublicKey", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_12}, + {"DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_368}, + {"TableMatchRecognizeClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_369}, + {"MatchRecognizeBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_370}, + {"MatchRecognizeClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"MRPartition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_371}, + {"MROrderBy", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_372}, + {"MRMeasures", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_373}, + {"MRRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRRowsTrampoline, + &FRAME_PLAN_374}, + {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, + &FRAME_PLAN_375}, + {"MRPattern", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_376}, + {"MRSubset", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_377}, + {"MRDefineAuto", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_12}, + {"MRDefine", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_378}, + {"MeasuresClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_379}, + {"MeasuresElement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_380}, + {"MeasureSemantics", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"RunningSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRunningSemanticsTrampoline, &FRAME_PLAN_12}, + {"FinalSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFinalSemanticsTrampoline, &FRAME_PLAN_12}, + {"RowsPerMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OneRowPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_12}, + {"AllRowsPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_381}, + {"AllRowsEmptyMatches", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ShowEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowEmptyMatchesTrampoline, &FRAME_PLAN_12}, + {"OmitEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOmitEmptyMatchesTrampoline, &FRAME_PLAN_12}, + {"WithUnmatchedRows", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_12}, + {"AfterMatchSkip", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_382}, + {"AfterMatchSkipTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SkipToNextRow", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSkipToNextRowTrampoline, &FRAME_PLAN_12}, + {"SkipPastLastRow", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_12}, + {"SkipToFirstVar", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_383}, + {"SkipToLastVar", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_383}, + {"SkipToVar", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_384}, + {"PatternClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_385}, + {"RowPattern", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_386}, + {"RowPatternAlternative", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_387}, + {"RowPatternTerm", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_388}, + {"RowPatternFactor", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_389}, + {"RowPatternPrimary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"RowPatternPermute", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_390}, + {"RowPatternAnchor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PatternStart", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePatternStartTrampoline, &FRAME_PLAN_12}, + {"PatternEnd", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_12}, + {"RowPatternGroup", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_391}, + {"RowPatternEmpty", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_12}, + {"RowPatternExclusion", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_392}, + {"RowPatternLabel", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_393}, + {"RowPatternQuantifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_394}, + {"RowPatternQuantifierKind", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"QuantifierReluctant", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierReluctantTrampoline, &FRAME_PLAN_12}, + {"QuantifierStar", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierStarTrampoline, &FRAME_PLAN_12}, + {"QuantifierPlus", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierPlusTrampoline, &FRAME_PLAN_12}, + {"QuantifierOptional", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_12}, + {"QuantifierRange", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_395}, + {"QuantifierBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"QuantifierMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierMinMaxTrampoline, &FRAME_PLAN_12}, + {"QuantifierMin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierMinTrampoline, &FRAME_PLAN_12}, + {"QuantifierMax", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierMaxTrampoline, &FRAME_PLAN_12}, + {"QuantifierExact", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_12}, + {"SubsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_396}, + {"SubsetElement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_397}, + {"DefineClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_398}, + {"DefineElement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_399}, + {"MergeIntoStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_400}, + {"MergeIntoUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_401}, + {"MergeMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"MatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_402}, + {"MatchedClauseAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UpdateMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_403}, + {"UpdateMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UpdateMatchSetAction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_404}, + {"UpdateByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_405}, + {"DeleteMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_12}, + {"InsertMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_406}, + {"InsertMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"InsertDefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_12}, + {"InsertByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_407}, + {"InsertValuesList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_408}, + {"DoNothingMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_12}, + {"ErrorMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_66}, + {"UpdateMatchSetClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_409}, + {"UpdateMatchSetInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_80}, + {"AndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_21}, + {"NotMatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_410}, + {"BySourceOrTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"BySource", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBySourceTrampoline, &FRAME_PLAN_12}, + {"ByTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeByTargetTrampoline, &FRAME_PLAN_12}, + {"PivotStatement", &PEGTransformerFactory::InitializePivotStatementTrampoline, + &PEGTransformerFactory::FinalizePivotStatementTrampoline, nullptr}, + {"PivotOn", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotOnTrampoline, + &FRAME_PLAN_411}, + {"PivotUsing", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_363}, + {"PivotColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_412}, + {"PivotColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PivotColumnExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_31}, + {"PivotColumnSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_413}, + {"UnpivotStatement", &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, + &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline, nullptr}, + {"IntoNameValues", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_414}, + {"OptionalParensNameList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ParenthesizedNameList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_415}, + {"BareNameList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_416}, + {"IncludeOrExcludeNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"IncludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIncludeNullsTrampoline, &FRAME_PLAN_12}, + {"ExcludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExcludeNullsTrampoline, &FRAME_PLAN_12}, + {"UnpivotHeader", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UnpivotHeaderSingle", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_38}, + {"UnpivotHeaderList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_415}, + {"PragmaStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_417}, + {"PragmaAssignOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PragmaAssign", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_418}, + {"PragmaFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_419}, + {"PragmaParameters", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_294}, + {"PrepareStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_420}, + {"TypeList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_421}, + {"SelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_202}, + {"SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, + &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline, nullptr}, + {"SelectSetOpChain", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_422}, + {"SelectSetOpChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_423}, + {"IntersectChain", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_424}, + {"IntersectChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_425}, + {"SetIntersectClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_426}, + {"SelectAtom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_295}, + {"SetopClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_427}, + {"SetopType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SetopUnion", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetopUnionTrampoline, &FRAME_PLAN_12}, + {"SetopExcept", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetopExceptTrampoline, &FRAME_PLAN_12}, + {"SelectStatementType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ResultModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_428}, + {"LimitOffset", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"LimitOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_429}, + {"OffsetLimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_430}, + {"OffsetFetchClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_431}, + {"FetchOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_432}, + {"FetchOnlyClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_433}, + {"TableStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_434}, + {"OptionalParensSimpleSelect", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SimpleSelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_435}, + {"SimpleSelect", &PEGTransformerFactory::InitializeSimpleSelectTrampoline, + &PEGTransformerFactory::FinalizeSimpleSelectTrampoline, nullptr}, + {"SelectFrom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SelectFromClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_436}, + {"FromSelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_437}, + {"WithStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_438}, + {"CTEBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CTESelectBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_295}, + {"CTEDMLBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_439}, + {"UsingKey", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_440}, + {"Materialized", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_12}, + {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, + &PEGTransformerFactory::FinalizeWithClauseTrampoline, nullptr}, + {"SelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_441}, + {"TargetList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_442}, + {"ColumnAliases", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_415}, + {"DistinctClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DistinctAll", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_12}, + {"DistinctOn", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_443}, + {"DistinctOnTargets", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_329}, + {"InnerTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, + &PEGTransformerFactory::FinalizeTableRefTrampoline, nullptr}, + {"TableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_444}, + {"BaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_445}, + {"TableAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_38}, + {"ValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_446}, + {"ParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_447}, + {"JoinOrPivot", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TablePivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_448}, + {"TablePivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_449}, + {"PivotGroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_450}, + {"TableUnpivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_451}, + {"TableUnpivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_452}, + {"PivotHeader", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_453}, + {"PivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_454}, + {"PivotValueTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"PivotEnumTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_12}, + {"PivotListTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_455}, + {"UnpivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_456}, + {"PivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_457}, + {"UnpivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_457}, + {"Lateral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeLateralTrampoline, + &FRAME_PLAN_12}, + {"BaseTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UnqualifiedBaseTableName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUnqualifiedBaseTableNameTrampoline, &FRAME_PLAN_12}, + {"QualifiedTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SchemaReservedTable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSchemaReservedTableTrampoline, &FRAME_PLAN_56}, + {"CatalogReservedSchemaTable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableTrampoline, &FRAME_PLAN_55}, + {"TableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TableFunctionLateralOpt", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_458}, + {"TableFunctionAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_459}, + {"WithOrdinality", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_12}, + {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline, &FRAME_PLAN_460}, + {"TableFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_461}, + {"FunctionArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NamedFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_462}, + {"PositionalFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_31}, + {"NamedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_463}, + {"TableAlias", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"TableAliasAs", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_464}, + {"TableAliasWithoutAs", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_465}, + {"AtClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_466}, + {"AtSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_467}, + {"AtUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_19}, + {"VersionAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVersionAtUnitTrampoline, &FRAME_PLAN_12}, + {"TimestampAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTimestampAtUnitTrampoline, &FRAME_PLAN_12}, + {"JoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NearestJoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NearestJoinAliased", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_468}, + {"NearestJoinBare", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_469}, + {"NearestBareTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NearestValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_470}, + {"NearestTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_471}, + {"NearestTableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_472}, + {"NearestBaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_473}, + {"NearestParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_474}, + {"ApproxOrExact", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NearestApprox", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestApproxTrampoline, &FRAME_PLAN_12}, + {"NearestExact", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestExactTrampoline, &FRAME_PLAN_12}, + {"DistanceOrSimilarity", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NearestDistance", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestDistanceTrampoline, &FRAME_PLAN_12}, + {"NearestSimilarity", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_12}, + {"RegularJoinClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_475}, + {"JoinByClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_476}, + {"Asof", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAsofTrampoline, + &FRAME_PLAN_12}, + {"JoinWithoutOnClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_477}, + {"JoinQualifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OnClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_21}, + {"UsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_478}, + {"UsingColumnName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, &FRAME_PLAN_149}, + {"JoinType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"JoinPrefix", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CrossJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_12}, + {"NaturalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_479}, + {"PositionalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_12}, + {"FullJoin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFullJoinTrampoline, &FRAME_PLAN_12}, + {"LeftJoin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLeftJoinTrampoline, &FRAME_PLAN_12}, + {"RightJoin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRightJoinTrampoline, &FRAME_PLAN_12}, + {"SemiJoin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSemiJoinTrampoline, &FRAME_PLAN_12}, + {"AntiJoin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAntiJoinTrampoline, &FRAME_PLAN_12}, + {"InnerJoin", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeInnerJoinTrampoline, &FRAME_PLAN_12}, + {"FromClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFromClauseTrampoline, &FRAME_PLAN_172}, + {"WhereClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_21}, + {"GroupByClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_480}, + {"HavingClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_21}, + {"QualifyClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_21}, + {"SampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_481}, + {"SelectSampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_481}, + {"WindowClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_482}, + {"WindowDefinition", &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, + &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline, nullptr}, + {"SampleEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SampleEntryCount", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_483}, + {"SampleEntryFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_484}, + {"SampleFunction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_83}, + {"SampleProperties", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_485}, + {"RepeatableSample", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_486}, + {"SampleSeed", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_12}, + {"SampleCount", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_487}, + {"SampleValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SampleUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SamplePercentage", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSamplePercentageTrampoline, &FRAME_PLAN_12}, + {"SampleRows", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSampleRowsTrampoline, &FRAME_PLAN_12}, + {"GroupByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"GroupByAll", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_12}, + {"GroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_488}, + {"GroupByExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"GroupByBaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupByBaseExpressionTrampoline, &FRAME_PLAN_31}, + {"EmptyGroupingItem", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_12}, + {"CubeOrRollupClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_489}, + {"CubeOrRollup", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, &FRAME_PLAN_19}, + {"CubeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCubeKeywordTrampoline, &FRAME_PLAN_12}, + {"RollupKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_12}, + {"GroupingSetsClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_490}, + {"SubqueryReference", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_295}, + {"OrderByExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_98}, + {"DescOrAsc", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DescendingOrder", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDescendingOrderTrampoline, &FRAME_PLAN_12}, + {"AscendingOrder", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeAscendingOrderTrampoline, &FRAME_PLAN_12}, + {"NullsFirstOrLast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"NullsFirst", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullsFirstTrampoline, &FRAME_PLAN_12}, + {"NullsLast", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_12}, + {"OrderByClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_491}, + {"OrderByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"OrderByExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_492}, + {"OrderByAll", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_493}, + {"LimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_494}, + {"OffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_495}, + {"OffsetValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_31}, + {"LimitValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"LimitAll", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLimitAllTrampoline, &FRAME_PLAN_12}, + {"LimitLiteralPercent", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLimitLiteralPercentTrampoline, &FRAME_PLAN_12}, + {"LimitExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLimitExpressionTrampoline, &FRAME_PLAN_31}, + {"FetchClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"FetchClauseWithoutValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_12}, + {"FetchClauseWithValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_496}, + {"FetchValue", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_31}, + {"AliasedExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ColIdExpression", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_497}, + {"ExpressionAsCollabel", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_380}, + {"ExpressionOptIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_31}, + {"ValuesClause", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_498}, + {"ValuesExpressions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_294}, + {"SetStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SetKeywordStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_499}, + {"VariableAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_500}, + {"SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ResetStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_501}, + {"ResetTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ResetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_502}, + {"ResetVariableOrSetting", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_503}, + {"SetSchema", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_502}, + {"StandardAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_504}, + {"SetVariableOrSetting", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_505}, + {"ZoneValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ZoneLocal", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeZoneLocalTrampoline, &FRAME_PLAN_12}, + {"ZoneDefault", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeZoneDefaultTrampoline, &FRAME_PLAN_12}, + {"ZoneStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeZoneStringLiteralTrampoline, &FRAME_PLAN_12}, + {"ZoneIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_12}, + {"ZoneIntervalWithInterval", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_506}, + {"ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_12}, + {"SetSetting", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_502}, + {"SetVariable", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_507}, + {"VariableScope", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_12}, + {"SettingScope", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"LocalScope", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeLocalScopeTrampoline, &FRAME_PLAN_12}, + {"SessionScope", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSessionScopeTrampoline, &FRAME_PLAN_12}, + {"GlobalScope", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_12}, + {"SetAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_508}, + {"VariableList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_339}, + {"TransactionStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"BeginTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_509}, + {"RollbackTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_12}, + {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_12}, + {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_510}, + {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ReadOnly", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReadOnlyTrampoline, &FRAME_PLAN_12}, + {"ReadWrite", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_12}, + {"UpdateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_511}, + {"UpdateTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"BaseTableSet", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_182}, + {"BaseTableAliasSet", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_512}, + {"UpdateAlias", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_32}, + {"UpdateSetClauseList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_513}, + {"UpdateSetClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"UpdateSetTuple", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_17}, + {"UpdateSetElement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_514}, + {"UpdateSetColumnTarget", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_515}, + {"UseStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_516}, + {"UseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"SchemaNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeSchemaNameAsUseTargetTrampoline, &FRAME_PLAN_54}, + {"CatalogNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, &FRAME_PLAN_54}, + {"UseTargetCatalogSchema", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_517}, + {"DotIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_12}, + {"VacuumStatement", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_518}, + {"VacuumOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"VacuumParensOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_519}, + {"VacuumLegacyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_520}, + {"VacuumOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, &FRAME_PLAN_19}, + {"OptAnalyze", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_521}, + {"OptFull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptFullTrampoline, + &FRAME_PLAN_12}, + {"OptFreeze", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOptFreezeTrampoline, &FRAME_PLAN_12}, + {"OptVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_12}, + {"NameList", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_415}, +}; + +static case_insensitive_map_t BuildGeneratedTransformFrameOps() { + case_insensitive_map_t result; + for (auto &ops : GENERATED_FRAME_OPS) { + result.emplace(ops.name, &ops); + } + return result; +} const case_insensitive_map_t &PEGTransformerFactory::GeneratedTransformFrameOps() { - static const case_insensitive_map_t result = { - {"Statement", &STATEMENT_OPS}, - {"PragmaName", &PRAGMA_NAME_OPS}, - {"TypeName", &TYPE_NAME_OPS}, - {"PlainIdentifier", &PLAIN_IDENTIFIER_OPS}, - {"QuotedIdentifier", "ED_IDENTIFIER_OPS}, - {"ReservedKeyword", &RESERVED_KEYWORD_OPS}, - {"UnreservedKeyword", &UNRESERVED_KEYWORD_OPS}, - {"ColumnNameKeyword", &COLUMN_NAME_KEYWORD_OPS}, - {"FuncNameKeyword", &FUNC_NAME_KEYWORD_OPS}, - {"TypeNameKeyword", &TYPE_NAME_KEYWORD_OPS}, - {"BareLabelKeyword", &BARE_LABEL_KEYWORD_OPS}, - {"SettingName", &SETTING_NAME_OPS}, - {"AlterStatement", &ALTER_STATEMENT_OPS}, - {"AlterOptions", &ALTER_OPTIONS_OPS}, - {"AlterTableStmt", &ALTER_TABLE_STMT_OPS}, - {"AlterSchemaStmt", &ALTER_SCHEMA_STMT_OPS}, - {"AlterSchemaOptions", &ALTER_SCHEMA_OPTIONS_OPS}, - {"AlterTableOptions", &ALTER_TABLE_OPTIONS_OPS}, - {"AddConstraint", &ADD_CONSTRAINT_OPS}, - {"DropConstraint", &DROP_CONSTRAINT_OPS}, - {"AddColumn", &ADD_COLUMN_OPS}, - {"AddColumnEntry", &ADD_COLUMN_ENTRY_OPS}, - {"DropColumn", &DROP_COLUMN_OPS}, - {"AlterColumn", &ALTER_COLUMN_OPS}, - {"RenameColumn", &RENAME_COLUMN_OPS}, - {"NestedColumnName", &NESTED_COLUMN_NAME_OPS}, - {"IdentifierDot", &IDENTIFIER_DOT_OPS}, - {"RenameAlter", &RENAME_ALTER_OPS}, - {"SetPartitionedBy", &SET_PARTITIONED_BY_OPS}, - {"ResetPartitionedBy", &RESET_PARTITIONED_BY_OPS}, - {"SetSortedBy", &SET_SORTED_BY_OPS}, - {"ResetSortedBy", &RESET_SORTED_BY_OPS}, - {"SetOptions", &SET_OPTIONS_OPS}, - {"ResetOptions", &RESET_OPTIONS_OPS}, - {"AlterColumnEntry", &ALTER_COLUMN_ENTRY_OPS}, - {"AddOrDropDefault", &ADD_OR_DROP_DEFAULT_OPS}, - {"AddDefault", &ADD_DEFAULT_OPS}, - {"DropDefault", &DROP_DEFAULT_OPS}, - {"ChangeNullability", &CHANGE_NULLABILITY_OPS}, - {"DropOrSet", &DROP_OR_SET_OPS}, - {"DropNullability", &DROP_NULLABILITY_OPS}, - {"SetNullability", &SET_NULLABILITY_OPS}, - {"AlterType", &ALTER_TYPE_OPS}, - {"UsingExpression", &USING_EXPRESSION_OPS}, - {"AlterViewStmt", &ALTER_VIEW_STMT_OPS}, - {"AlterSequenceStmt", &ALTER_SEQUENCE_STMT_OPS}, - {"QualifiedSequenceName", &QUALIFIED_SEQUENCE_NAME_OPS}, - {"AlterSequenceOptions", &ALTER_SEQUENCE_OPTIONS_OPS}, - {"RenameAlterSequenceOptions", &RENAME_ALTER_SEQUENCE_OPTIONS_OPS}, - {"SetSequenceOption", &SET_SEQUENCE_OPTION_OPS}, - {"AlterDatabaseStmt", &ALTER_DATABASE_STMT_OPS}, - {"AnalyzeStatement", &ANALYZE_STATEMENT_OPS}, - {"AnalyzeTarget", &ANALYZE_TARGET_OPS}, - {"AnalyzeVerbose", &ANALYZE_VERBOSE_OPS}, - {"AttachStatement", &ATTACH_STATEMENT_OPS}, - {"DatabasePath", &DATABASE_PATH_OPS}, - {"AttachAlias", &ATTACH_ALIAS_OPS}, - {"AttachOptions", &ATTACH_OPTIONS_OPS}, - {"CallStatement", &CALL_STATEMENT_OPS}, - {"CheckpointStatement", &CHECKPOINT_STATEMENT_OPS}, - {"CheckpointForce", &CHECKPOINT_FORCE_OPS}, - {"CommentStatement", &COMMENT_STATEMENT_OPS}, - {"CommentTarget", &COMMENT_TARGET_OPS}, - {"CommentStringLiteralIdentifier", &COMMENT_STRING_LITERAL_IDENTIFIER_OPS}, - {"CommentOnType", &COMMENT_ON_TYPE_OPS}, - {"CommentTable", &COMMENT_TABLE_OPS}, - {"CommentSequence", &COMMENT_SEQUENCE_OPS}, - {"CommentFunction", &COMMENT_FUNCTION_OPS}, - {"CommentMacroTable", &COMMENT_MACRO_TABLE_OPS}, - {"CommentMacro", &COMMENT_MACRO_OPS}, - {"CommentView", &COMMENT_VIEW_OPS}, - {"CommentDatabase", &COMMENT_DATABASE_OPS}, - {"CommentIndex", &COMMENT_INDEX_OPS}, - {"CommentSchema", &COMMENT_SCHEMA_OPS}, - {"CommentType", &COMMENT_TYPE_OPS}, - {"CommentColumn", &COMMENT_COLUMN_OPS}, - {"CommentValue", &COMMENT_VALUE_OPS}, - {"StringLiteralValue", &STRING_LITERAL_VALUE_OPS}, - {"AnalyzeKeyword", &ANALYZE_KEYWORD_OPS}, - {"IndexName", &INDEX_NAME_OPS}, - {"ConstraintName", &CONSTRAINT_NAME_OPS}, - {"SequenceName", &SEQUENCE_NAME_OPS}, - {"CollationName", &COLLATION_NAME_OPS}, - {"NumberLiteral", &NUMBER_LITERAL_OPS}, - {"StringLiteral", &STRING_LITERAL_OPS}, - {"Type", &TYPE_OPS}, - {"TypeVariations", &TYPE_VARIATIONS_OPS}, - {"SimpleType", &SIMPLE_TYPE_OPS}, - {"CharacterSimpleType", &CHARACTER_SIMPLE_TYPE_OPS}, - {"QualifiedSimpleType", &QUALIFIED_SIMPLE_TYPE_OPS}, - {"IntervalType", &INTERVAL_TYPE_OPS}, - {"IntervalInterval", &INTERVAL_INTERVAL_OPS}, - {"IntervalWithSpecifier", &INTERVAL_WITH_SPECIFIER_OPS}, - {"IntervalWithRangeSpecifier", &INTERVAL_WITH_RANGE_SPECIFIER_OPS}, - {"IntervalWithSimpleSpecifier", &INTERVAL_WITH_SIMPLE_SPECIFIER_OPS}, - {"IntervalWithoutSpecifier", &INTERVAL_WITHOUT_SPECIFIER_OPS}, - {"IntervalToIntervalAsType", &INTERVAL_TO_INTERVAL_AS_TYPE_OPS}, - {"YearKeyword", &YEAR_KEYWORD_OPS}, - {"MonthKeyword", &MONTH_KEYWORD_OPS}, - {"DayKeyword", &DAY_KEYWORD_OPS}, - {"HourKeyword", &HOUR_KEYWORD_OPS}, - {"MinuteKeyword", &MINUTE_KEYWORD_OPS}, - {"SecondKeyword", &SECOND_KEYWORD_OPS}, - {"MillisecondKeyword", &MILLISECOND_KEYWORD_OPS}, - {"MicrosecondKeyword", &MICROSECOND_KEYWORD_OPS}, - {"WeekKeyword", &WEEK_KEYWORD_OPS}, - {"QuarterKeyword", &QUARTER_KEYWORD_OPS}, - {"DecadeKeyword", &DECADE_KEYWORD_OPS}, - {"CenturyKeyword", &CENTURY_KEYWORD_OPS}, - {"MillenniumKeyword", &MILLENNIUM_KEYWORD_OPS}, - {"Interval", &INTERVAL_OPS}, - {"IntervalToInterval", &INTERVAL_TO_INTERVAL_OPS}, - {"YearToMonth", &YEAR_TO_MONTH_OPS}, - {"DayToHour", &DAY_TO_HOUR_OPS}, - {"DayToMinute", &DAY_TO_MINUTE_OPS}, - {"DayToSecond", &DAY_TO_SECOND_OPS}, - {"HourToMinute", &HOUR_TO_MINUTE_OPS}, - {"HourToSecond", &HOUR_TO_SECOND_OPS}, - {"MinuteToSecond", &MINUTE_TO_SECOND_OPS}, - {"BitType", &BIT_TYPE_OPS}, - {"GeometryType", &GEOMETRY_TYPE_OPS}, - {"VariantType", &VARIANT_TYPE_OPS}, - {"NumericType", &NUMERIC_TYPE_OPS}, - {"SimpleNumericType", &SIMPLE_NUMERIC_TYPE_OPS}, - {"DecimalNumericType", &DECIMAL_NUMERIC_TYPE_OPS}, - {"IntType", &INT_TYPE_OPS}, - {"IntegerType", &INTEGER_TYPE_OPS}, - {"SmallintType", &SMALLINT_TYPE_OPS}, - {"BigintType", &BIGINT_TYPE_OPS}, - {"RealType", &REAL_TYPE_OPS}, - {"BooleanType", &BOOLEAN_TYPE_OPS}, - {"DoubleType", &DOUBLE_TYPE_OPS}, - {"FloatType", &FLOAT_TYPE_OPS}, - {"DecimalType", &DECIMAL_TYPE_OPS}, - {"DecType", &DEC_TYPE_OPS}, - {"NumericModType", &NUMERIC_MOD_TYPE_OPS}, - {"QualifiedTypeName", &QUALIFIED_TYPE_NAME_OPS}, - {"TypeNameAsQualifiedName", &TYPE_NAME_AS_QUALIFIED_NAME_OPS}, - {"CatalogReservedSchemaTypeName", &CATALOG_RESERVED_SCHEMA_TYPE_NAME_OPS}, - {"SchemaReservedTypeName", &SCHEMA_RESERVED_TYPE_NAME_OPS}, - {"TypeModifiers", &TYPE_MODIFIERS_OPS}, - {"NestedType", &NESTED_TYPE_OPS}, - {"RowType", &ROW_TYPE_OPS}, - {"SetofType", &SETOF_TYPE_OPS}, - {"UnionType", &UNION_TYPE_OPS}, - {"ColIdTypeList", &COL_ID_TYPE_LIST_OPS}, - {"MapType", &MAP_TYPE_OPS}, - {"TupleType", &TUPLE_TYPE_OPS}, - {"ColIdType", &COL_ID_TYPE_OPS}, - {"ArrayBounds", &ARRAY_BOUNDS_OPS}, - {"ArrayKeyword", &ARRAY_KEYWORD_OPS}, - {"ArrayKeywordWithBounds", &ARRAY_KEYWORD_WITH_BOUNDS_OPS}, - {"SquareBracketsArray", &SQUARE_BRACKETS_ARRAY_OPS}, - {"TimeType", &TIME_TYPE_OPS}, - {"TimeOrTimestamp", &TIME_OR_TIMESTAMP_OPS}, - {"TimeTypeId", &TIME_TYPE_ID_OPS}, - {"TimestampTypeId", &TIMESTAMP_TYPE_ID_OPS}, - {"TimeZone", &TIME_ZONE_OPS}, - {"WithOrWithout", &WITH_OR_WITHOUT_OPS}, - {"WithRule", &WITH_RULE_OPS}, - {"WithoutRule", &WITHOUT_RULE_OPS}, - {"ConnectStatement", &CONNECT_STATEMENT_OPS}, - {"DisconnectStatement", &DISCONNECT_STATEMENT_OPS}, - {"SessionTarget", &SESSION_TARGET_OPS}, - {"LocalSessionTarget", &LOCAL_SESSION_TARGET_OPS}, - {"StringSessionTarget", &STRING_SESSION_TARGET_OPS}, - {"CatalogSessionTarget", &CATALOG_SESSION_TARGET_OPS}, - {"CopyStatement", ©_STATEMENT_OPS}, - {"CopyVariations", ©_VARIATIONS_OPS}, - {"CopyTable", ©_TABLE_OPS}, - {"FromOrTo", &FROM_OR_TO_OPS}, - {"CopyFrom", ©_FROM_OPS}, - {"CopyTo", ©_TO_OPS}, - {"CopySelect", ©_SELECT_OPS}, - {"CopyFileName", ©_FILE_NAME_OPS}, - {"CopyFileNameExpression", ©_FILE_NAME_EXPRESSION_OPS}, - {"CopyFileNameStringLiteral", ©_FILE_NAME_STRING_LITERAL_OPS}, - {"CopyFileNameIdentifier", ©_FILE_NAME_IDENTIFIER_OPS}, - {"CopyFileNameIdentifierColId", ©_FILE_NAME_IDENTIFIER_COL_ID_OPS}, - {"IdentifierColId", &IDENTIFIER_COL_ID_OPS}, - {"CopyFileNameSuffix", ©_FILE_NAME_SUFFIX_OPS}, - {"CopyLegacyOption", ©_LEGACY_OPTION_OPS}, - {"CopyOptions", ©_OPTIONS_OPS}, - {"CopyOptionList", ©_OPTION_LIST_OPS}, - {"SpecializedOptionList", &SPECIALIZED_OPTION_LIST_OPS}, - {"SpecializedOptionTail", &SPECIALIZED_OPTION_TAIL_OPS}, - {"SpecializedOption", &SPECIALIZED_OPTION_OPS}, - {"SingleOption", &SINGLE_OPTION_OPS}, - {"BinaryOption", &BINARY_OPTION_OPS}, - {"FreezeOption", &FREEZE_OPTION_OPS}, - {"OidsOption", &OIDS_OPTION_OPS}, - {"CsvOption", &CSV_OPTION_OPS}, - {"HeaderOption", &HEADER_OPTION_OPS}, - {"NullAsOption", &NULL_AS_OPTION_OPS}, - {"DelimiterAsOption", &DELIMITER_AS_OPTION_OPS}, - {"QuoteAsOption", "E_AS_OPTION_OPS}, - {"EscapeAsOption", &ESCAPE_AS_OPTION_OPS}, - {"EncodingOption", &ENCODING_OPTION_OPS}, - {"ForceQuoteOption", &FORCE_QUOTE_OPTION_OPS}, - {"StarSymbolColumnList", &STAR_SYMBOL_COLUMN_LIST_OPS}, - {"ForceQuote", &FORCE_QUOTE_OPS}, - {"PartitionByOption", &PARTITION_BY_OPTION_OPS}, - {"PartitionByColumnList", &PARTITION_BY_COLUMN_LIST_OPS}, - {"StarPartitionByColumnList", &STAR_PARTITION_BY_COLUMN_LIST_OPS}, - {"ParenthesizedPartitionByColumnList", &PARENTHESIZED_PARTITION_BY_COLUMN_LIST_OPS}, - {"SinglePartitionByColumnList", &SINGLE_PARTITION_BY_COLUMN_LIST_OPS}, - {"ForceNullOption", &FORCE_NULL_OPTION_OPS}, - {"ForceNotNull", &FORCE_NOT_NULL_OPS}, - {"CopyGenericOptionList", ©_GENERIC_OPTION_LIST_OPS}, - {"CopyGenericOption", ©_GENERIC_OPTION_OPS}, - {"OrderByCopyOption", &ORDER_BY_COPY_OPTION_OPS}, - {"PartitionedByCopyOption", &PARTITIONED_BY_COPY_OPTION_OPS}, - {"GenericCopyOptionList", &GENERIC_COPY_OPTION_LIST_OPS}, - {"GenericCopyOption", &GENERIC_COPY_OPTION_OPS}, - {"GenericCopyOptionValue", &GENERIC_COPY_OPTION_VALUE_OPS}, - {"GenericCopyOptionOrderList", &GENERIC_COPY_OPTION_ORDER_LIST_OPS}, - {"GenericCopyOptionExpression", &GENERIC_COPY_OPTION_EXPRESSION_OPS}, - {"GenericCopyOptionParenthesizedExpressionList", &GENERIC_COPY_OPTION_PARENTHESIZED_EXPRESSION_LIST_OPS}, - {"CopyFromDatabase", ©_FROM_DATABASE_OPS}, - {"CopyFromDatabaseWithFlag", ©_FROM_DATABASE_WITH_FLAG_OPS}, - {"CopyFromDatabaseWithoutFlag", ©_FROM_DATABASE_WITHOUT_FLAG_OPS}, - {"CopyDatabaseFlag", ©_DATABASE_FLAG_OPS}, - {"SchemaOrData", &SCHEMA_OR_DATA_OPS}, - {"CopySchema", ©_SCHEMA_OPS}, - {"CopyData", ©_DATA_OPS}, - {"CreateIndexStmt", &CREATE_INDEX_STMT_OPS}, - {"WithList", &WITH_LIST_OPS}, - {"RelOptionOrOids", &REL_OPTION_OR_OIDS_OPS}, - {"RelOptionList", &REL_OPTION_LIST_OPS}, - {"Oids", &OIDS_OPS}, - {"WithOrWithoutOids", &WITH_OR_WITHOUT_OIDS_OPS}, - {"WithOids", &WITH_OIDS_OPS}, - {"WithoutOids", &WITHOUT_OIDS_OPS}, - {"IndexElement", &INDEX_ELEMENT_OPS}, - {"UniqueIndex", &UNIQUE_INDEX_OPS}, - {"IndexType", &INDEX_TYPE_OPS}, - {"RelOption", &REL_OPTION_OPS}, - {"RelOptionName", &REL_OPTION_NAME_OPS}, - {"DottedColLabel", &DOTTED_COL_LABEL_OPS}, - {"RelOptionArgumentOpt", &REL_OPTION_ARGUMENT_OPT_OPS}, - {"DefArg", &DEF_ARG_OPS}, - {"DefArgNull", &DEF_ARG_NULL_OPS}, - {"DefArgKeyword", &DEF_ARG_KEYWORD_OPS}, - {"DefArgStringLiteral", &DEF_ARG_STRING_LITERAL_OPS}, - {"NoneLiteral", &NONE_LITERAL_OPS}, - {"CreateMacroStmt", &CREATE_MACRO_STMT_OPS}, - {"ReturnsType", &RETURNS_TYPE_OPS}, - {"MacroOrFunction", &MACRO_OR_FUNCTION_OPS}, - {"MacroKeyword", &MACRO_KEYWORD_OPS}, - {"FunctionKeyword", &FUNCTION_KEYWORD_OPS}, - {"MacroDefinition", &MACRO_DEFINITION_OPS}, - {"MacroDefinitionBody", &MACRO_DEFINITION_BODY_OPS}, - {"MacroParameters", &MACRO_PARAMETERS_OPS}, - {"MacroParameter", &MACRO_PARAMETER_OPS}, - {"SimpleParameter", &SIMPLE_PARAMETER_OPS}, - {"ScalarMacroDefinition", &SCALAR_MACRO_DEFINITION_OPS}, - {"TableMacroDefinition", &TABLE_MACRO_DEFINITION_OPS}, - {"CreateSchemaStmt", &CREATE_SCHEMA_STMT_OPS}, - {"WithOptionList", &WITH_OPTION_LIST_OPS}, - {"CreateSecretStmt", &CREATE_SECRET_STMT_OPS}, - {"SecretStorageSpecifier", &SECRET_STORAGE_SPECIFIER_OPS}, - {"SecretName", &SECRET_NAME_OPS}, - {"CreateSequenceStmt", &CREATE_SEQUENCE_STMT_OPS}, - {"SequenceOption", &SEQUENCE_OPTION_OPS}, - {"SeqSetCycle", &SEQ_SET_CYCLE_OPS}, - {"SeqCycle", &SEQ_CYCLE_OPS}, - {"SeqNoCycle", &SEQ_NO_CYCLE_OPS}, - {"SeqSetIncrement", &SEQ_SET_INCREMENT_OPS}, - {"SeqSetMinMax", &SEQ_SET_MIN_MAX_OPS}, - {"SeqNoMinMax", &SEQ_NO_MIN_MAX_OPS}, - {"SeqStartWith", &SEQ_START_WITH_OPS}, - {"SeqOwnedBy", &SEQ_OWNED_BY_OPS}, - {"SeqMinOrMax", &SEQ_MIN_OR_MAX_OPS}, - {"MinValue", &MIN_VALUE_OPS}, - {"MaxValue", &MAX_VALUE_OPS}, - {"CreateStatement", &CREATE_STATEMENT_OPS}, - {"CreateStatementVariation", &CREATE_STATEMENT_VARIATION_OPS}, - {"OrReplace", &OR_REPLACE_OPS}, - {"Temporary", &TEMPORARY_OPS}, - {"Persistent", &PERSISTENT_OPS}, - {"TempPersistent", &TEMP_PERSISTENT_OPS}, - {"TemporaryPersistent", &TEMPORARY_PERSISTENT_OPS}, - {"CreateTableStmt", &CREATE_TABLE_STMT_OPS}, - {"CreateTableDefinition", &CREATE_TABLE_DEFINITION_OPS}, - {"CreateTableAs", &CREATE_TABLE_AS_OPS}, - {"PartitionSortedOptions", &PARTITION_SORTED_OPTIONS_OPS}, - {"PartitionOptSortedOptions", &PARTITION_OPT_SORTED_OPTIONS_OPS}, - {"SortedOptPartitionOptions", &SORTED_OPT_PARTITION_OPTIONS_OPS}, - {"PartitionOptions", &PARTITION_OPTIONS_OPS}, - {"SortedOptions", &SORTED_OPTIONS_OPS}, - {"WithData", &WITH_DATA_OPS}, - {"WithDataOnly", &WITH_DATA_ONLY_OPS}, - {"WithNoData", &WITH_NO_DATA_OPS}, - {"IdentifierList", &IDENTIFIER_LIST_OPS}, - {"CreateColumnList", &CREATE_COLUMN_LIST_OPS}, - {"IfNotExists", &IF_NOT_EXISTS_OPS}, - {"QualifiedName", &QUALIFIED_NAME_OPS}, - {"SchemaReservedIdentifierOrStringLiteral", &SCHEMA_RESERVED_IDENTIFIER_OR_STRING_LITERAL_OPS}, - {"CatalogReservedSchemaIdentifier", &CATALOG_RESERVED_SCHEMA_IDENTIFIER_OPS}, - {"IdentifierOrStringLiteral", &IDENTIFIER_OR_STRING_LITERAL_OPS}, - {"ReservedIdentifierOrStringLiteral", &RESERVED_IDENTIFIER_OR_STRING_LITERAL_OPS}, - {"CatalogQualification", &CATALOG_QUALIFICATION_OPS}, - {"SchemaQualification", &SCHEMA_QUALIFICATION_OPS}, - {"ReservedSchemaQualification", &RESERVED_SCHEMA_QUALIFICATION_OPS}, - {"TableQualification", &TABLE_QUALIFICATION_OPS}, - {"ReservedTableQualification", &RESERVED_TABLE_QUALIFICATION_OPS}, - {"CreateTableColumnList", &CREATE_TABLE_COLUMN_LIST_OPS}, - {"CreateTableColumnElement", &CREATE_TABLE_COLUMN_ELEMENT_OPS}, - {"CreateTableColumnDefinition", &CREATE_TABLE_COLUMN_DEFINITION_OPS}, - {"CreateTableConstraint", &CREATE_TABLE_CONSTRAINT_OPS}, - {"ColumnDefinition", &COLUMN_DEFINITION_OPS}, - {"ColumnConstraint", &COLUMN_CONSTRAINT_OPS}, - {"NameableColumnConstraint", &NAMEABLE_COLUMN_CONSTRAINT_OPS}, - {"ColumnConstraintElement", &COLUMN_CONSTRAINT_ELEMENT_OPS}, - {"NotNullConstraint", &NOT_NULL_CONSTRAINT_OPS}, - {"NullConstraint", &NULL_CONSTRAINT_OPS}, - {"NotNullColumnConstraint", &NOT_NULL_COLUMN_CONSTRAINT_OPS}, - {"UniqueConstraint", &UNIQUE_CONSTRAINT_OPS}, - {"PrimaryKeyConstraint", &PRIMARY_KEY_CONSTRAINT_OPS}, - {"ConstraintTiming", &CONSTRAINT_TIMING_OPS}, - {"ImmediateConstraint", &IMMEDIATE_CONSTRAINT_OPS}, - {"DeferredConstraint", &DEFERRED_CONSTRAINT_OPS}, - {"DefaultValue", &DEFAULT_VALUE_OPS}, - {"CheckConstraint", &CHECK_CONSTRAINT_OPS}, - {"ForeignKeyConstraint", &FOREIGN_KEY_CONSTRAINT_OPS}, - {"ColumnCollation", &COLUMN_COLLATION_OPS}, - {"ColumnCompression", &COLUMN_COMPRESSION_OPS}, - {"KeyActions", &KEY_ACTIONS_OPS}, - {"UpdateFirstKeyActions", &UPDATE_FIRST_KEY_ACTIONS_OPS}, - {"DeleteFirstKeyActions", &DELETE_FIRST_KEY_ACTIONS_OPS}, - {"UpdateAction", &UPDATE_ACTION_OPS}, - {"DeleteAction", &DELETE_ACTION_OPS}, - {"KeyAction", &KEY_ACTION_OPS}, - {"NoKeyAction", &NO_KEY_ACTION_OPS}, - {"RestrictKeyAction", &RESTRICT_KEY_ACTION_OPS}, - {"CascadeKeyAction", &CASCADE_KEY_ACTION_OPS}, - {"SetNullKeyAction", &SET_NULL_KEY_ACTION_OPS}, - {"SetDefaultKeyAction", &SET_DEFAULT_KEY_ACTION_OPS}, - {"TopLevelConstraint", &TOP_LEVEL_CONSTRAINT_OPS}, - {"TopLevelConstraintList", &TOP_LEVEL_CONSTRAINT_LIST_OPS}, - {"TopCheckConstraint", &TOP_CHECK_CONSTRAINT_OPS}, - {"TopPrimaryKeyConstraint", &TOP_PRIMARY_KEY_CONSTRAINT_OPS}, - {"TopUniqueConstraint", &TOP_UNIQUE_CONSTRAINT_OPS}, - {"TopForeignKeyConstraint", &TOP_FOREIGN_KEY_CONSTRAINT_OPS}, - {"ColumnIdList", &COLUMN_ID_LIST_OPS}, - {"DottedIdentifier", &DOTTED_IDENTIFIER_OPS}, - {"DotColLabel", &DOT_COL_LABEL_OPS}, - {"Identifier", &IDENTIFIER_OPS}, - {"ColId", &COL_ID_OPS}, - {"ColIdOrString", &COL_ID_OR_STRING_OPS}, - {"TypeFuncName", &TYPE_FUNC_NAME_OPS}, - {"TypeFuncKeyword", &TYPE_FUNC_KEYWORD_OPS}, - {"ColLabel", &COL_LABEL_OPS}, - {"ColLabelOrString", &COL_LABEL_OR_STRING_OPS}, - {"ColLabelIdentifier", &COL_LABEL_IDENTIFIER_OPS}, - {"StringLiteralIdentifier", &STRING_LITERAL_IDENTIFIER_OPS}, - {"GeneratedColumn", &GENERATED_COLUMN_OPS}, - {"Generated", &GENERATED_OPS}, - {"GeneratedAlways", &GENERATED_ALWAYS_OPS}, - {"GeneratedByDefault", &GENERATED_BY_DEFAULT_OPS}, - {"GeneratedColumnType", &GENERATED_COLUMN_TYPE_OPS}, - {"CommitAction", &COMMIT_ACTION_OPS}, - {"PreserveOrDelete", &PRESERVE_OR_DELETE_OPS}, - {"PreserveRows", &PRESERVE_ROWS_OPS}, - {"DeleteRows", &DELETE_ROWS_OPS}, - {"VirtualGeneratedColumn", &VIRTUAL_GENERATED_COLUMN_OPS}, - {"StoredGeneratedColumn", &STORED_GENERATED_COLUMN_OPS}, - {"CreateTriggerStmt", &CREATE_TRIGGER_STMT_OPS}, - {"TriggerBody", &TRIGGER_BODY_OPS}, - {"TriggerName", &TRIGGER_NAME_OPS}, - {"ReferencingClause", &REFERENCING_CLAUSE_OPS}, - {"ReferencingItem", &REFERENCING_ITEM_OPS}, - {"ReferencingNewTableAs", &REFERENCING_NEW_TABLE_AS_OPS}, - {"ReferencingOldTableAs", &REFERENCING_OLD_TABLE_AS_OPS}, - {"TriggerTiming", &TRIGGER_TIMING_OPS}, - {"TriggerBefore", &TRIGGER_BEFORE_OPS}, - {"TriggerAfter", &TRIGGER_AFTER_OPS}, - {"TriggerInsteadOf", &TRIGGER_INSTEAD_OF_OPS}, - {"TriggerEvent", &TRIGGER_EVENT_OPS}, - {"TriggerEventInsert", &TRIGGER_EVENT_INSERT_OPS}, - {"TriggerEventDelete", &TRIGGER_EVENT_DELETE_OPS}, - {"TriggerEventUpdate", &TRIGGER_EVENT_UPDATE_OPS}, - {"TriggerEventUpdateOf", &TRIGGER_EVENT_UPDATE_OF_OPS}, - {"TriggerColumnList", &TRIGGER_COLUMN_LIST_OPS}, - {"ForEachClause", &FOR_EACH_CLAUSE_OPS}, - {"ForEachRow", &FOR_EACH_ROW_OPS}, - {"ForEachStatement", &FOR_EACH_STATEMENT_OPS}, - {"CreateTypeStmt", &CREATE_TYPE_STMT_OPS}, - {"CreateType", &CREATE_TYPE_OPS}, - {"CreateTypeFromType", &CREATE_TYPE_FROM_TYPE_OPS}, - {"EnumSelectType", &ENUM_SELECT_TYPE_OPS}, - {"EnumStringLiteralList", &ENUM_STRING_LITERAL_LIST_OPS}, - {"CreateViewStmt", &CREATE_VIEW_STMT_OPS}, - {"CreateRecursive", &CREATE_RECURSIVE_OPS}, - {"CreateSecure", &CREATE_SECURE_OPS}, - {"DeallocateStatement", &DEALLOCATE_STATEMENT_OPS}, - {"DeallocatePrepare", &DEALLOCATE_PREPARE_OPS}, - {"DeleteStatement", &DELETE_STATEMENT_OPS}, - {"TruncateStatement", &TRUNCATE_STATEMENT_OPS}, - {"TruncateOptions", &TRUNCATE_OPTIONS_OPS}, - {"TruncateAliasOptions", &TRUNCATE_ALIAS_OPTIONS_OPS}, - {"TruncateDropBehavior", &TRUNCATE_DROP_BEHAVIOR_OPS}, - {"TargetOptAlias", &TARGET_OPT_ALIAS_OPS}, - {"TargetAlias", &TARGET_ALIAS_OPS}, - {"DeleteUsingClause", &DELETE_USING_CLAUSE_OPS}, - {"DescribeStatement", &DESCRIBE_STATEMENT_OPS}, - {"ShowDeprecatedSelect", &SHOW_DEPRECATED_SELECT_OPS}, - {"DescribeSelect", &DESCRIBE_SELECT_OPS}, - {"ShowAllTables", &SHOW_ALL_TABLES_OPS}, - {"ShowTables", &SHOW_TABLES_OPS}, - {"ShowByName", &SHOW_BY_NAME_OPS}, - {"DescribeByName", &DESCRIBE_BY_NAME_OPS}, - {"DescribeOrSummarize", &DESCRIBE_OR_SUMMARIZE_OPS}, - {"ShowTarget", &SHOW_TARGET_OPS}, - {"ShowDeprecatedQualifiedTableName", &SHOW_DEPRECATED_QUALIFIED_TABLE_NAME_OPS}, - {"ShowSettingName", &SHOW_SETTING_NAME_OPS}, - {"DescribeTarget", &DESCRIBE_TARGET_OPS}, - {"DescribeBaseTableName", &DESCRIBE_BASE_TABLE_NAME_OPS}, - {"DescribeStringLiteral", &DESCRIBE_STRING_LITERAL_OPS}, - {"Summarize", &SUMMARIZE_OPS}, - {"SummarizeRule", &SUMMARIZE_RULE_OPS}, - {"ShowOrDescribe", &SHOW_OR_DESCRIBE_OPS}, - {"ShowRule", &SHOW_RULE_OPS}, - {"DescribeRule", &DESCRIBE_RULE_OPS}, - {"DescribeLongRule", &DESCRIBE_LONG_RULE_OPS}, - {"DescRule", &DESC_RULE_OPS}, - {"DetachStatement", &DETACH_STATEMENT_OPS}, - {"DropStatement", &DROP_STATEMENT_OPS}, - {"DropEntries", &DROP_ENTRIES_OPS}, - {"DropTrigger", &DROP_TRIGGER_OPS}, - {"DropTable", &DROP_TABLE_OPS}, - {"DropTableFunction", &DROP_TABLE_FUNCTION_OPS}, - {"DropFunction", &DROP_FUNCTION_OPS}, - {"DropSchema", &DROP_SCHEMA_OPS}, - {"DropIndex", &DROP_INDEX_OPS}, - {"QualifiedIndexName", &QUALIFIED_INDEX_NAME_OPS}, - {"QualifiedIndexNameString", &QUALIFIED_INDEX_NAME_STRING_OPS}, - {"SchemaReservedIndex", &SCHEMA_RESERVED_INDEX_OPS}, - {"CatalogReservedSchemaIndex", &CATALOG_RESERVED_SCHEMA_INDEX_OPS}, - {"DropSequence", &DROP_SEQUENCE_OPS}, - {"DropCollation", &DROP_COLLATION_OPS}, - {"DropType", &DROP_TYPE_OPS}, - {"DropSecret", &DROP_SECRET_OPS}, - {"TableOrView", &TABLE_OR_VIEW_OPS}, - {"MaterializedViewEntry", &MATERIALIZED_VIEW_ENTRY_OPS}, - {"FunctionTypeMacro", &FUNCTION_TYPE_MACRO_OPS}, - {"FunctionTypeMacroKeyword", &FUNCTION_TYPE_MACRO_KEYWORD_OPS}, - {"FunctionTypeFunction", &FUNCTION_TYPE_FUNCTION_OPS}, - {"DropBehavior", &DROP_BEHAVIOR_OPS}, - {"CascadeDropBehavior", &CASCADE_DROP_BEHAVIOR_OPS}, - {"RestrictDropBehavior", &RESTRICT_DROP_BEHAVIOR_OPS}, - {"IfExists", &IF_EXISTS_OPS}, - {"DropSecretStorage", &DROP_SECRET_STORAGE_OPS}, - {"ExecuteStatement", &EXECUTE_STATEMENT_OPS}, - {"ExplainStatement", &EXPLAIN_STATEMENT_OPS}, - {"ExplainOptionList", &EXPLAIN_OPTION_LIST_OPS}, - {"ExplainOption", &EXPLAIN_OPTION_OPS}, - {"ExplainOptionName", &EXPLAIN_OPTION_NAME_OPS}, - {"ExplainSelectStatement", &EXPLAIN_SELECT_STATEMENT_OPS}, - {"ExplainableStatements", &EXPLAINABLE_STATEMENTS_OPS}, - {"ExportStatement", &EXPORT_STATEMENT_OPS}, - {"ExportSource", &EXPORT_SOURCE_OPS}, - {"ExportOptions", &EXPORT_OPTIONS_OPS}, - {"ImportStatement", &IMPORT_STATEMENT_OPS}, - {"ColumnReference", &COLUMN_REFERENCE_OPS}, - {"NestedSchemaTableColumnName", &NESTED_SCHEMA_TABLE_COLUMN_NAME_OPS}, - {"CatalogReservedSchemaTableColumnName", &CATALOG_RESERVED_SCHEMA_TABLE_COLUMN_NAME_OPS}, - {"SchemaReservedTableColumnName", &SCHEMA_RESERVED_TABLE_COLUMN_NAME_OPS}, - {"TableReservedColumnName", &TABLE_RESERVED_COLUMN_NAME_OPS}, - {"FunctionExpression", &FUNCTION_EXPRESSION_OPS}, - {"FunctionExpressionArguments", &FUNCTION_EXPRESSION_ARGUMENTS_OPS}, - {"FunctionExpressionArgumentList", &FUNCTION_EXPRESSION_ARGUMENT_LIST_OPS}, - {"FunctionArgumentList", &FUNCTION_ARGUMENT_LIST_OPS}, - {"FunctionIdentifier", &FUNCTION_IDENTIFIER_OPS}, - {"FunctionNameAsQualifiedName", &FUNCTION_NAME_AS_QUALIFIED_NAME_OPS}, - {"CatalogReservedSchemaFunctionName", &CATALOG_RESERVED_SCHEMA_FUNCTION_NAME_OPS}, - {"SchemaReservedFunctionName", &SCHEMA_RESERVED_FUNCTION_NAME_OPS}, - {"DistinctOrAll", &DISTINCT_OR_ALL_OPS}, - {"DistinctKeyword", &DISTINCT_KEYWORD_OPS}, - {"AllKeyword", &ALL_KEYWORD_OPS}, - {"WithinGroupClause", &WITHIN_GROUP_CLAUSE_OPS}, - {"FilterClause", &FILTER_CLAUSE_OPS}, - {"FilterClauseExpression", &FILTER_CLAUSE_EXPRESSION_OPS}, - {"FilterClauseContents", &FILTER_CLAUSE_CONTENTS_OPS}, - {"IgnoreOrRespectNulls", &IGNORE_OR_RESPECT_NULLS_OPS}, - {"IgnoreNulls", &IGNORE_NULLS_OPS}, - {"RespectNulls", &RESPECT_NULLS_OPS}, - {"ParenthesisExpression", &PARENTHESIS_EXPRESSION_OPS}, - {"LiteralExpression", &LITERAL_EXPRESSION_OPS}, - {"ConstantLiteral", &CONSTANT_LITERAL_OPS}, - {"NullLiteral", &NULL_LITERAL_OPS}, - {"TrueLiteral", &TRUE_LITERAL_OPS}, - {"FalseLiteral", &FALSE_LITERAL_OPS}, - {"CastExpression", &CAST_EXPRESSION_OPS}, - {"CastArguments", &CAST_ARGUMENTS_OPS}, - {"CastOrTryCast", &CAST_OR_TRY_CAST_OPS}, - {"CastKeyword", &CAST_KEYWORD_OPS}, - {"TryCastKeyword", &TRY_CAST_KEYWORD_OPS}, - {"ColIdDot", &COL_ID_DOT_OPS}, - {"StarExpression", &STAR_EXPRESSION_OPS}, - {"StarQualifierList", &STAR_QUALIFIER_LIST_OPS}, - {"ExcludeList", &EXCLUDE_LIST_OPS}, - {"ExcludeNames", &EXCLUDE_NAMES_OPS}, - {"ExcludeNameList", &EXCLUDE_NAME_LIST_OPS}, - {"ExcludeNameSingle", &EXCLUDE_NAME_SINGLE_OPS}, - {"ExcludeName", &EXCLUDE_NAME_OPS}, - {"ExcludeDottedName", &EXCLUDE_DOTTED_NAME_OPS}, - {"ExcludeColumnName", &EXCLUDE_COLUMN_NAME_OPS}, - {"ReplaceList", &REPLACE_LIST_OPS}, - {"ReplaceEntries", &REPLACE_ENTRIES_OPS}, - {"ReplaceEntrySingle", &REPLACE_ENTRY_SINGLE_OPS}, - {"ReplaceEntryList", &REPLACE_ENTRY_LIST_OPS}, - {"ReplaceEntry", &REPLACE_ENTRY_OPS}, - {"RenameList", &RENAME_LIST_OPS}, - {"RenameEntries", &RENAME_ENTRIES_OPS}, - {"RenameEntryList", &RENAME_ENTRY_LIST_OPS}, - {"SingleRenameEntry", &SINGLE_RENAME_ENTRY_OPS}, - {"RenameEntry", &RENAME_ENTRY_OPS}, - {"SubqueryExpression", &SUBQUERY_EXPRESSION_OPS}, - {"SubqueryNot", &SUBQUERY_NOT_OPS}, - {"SubqueryExists", &SUBQUERY_EXISTS_OPS}, - {"CaseExpression", &CASE_EXPRESSION_OPS}, - {"CaseWhenThen", &CASE_WHEN_THEN_OPS}, - {"CaseElse", &CASE_ELSE_OPS}, - {"TypeLiteral", &TYPE_LITERAL_OPS}, - {"IntervalLiteral", &INTERVAL_LITERAL_OPS}, - {"IntervalParameter", &INTERVAL_PARAMETER_OPS}, - {"IntervalStringParameter", &INTERVAL_STRING_PARAMETER_OPS}, - {"FrameClause", &FRAME_CLAUSE_OPS}, - {"Framing", &FRAMING_OPS}, - {"RowsFraming", &ROWS_FRAMING_OPS}, - {"RangeFraming", &RANGE_FRAMING_OPS}, - {"GroupsFraming", &GROUPS_FRAMING_OPS}, - {"FrameExtent", &FRAME_EXTENT_OPS}, - {"SingleFrameExtent", &SINGLE_FRAME_EXTENT_OPS}, - {"BetweenFrameExtent", &BETWEEN_FRAME_EXTENT_OPS}, - {"FrameBound", &FRAME_BOUND_OPS}, - {"FrameUnbounded", &FRAME_UNBOUNDED_OPS}, - {"FrameExpression", &FRAME_EXPRESSION_OPS}, - {"FrameCurrentRow", &FRAME_CURRENT_ROW_OPS}, - {"PrecedingOrFollowing", &PRECEDING_OR_FOLLOWING_OPS}, - {"PrecedingFrame", &PRECEDING_FRAME_OPS}, - {"FollowingFrame", &FOLLOWING_FRAME_OPS}, - {"WindowExcludeClause", &WINDOW_EXCLUDE_CLAUSE_OPS}, - {"WindowExcludeElement", &WINDOW_EXCLUDE_ELEMENT_OPS}, - {"ExcludeCurrentRow", &EXCLUDE_CURRENT_ROW_OPS}, - {"ExcludeGroup", &EXCLUDE_GROUP_OPS}, - {"ExcludeTies", &EXCLUDE_TIES_OPS}, - {"ExcludeNoOthers", &EXCLUDE_NO_OTHERS_OPS}, - {"OverClause", &OVER_CLAUSE_OPS}, - {"WindowFrame", &WINDOW_FRAME_OPS}, - {"IdentifierWindowFrame", &IDENTIFIER_WINDOW_FRAME_OPS}, - {"ParensIdentifier", &PARENS_IDENTIFIER_OPS}, - {"WindowFrameDefinition", &WINDOW_FRAME_DEFINITION_OPS}, - {"WindowFrameNameContentsParens", &WINDOW_FRAME_NAME_CONTENTS_PARENS_OPS}, - {"WindowFrameNameContents", &WINDOW_FRAME_NAME_CONTENTS_OPS}, - {"WindowFrameContentsParens", &WINDOW_FRAME_CONTENTS_PARENS_OPS}, - {"WindowFrameContents", &WINDOW_FRAME_CONTENTS_OPS}, - {"BaseWindowName", &BASE_WINDOW_NAME_OPS}, - {"WindowPartition", &WINDOW_PARTITION_OPS}, - {"ListExpression", &LIST_EXPRESSION_OPS}, - {"ArrayBoundedListExpression", &ARRAY_BOUNDED_LIST_EXPRESSION_OPS}, - {"ArrayParensSelect", &ARRAY_PARENS_SELECT_OPS}, - {"BoundedListExpression", &BOUNDED_LIST_EXPRESSION_OPS}, - {"StructExpression", &STRUCT_EXPRESSION_OPS}, - {"StructField", &STRUCT_FIELD_OPS}, - {"MapExpression", &MAP_EXPRESSION_OPS}, - {"MapStructExpression", &MAP_STRUCT_EXPRESSION_OPS}, - {"MapStructField", &MAP_STRUCT_FIELD_OPS}, - {"GroupingExpression", &GROUPING_EXPRESSION_OPS}, - {"GroupingOrGroupingId", &GROUPING_OR_GROUPING_ID_OPS}, - {"GroupingKeyword", &GROUPING_KEYWORD_OPS}, - {"GroupingIdKeyword", &GROUPING_ID_KEYWORD_OPS}, - {"Parameter", &PARAMETER_OPS}, - {"QuestionMarkNumberedParameter", &QUESTION_MARK_NUMBERED_PARAMETER_OPS}, - {"AnonymousParameter", &ANONYMOUS_PARAMETER_OPS}, - {"NumberedParameter", &NUMBERED_PARAMETER_OPS}, - {"ColLabelParameter", &COL_LABEL_PARAMETER_OPS}, - {"PositionalExpression", &POSITIONAL_EXPRESSION_OPS}, - {"DefaultExpression", &DEFAULT_EXPRESSION_OPS}, - {"ListComprehensionExpression", &LIST_COMPREHENSION_EXPRESSION_OPS}, - {"ListComprehensionFilter", &LIST_COMPREHENSION_FILTER_OPS}, - {"ParensExpression", &PARENS_EXPRESSION_OPS}, - {"MeasureSemanticsExpression", &MEASURE_SEMANTICS_EXPRESSION_OPS}, - {"SingleExpression", &SINGLE_EXPRESSION_OPS}, - {"Expression", &EXPRESSION_OPS}, - {"ColumnDefaultExpr", &COLUMN_DEFAULT_EXPR_OPS}, - {"LambdaArrowExpression", &LAMBDA_ARROW_EXPRESSION_OPS}, - {"SingleArrowPair", &SINGLE_ARROW_PAIR_OPS}, - {"LogicalOrExpression", &LOGICAL_OR_EXPRESSION_OPS}, - {"LogicalOrExpressionTail", &LOGICAL_OR_EXPRESSION_TAIL_OPS}, - {"ColDefOrExpr", &COL_DEF_OR_EXPR_OPS}, - {"ColDefOrExpressionTail", &COL_DEF_OR_EXPRESSION_TAIL_OPS}, - {"LogicalAndExpression", &LOGICAL_AND_EXPRESSION_OPS}, - {"LogicalAndExpressionTail", &LOGICAL_AND_EXPRESSION_TAIL_OPS}, - {"ColDefAndExpr", &COL_DEF_AND_EXPR_OPS}, - {"ColDefAndExpressionTail", &COL_DEF_AND_EXPRESSION_TAIL_OPS}, - {"LogicalNotExpression", &LOGICAL_NOT_EXPRESSION_OPS}, - {"NotExpression", &NOT_EXPRESSION_OPS}, - {"NotKeyword", &NOT_KEYWORD_OPS}, - {"IsExpression", &IS_EXPRESSION_OPS}, - {"IsExpressionContinuation", &IS_EXPRESSION_CONTINUATION_OPS}, - {"IsExpressionTail", &IS_EXPRESSION_TAIL_OPS}, - {"IsTestTail", &IS_TEST_TAIL_OPS}, - {"IsDistinctTail", &IS_DISTINCT_TAIL_OPS}, - {"IsComparisonTail", &IS_COMPARISON_TAIL_OPS}, - {"IsOtherOperatorTail", &IS_OTHER_OPERATOR_TAIL_OPS}, - {"IsCastTail", &IS_CAST_TAIL_OPS}, - {"IsTest", &IS_TEST_OPS}, - {"IsLiteral", &IS_LITERAL_OPS}, - {"IsLiteralValue", &IS_LITERAL_VALUE_OPS}, - {"UnknownLiteral", &UNKNOWN_LITERAL_OPS}, - {"NotNull", &NOT_NULL_OPS}, - {"NotNullKeyword", &NOT_NULL_KEYWORD_OPS}, - {"NotNullOperator", &NOT_NULL_OPERATOR_OPS}, - {"IsNull", &IS_NULL_OPS}, - {"IsNullOperator", &IS_NULL_OPERATOR_OPS}, - {"IsDistinctFromExpression", &IS_DISTINCT_FROM_EXPRESSION_OPS}, - {"IsDistinctFromTail", &IS_DISTINCT_FROM_TAIL_OPS}, - {"IsDistinctFromOp", &IS_DISTINCT_FROM_OP_OPS}, - {"ComparisonExpression", &COMPARISON_EXPRESSION_OPS}, - {"ComparisonExpressionTail", &COMPARISON_EXPRESSION_TAIL_OPS}, - {"ComparisonOperand", &COMPARISON_OPERAND_OPS}, - {"NotComparisonOperand", &NOT_COMPARISON_OPERAND_OPS}, - {"ComparisonOperator", &COMPARISON_OPERATOR_OPS}, - {"OperatorEqual", &OPERATOR_EQUAL_OPS}, - {"OperatorNotEqual", &OPERATOR_NOT_EQUAL_OPS}, - {"OperatorLessThan", &OPERATOR_LESS_THAN_OPS}, - {"OperatorGreaterThan", &OPERATOR_GREATER_THAN_OPS}, - {"OperatorLessThanEquals", &OPERATOR_LESS_THAN_EQUALS_OPS}, - {"OperatorGreaterThanEquals", &OPERATOR_GREATER_THAN_EQUALS_OPS}, - {"BetweenInLikeExpression", &BETWEEN_IN_LIKE_EXPRESSION_OPS}, - {"InPredicate", &IN_PREDICATE_OPS}, - {"BetweenLikeOp", &BETWEEN_LIKE_OP_OPS}, - {"BetweenLikeOpExpression", &BETWEEN_LIKE_OP_EXPRESSION_OPS}, - {"LikeClause", &LIKE_CLAUSE_OPS}, - {"EscapeClause", &ESCAPE_CLAUSE_OPS}, - {"LikeVariations", &LIKE_VARIATIONS_OPS}, - {"LikeToken", &LIKE_TOKEN_OPS}, - {"ILikeToken", &ILIKE_TOKEN_OPS}, - {"GlobToken", &GLOB_TOKEN_OPS}, - {"SimilarToToken", &SIMILAR_TO_TOKEN_OPS}, - {"RegexMatchToken", ®EX_MATCH_TOKEN_OPS}, - {"RegexInsensitiveMatchToken", ®EX_INSENSITIVE_MATCH_TOKEN_OPS}, - {"NotILikeOp", &NOT_ILIKE_OP_OPS}, - {"NotLikeOp", &NOT_LIKE_OP_OPS}, - {"NotRegexInsensitiveMatchOp", &NOT_REGEX_INSENSITIVE_MATCH_OP_OPS}, - {"NotSimilarToOp", &NOT_SIMILAR_TO_OP_OPS}, - {"InClause", &IN_CLAUSE_OPS}, - {"InExpression", &IN_EXPRESSION_OPS}, - {"InContainsExpression", &IN_CONTAINS_EXPRESSION_OPS}, - {"InExpressionList", &IN_EXPRESSION_LIST_OPS}, - {"InSelectStatement", &IN_SELECT_STATEMENT_OPS}, - {"BetweenClause", &BETWEEN_CLAUSE_OPS}, - {"OtherOperatorExpression", &OTHER_OPERATOR_EXPRESSION_OPS}, - {"InfixOtherOperatorExpression", &INFIX_OTHER_OPERATOR_EXPRESSION_OPS}, - {"OtherOperatorTail", &OTHER_OPERATOR_TAIL_OPS}, - {"OtherOperator", &OTHER_OPERATOR_OPS}, - {"AnyAllParsedOperator", &ANY_ALL_PARSED_OPERATOR_OPS}, - {"NamedOtherOperator", &NAMED_OTHER_OPERATOR_OPS}, - {"OperatorLiteral", &OPERATOR_LITERAL_OPS}, - {"AnyOperatorLiteral", &ANY_OPERATOR_LITERAL_OPS}, - {"AnyAllOperator", &ANY_ALL_OPERATOR_OPS}, - {"AnyOrAll", &ANY_OR_ALL_OPS}, - {"SubqueryAny", &SUBQUERY_ANY_OPS}, - {"SubqueryAll", &SUBQUERY_ALL_OPS}, - {"QualifiedOperator", &QUALIFIED_OPERATOR_OPS}, - {"QualifiedOperatorContents", &QUALIFIED_OPERATOR_CONTENTS_OPS}, - {"BitwiseExpression", &BITWISE_EXPRESSION_OPS}, - {"BitwiseExpressionTail", &BITWISE_EXPRESSION_TAIL_OPS}, - {"BitOperator", &BIT_OPERATOR_OPS}, - {"TildeExpression", &TILDE_EXPRESSION_OPS}, - {"AdditiveExpression", &ADDITIVE_EXPRESSION_OPS}, - {"AdditiveExpressionTail", &ADDITIVE_EXPRESSION_TAIL_OPS}, - {"Term", &TERM_OPS}, - {"MultiplicativeExpression", &MULTIPLICATIVE_EXPRESSION_OPS}, - {"MultiplicativeExpressionTail", &MULTIPLICATIVE_EXPRESSION_TAIL_OPS}, - {"Factor", &FACTOR_OPS}, - {"ExponentiationExpression", &EXPONENTIATION_EXPRESSION_OPS}, - {"ExponentiationExpressionTail", &EXPONENTIATION_EXPRESSION_TAIL_OPS}, - {"ExponentOperator", &EXPONENT_OPERATOR_OPS}, - {"CollateExpression", &COLLATE_EXPRESSION_OPS}, - {"CollateExpressionTail", &COLLATE_EXPRESSION_TAIL_OPS}, - {"AtTimeZoneExpression", &AT_TIME_ZONE_EXPRESSION_OPS}, - {"AtTimeZoneExpressionTail", &AT_TIME_ZONE_EXPRESSION_TAIL_OPS}, - {"UnaryExpression", &UNARY_EXPRESSION_OPS}, - {"PrefixExpression", &PREFIX_EXPRESSION_OPS}, - {"CustomPrefixExpression", &CUSTOM_PREFIX_EXPRESSION_OPS}, - {"PrefixOperator", &PREFIX_OPERATOR_OPS}, - {"MinusPrefixOperator", &MINUS_PREFIX_OPERATOR_OPS}, - {"PlusPrefixOperator", &PLUS_PREFIX_OPERATOR_OPS}, - {"TildePrefixOperator", &TILDE_PREFIX_OPERATOR_OPS}, - {"BaseExpression", &BASE_EXPRESSION_OPS}, - {"IndirectionList", &INDIRECTION_LIST_OPS}, - {"Indirection", &INDIRECTION_OPS}, - {"CastOperator", &CAST_OPERATOR_OPS}, - {"DotOperator", &DOT_OPERATOR_OPS}, - {"DotMethodOperator", &DOT_METHOD_OPERATOR_OPS}, - {"DotColumnOperator", &DOT_COLUMN_OPERATOR_OPS}, - {"MethodExpression", &METHOD_EXPRESSION_OPS}, - {"MethodExpressionArguments", &METHOD_EXPRESSION_ARGUMENTS_OPS}, - {"MethodExpressionArgumentList", &METHOD_EXPRESSION_ARGUMENT_LIST_OPS}, - {"MethodFunctionArguments", &METHOD_FUNCTION_ARGUMENTS_OPS}, - {"SliceExpression", &SLICE_EXPRESSION_OPS}, - {"SliceBound", &SLICE_BOUND_OPS}, - {"SliceUpperBound", &SLICE_UPPER_BOUND_OPS}, - {"MinusStepSliceBound", &MINUS_STEP_SLICE_BOUND_OPS}, - {"EndStepSliceBound", &END_STEP_SLICE_BOUND_OPS}, - {"EndSliceBound", &END_SLICE_BOUND_OPS}, - {"StepSliceBound", &STEP_SLICE_BOUND_OPS}, - {"PostfixOperator", &POSTFIX_OPERATOR_OPS}, - {"SpecialFunctionExpression", &SPECIAL_FUNCTION_EXPRESSION_OPS}, - {"CoalesceExpression", &COALESCE_EXPRESSION_OPS}, - {"UnpackExpression", &UNPACK_EXPRESSION_OPS}, - {"TryExpression", &TRY_EXPRESSION_OPS}, - {"ColumnsExpression", &COLUMNS_EXPRESSION_OPS}, - {"ExtractExpression", &EXTRACT_EXPRESSION_OPS}, - {"ExtractArguments", &EXTRACT_ARGUMENTS_OPS}, - {"LambdaExpression", &LAMBDA_EXPRESSION_OPS}, - {"NullIfExpression", &NULL_IF_EXPRESSION_OPS}, - {"NullIfArguments", &NULL_IF_ARGUMENTS_OPS}, - {"PositionExpression", &POSITION_EXPRESSION_OPS}, - {"PositionArguments", &POSITION_ARGUMENTS_OPS}, - {"RowExpression", &ROW_EXPRESSION_OPS}, - {"SubstringExpression", &SUBSTRING_EXPRESSION_OPS}, - {"SubstringArguments", &SUBSTRING_ARGUMENTS_OPS}, - {"SubstringExpressionList", &SUBSTRING_EXPRESSION_LIST_OPS}, - {"SubstringParameters", &SUBSTRING_PARAMETERS_OPS}, - {"SubstringFromFor", &SUBSTRING_FROM_FOR_OPS}, - {"SubstringFromOptionalFor", &SUBSTRING_FROM_OPTIONAL_FOR_OPS}, - {"SubstringFor", &SUBSTRING_FOR_OPS}, - {"TrimExpression", &TRIM_EXPRESSION_OPS}, - {"TrimArguments", &TRIM_ARGUMENTS_OPS}, - {"TrimDirection", &TRIM_DIRECTION_OPS}, - {"TrimBoth", &TRIM_BOTH_OPS}, - {"TrimLeading", &TRIM_LEADING_OPS}, - {"TrimTrailing", &TRIM_TRAILING_OPS}, - {"TrimSource", &TRIM_SOURCE_OPS}, - {"OverlayExpression", &OVERLAY_EXPRESSION_OPS}, - {"OverlayArguments", &OVERLAY_ARGUMENTS_OPS}, - {"OverlayParameters", &OVERLAY_PARAMETERS_OPS}, - {"FromExpression", &FROM_EXPRESSION_OPS}, - {"ForExpression", &FOR_EXPRESSION_OPS}, - {"OverlayExpressionList", &OVERLAY_EXPRESSION_LIST_OPS}, - {"ExtractArgument", &EXTRACT_ARGUMENT_OPS}, - {"ExtractDatePartArgument", &EXTRACT_DATE_PART_ARGUMENT_OPS}, - {"ExtractIdentifierArgument", &EXTRACT_IDENTIFIER_ARGUMENT_OPS}, - {"ExtractStringArgument", &EXTRACT_STRING_ARGUMENT_OPS}, - {"ExtractDatePart", &EXTRACT_DATE_PART_OPS}, - {"ExternalResourceStatement", &EXTERNAL_RESOURCE_STATEMENT_OPS}, - {"CreateExternalResourceStmt", &CREATE_EXTERNAL_RESOURCE_STMT_OPS}, - {"RegisterExternalResourceStmt", ®ISTER_EXTERNAL_RESOURCE_STMT_OPS}, - {"DestroyExternalResourceStmt", &DESTROY_EXTERNAL_RESOURCE_STMT_OPS}, - {"ShowExternalResourcesStmt", &SHOW_EXTERNAL_RESOURCES_STMT_OPS}, - {"ShowAllModifier", &SHOW_ALL_MODIFIER_OPS}, - {"ExternalResourceCreationOptions", &EXTERNAL_RESOURCE_CREATION_OPTIONS_OPS}, - {"AttachToExternalResource", &ATTACH_TO_EXTERNAL_RESOURCE_OPS}, - {"ConnectToExternalResource", &CONNECT_TO_EXTERNAL_RESOURCE_OPS}, - {"ExternalResourceSource", &EXTERNAL_RESOURCE_SOURCE_OPS}, - {"ExternalResourceCreateClause", &EXTERNAL_RESOURCE_CREATE_CLAUSE_OPS}, - {"ExternalResourceReferenceClause", &EXTERNAL_RESOURCE_REFERENCE_CLAUSE_OPS}, - {"InsertStatement", &INSERT_STATEMENT_OPS}, - {"OrAction", &OR_ACTION_OPS}, - {"InsertOrReplace", &INSERT_OR_REPLACE_OPS}, - {"InsertOrIgnore", &INSERT_OR_IGNORE_OPS}, - {"ByNameOrPosition", &BY_NAME_OR_POSITION_OPS}, - {"InsertByNameOrder", &INSERT_BY_NAME_ORDER_OPS}, - {"InsertByPositionOrder", &INSERT_BY_POSITION_ORDER_OPS}, - {"InsertByName", &INSERT_BY_NAME_OPS}, - {"InsertByPosition", &INSERT_BY_POSITION_OPS}, - {"InsertTarget", &INSERT_TARGET_OPS}, - {"InsertAlias", &INSERT_ALIAS_OPS}, - {"ColumnList", &COLUMN_LIST_OPS}, - {"InsertColumnList", &INSERT_COLUMN_LIST_OPS}, - {"InsertValues", &INSERT_VALUES_OPS}, - {"SelectInsertValues", &SELECT_INSERT_VALUES_OPS}, - {"DefaultValues", &DEFAULT_VALUES_OPS}, - {"OnConflictClause", &ON_CONFLICT_CLAUSE_OPS}, - {"OnConflictTarget", &ON_CONFLICT_TARGET_OPS}, - {"OnConflictExpressionTarget", &ON_CONFLICT_EXPRESSION_TARGET_OPS}, - {"OnConflictIndexTarget", &ON_CONFLICT_INDEX_TARGET_OPS}, - {"OnConflictAction", &ON_CONFLICT_ACTION_OPS}, - {"OnConflictUpdate", &ON_CONFLICT_UPDATE_OPS}, - {"OnConflictNothing", &ON_CONFLICT_NOTHING_OPS}, - {"ReturningClause", &RETURNING_CLAUSE_OPS}, - {"LoadStatement", &LOAD_STATEMENT_OPS}, - {"ExtensionAlias", &EXTENSION_ALIAS_OPS}, - {"InstallStatement", &INSTALL_STATEMENT_OPS}, - {"InstallAndLoad", &INSTALL_AND_LOAD_OPS}, - {"UpdateExtensionsStatement", &UPDATE_EXTENSIONS_STATEMENT_OPS}, - {"FromSource", &FROM_SOURCE_OPS}, - {"FromSourceIdentifier", &FROM_SOURCE_IDENTIFIER_OPS}, - {"FromSourceString", &FROM_SOURCE_STRING_OPS}, - {"VersionNumber", &VERSION_NUMBER_OPS}, - {"ExtensionRepositoryStatement", &EXTENSION_REPOSITORY_STATEMENT_OPS}, - {"CreateExtensionRepositoryStmt", &CREATE_EXTENSION_REPOSITORY_STMT_OPS}, - {"RepositoryPrefix", &REPOSITORY_PREFIX_OPS}, - {"RepositoryPublicKey", &REPOSITORY_PUBLIC_KEY_OPS}, - {"DropExtensionRepositoryStmt", &DROP_EXTENSION_REPOSITORY_STMT_OPS}, - {"TableMatchRecognizeClause", &TABLE_MATCH_RECOGNIZE_CLAUSE_OPS}, - {"MatchRecognizeBody", &MATCH_RECOGNIZE_BODY_OPS}, - {"MatchRecognizeClause", &MATCH_RECOGNIZE_CLAUSE_OPS}, - {"MRPartition", &MRPARTITION_OPS}, - {"MROrderBy", &MRORDER_BY_OPS}, - {"MRMeasures", &MRMEASURES_OPS}, - {"MRRows", &MRROWS_OPS}, - {"MRSkip", &MRSKIP_OPS}, - {"MRPattern", &MRPATTERN_OPS}, - {"MRSubset", &MRSUBSET_OPS}, - {"MRDefineAuto", &MRDEFINE_AUTO_OPS}, - {"MRDefine", &MRDEFINE_OPS}, - {"MeasuresClause", &MEASURES_CLAUSE_OPS}, - {"MeasuresElement", &MEASURES_ELEMENT_OPS}, - {"MeasureSemantics", &MEASURE_SEMANTICS_OPS}, - {"RunningSemantics", &RUNNING_SEMANTICS_OPS}, - {"FinalSemantics", &FINAL_SEMANTICS_OPS}, - {"RowsPerMatch", &ROWS_PER_MATCH_OPS}, - {"OneRowPerMatch", &ONE_ROW_PER_MATCH_OPS}, - {"AllRowsPerMatch", &ALL_ROWS_PER_MATCH_OPS}, - {"AllRowsEmptyMatches", &ALL_ROWS_EMPTY_MATCHES_OPS}, - {"ShowEmptyMatches", &SHOW_EMPTY_MATCHES_OPS}, - {"OmitEmptyMatches", &OMIT_EMPTY_MATCHES_OPS}, - {"WithUnmatchedRows", &WITH_UNMATCHED_ROWS_OPS}, - {"AfterMatchSkip", &AFTER_MATCH_SKIP_OPS}, - {"AfterMatchSkipTarget", &AFTER_MATCH_SKIP_TARGET_OPS}, - {"SkipToNextRow", &SKIP_TO_NEXT_ROW_OPS}, - {"SkipPastLastRow", &SKIP_PAST_LAST_ROW_OPS}, - {"SkipToFirstVar", &SKIP_TO_FIRST_VAR_OPS}, - {"SkipToLastVar", &SKIP_TO_LAST_VAR_OPS}, - {"SkipToVar", &SKIP_TO_VAR_OPS}, - {"PatternClause", &PATTERN_CLAUSE_OPS}, - {"RowPattern", &ROW_PATTERN_OPS}, - {"RowPatternAlternative", &ROW_PATTERN_ALTERNATIVE_OPS}, - {"RowPatternTerm", &ROW_PATTERN_TERM_OPS}, - {"RowPatternFactor", &ROW_PATTERN_FACTOR_OPS}, - {"RowPatternPrimary", &ROW_PATTERN_PRIMARY_OPS}, - {"RowPatternPermute", &ROW_PATTERN_PERMUTE_OPS}, - {"RowPatternAnchor", &ROW_PATTERN_ANCHOR_OPS}, - {"PatternStart", &PATTERN_START_OPS}, - {"PatternEnd", &PATTERN_END_OPS}, - {"RowPatternGroup", &ROW_PATTERN_GROUP_OPS}, - {"RowPatternEmpty", &ROW_PATTERN_EMPTY_OPS}, - {"RowPatternExclusion", &ROW_PATTERN_EXCLUSION_OPS}, - {"RowPatternLabel", &ROW_PATTERN_LABEL_OPS}, - {"RowPatternQuantifier", &ROW_PATTERN_QUANTIFIER_OPS}, - {"RowPatternQuantifierKind", &ROW_PATTERN_QUANTIFIER_KIND_OPS}, - {"QuantifierReluctant", &QUANTIFIER_RELUCTANT_OPS}, - {"QuantifierStar", &QUANTIFIER_STAR_OPS}, - {"QuantifierPlus", &QUANTIFIER_PLUS_OPS}, - {"QuantifierOptional", &QUANTIFIER_OPTIONAL_OPS}, - {"QuantifierRange", &QUANTIFIER_RANGE_OPS}, - {"QuantifierBounds", &QUANTIFIER_BOUNDS_OPS}, - {"QuantifierMinMax", &QUANTIFIER_MIN_MAX_OPS}, - {"QuantifierMin", &QUANTIFIER_MIN_OPS}, - {"QuantifierMax", &QUANTIFIER_MAX_OPS}, - {"QuantifierExact", &QUANTIFIER_EXACT_OPS}, - {"SubsetClause", &SUBSET_CLAUSE_OPS}, - {"SubsetElement", &SUBSET_ELEMENT_OPS}, - {"DefineClause", &DEFINE_CLAUSE_OPS}, - {"DefineElement", &DEFINE_ELEMENT_OPS}, - {"MergeIntoStatement", &MERGE_INTO_STATEMENT_OPS}, - {"MergeIntoUsingClause", &MERGE_INTO_USING_CLAUSE_OPS}, - {"MergeMatch", &MERGE_MATCH_OPS}, - {"MatchedClause", &MATCHED_CLAUSE_OPS}, - {"MatchedClauseAction", &MATCHED_CLAUSE_ACTION_OPS}, - {"UpdateMatchClause", &UPDATE_MATCH_CLAUSE_OPS}, - {"UpdateMatchInfo", &UPDATE_MATCH_INFO_OPS}, - {"UpdateMatchSetAction", &UPDATE_MATCH_SET_ACTION_OPS}, - {"UpdateByNameOrPosition", &UPDATE_BY_NAME_OR_POSITION_OPS}, - {"DeleteMatchClause", &DELETE_MATCH_CLAUSE_OPS}, - {"InsertMatchClause", &INSERT_MATCH_CLAUSE_OPS}, - {"InsertMatchInfo", &INSERT_MATCH_INFO_OPS}, - {"InsertDefaultValues", &INSERT_DEFAULT_VALUES_OPS}, - {"InsertByNameOrPosition", &INSERT_BY_NAME_OR_POSITION_OPS}, - {"InsertValuesList", &INSERT_VALUES_LIST_OPS}, - {"DoNothingMatchClause", &DO_NOTHING_MATCH_CLAUSE_OPS}, - {"ErrorMatchClause", &ERROR_MATCH_CLAUSE_OPS}, - {"UpdateMatchSetClause", &UPDATE_MATCH_SET_CLAUSE_OPS}, - {"UpdateMatchSetInfo", &UPDATE_MATCH_SET_INFO_OPS}, - {"AndExpression", &AND_EXPRESSION_OPS}, - {"NotMatchedClause", &NOT_MATCHED_CLAUSE_OPS}, - {"BySourceOrTarget", &BY_SOURCE_OR_TARGET_OPS}, - {"BySource", &BY_SOURCE_OPS}, - {"ByTarget", &BY_TARGET_OPS}, - {"PivotStatement", &PIVOT_STATEMENT_OPS}, - {"PivotOn", &PIVOT_ON_OPS}, - {"PivotUsing", &PIVOT_USING_OPS}, - {"PivotColumnList", &PIVOT_COLUMN_LIST_OPS}, - {"PivotColumnEntry", &PIVOT_COLUMN_ENTRY_OPS}, - {"PivotColumnExpression", &PIVOT_COLUMN_EXPRESSION_OPS}, - {"PivotColumnSubquery", &PIVOT_COLUMN_SUBQUERY_OPS}, - {"UnpivotStatement", &UNPIVOT_STATEMENT_OPS}, - {"IntoNameValues", &INTO_NAME_VALUES_OPS}, - {"OptionalParensNameList", &OPTIONAL_PARENS_NAME_LIST_OPS}, - {"ParenthesizedNameList", &PARENTHESIZED_NAME_LIST_OPS}, - {"BareNameList", &BARE_NAME_LIST_OPS}, - {"IncludeOrExcludeNulls", &INCLUDE_OR_EXCLUDE_NULLS_OPS}, - {"IncludeNulls", &INCLUDE_NULLS_OPS}, - {"ExcludeNulls", &EXCLUDE_NULLS_OPS}, - {"UnpivotHeader", &UNPIVOT_HEADER_OPS}, - {"UnpivotHeaderSingle", &UNPIVOT_HEADER_SINGLE_OPS}, - {"UnpivotHeaderList", &UNPIVOT_HEADER_LIST_OPS}, - {"PragmaStatement", &PRAGMA_STATEMENT_OPS}, - {"PragmaAssignOrFunction", &PRAGMA_ASSIGN_OR_FUNCTION_OPS}, - {"PragmaAssign", &PRAGMA_ASSIGN_OPS}, - {"PragmaFunction", &PRAGMA_FUNCTION_OPS}, - {"PragmaParameters", &PRAGMA_PARAMETERS_OPS}, - {"PrepareStatement", &PREPARE_STATEMENT_OPS}, - {"TypeList", &TYPE_LIST_OPS}, - {"SelectStatement", &SELECT_STATEMENT_OPS}, - {"SelectStatementInternal", &SELECT_STATEMENT_INTERNAL_OPS}, - {"SelectSetOpChain", &SELECT_SET_OP_CHAIN_OPS}, - {"SelectSetOpChainTail", &SELECT_SET_OP_CHAIN_TAIL_OPS}, - {"IntersectChain", &INTERSECT_CHAIN_OPS}, - {"IntersectChainTail", &INTERSECT_CHAIN_TAIL_OPS}, - {"SetIntersectClause", &SET_INTERSECT_CLAUSE_OPS}, - {"SelectAtom", &SELECT_ATOM_OPS}, - {"SelectParens", &SELECT_PARENS_OPS}, - {"SetopClause", &SETOP_CLAUSE_OPS}, - {"SetopType", &SETOP_TYPE_OPS}, - {"SetopUnion", &SETOP_UNION_OPS}, - {"SetopExcept", &SETOP_EXCEPT_OPS}, - {"SelectStatementType", &SELECT_STATEMENT_TYPE_OPS}, - {"ResultModifiers", &RESULT_MODIFIERS_OPS}, - {"LimitOffset", &LIMIT_OFFSET_OPS}, - {"LimitOffsetClause", &LIMIT_OFFSET_CLAUSE_OPS}, - {"OffsetLimitClause", &OFFSET_LIMIT_CLAUSE_OPS}, - {"OffsetFetchClause", &OFFSET_FETCH_CLAUSE_OPS}, - {"FetchOffsetClause", &FETCH_OFFSET_CLAUSE_OPS}, - {"FetchOnlyClause", &FETCH_ONLY_CLAUSE_OPS}, - {"TableStatement", &TABLE_STATEMENT_OPS}, - {"OptionalParensSimpleSelect", &OPTIONAL_PARENS_SIMPLE_SELECT_OPS}, - {"SimpleSelectParens", &SIMPLE_SELECT_PARENS_OPS}, - {"SimpleSelect", &SIMPLE_SELECT_OPS}, - {"SelectFrom", &SELECT_FROM_OPS}, - {"SelectFromClause", &SELECT_FROM_CLAUSE_OPS}, - {"FromSelectClause", &FROM_SELECT_CLAUSE_OPS}, - {"WithStatement", &WITH_STATEMENT_OPS}, - {"CTEBody", &CTEBODY_OPS}, - {"CTESelectBody", &CTESELECT_BODY_OPS}, - {"CTEDMLBody", &CTEDMLBODY_OPS}, - {"UsingKey", &USING_KEY_OPS}, - {"Materialized", &MATERIALIZED_OPS}, - {"WithClause", &WITH_CLAUSE_OPS}, - {"SelectClause", &SELECT_CLAUSE_OPS}, - {"TargetList", &TARGET_LIST_OPS}, - {"ColumnAliases", &COLUMN_ALIASES_OPS}, - {"DistinctClause", &DISTINCT_CLAUSE_OPS}, - {"DistinctAll", &DISTINCT_ALL_OPS}, - {"DistinctOn", &DISTINCT_ON_OPS}, - {"DistinctOnTargets", &DISTINCT_ON_TARGETS_OPS}, - {"InnerTableRef", &INNER_TABLE_REF_OPS}, - {"TableRef", &TABLE_REF_OPS}, - {"TableSubquery", &TABLE_SUBQUERY_OPS}, - {"BaseTableRef", &BASE_TABLE_REF_OPS}, - {"TableAliasColon", &TABLE_ALIAS_COLON_OPS}, - {"ValuesRef", &VALUES_REF_OPS}, - {"ParensTableRef", &PARENS_TABLE_REF_OPS}, - {"JoinOrPivot", &JOIN_OR_PIVOT_OPS}, - {"TablePivotClause", &TABLE_PIVOT_CLAUSE_OPS}, - {"TablePivotClauseBody", &TABLE_PIVOT_CLAUSE_BODY_OPS}, - {"PivotGroupByList", &PIVOT_GROUP_BY_LIST_OPS}, - {"TableUnpivotClause", &TABLE_UNPIVOT_CLAUSE_OPS}, - {"TableUnpivotClauseBody", &TABLE_UNPIVOT_CLAUSE_BODY_OPS}, - {"PivotHeader", &PIVOT_HEADER_OPS}, - {"PivotValueList", &PIVOT_VALUE_LIST_OPS}, - {"PivotValueTarget", &PIVOT_VALUE_TARGET_OPS}, - {"PivotEnumTarget", &PIVOT_ENUM_TARGET_OPS}, - {"PivotListTarget", &PIVOT_LIST_TARGET_OPS}, - {"UnpivotValueList", &UNPIVOT_VALUE_LIST_OPS}, - {"PivotTargetList", &PIVOT_TARGET_LIST_OPS}, - {"UnpivotTargetList", &UNPIVOT_TARGET_LIST_OPS}, - {"Lateral", &LATERAL_OPS}, - {"BaseTableName", &BASE_TABLE_NAME_OPS}, - {"UnqualifiedBaseTableName", &UNQUALIFIED_BASE_TABLE_NAME_OPS}, - {"QualifiedTableName", &QUALIFIED_TABLE_NAME_OPS}, - {"SchemaReservedTable", &SCHEMA_RESERVED_TABLE_OPS}, - {"CatalogReservedSchemaTable", &CATALOG_RESERVED_SCHEMA_TABLE_OPS}, - {"TableFunction", &TABLE_FUNCTION_OPS}, - {"TableFunctionLateralOpt", &TABLE_FUNCTION_LATERAL_OPT_OPS}, - {"TableFunctionAliasColon", &TABLE_FUNCTION_ALIAS_COLON_OPS}, - {"WithOrdinality", &WITH_ORDINALITY_OPS}, - {"QualifiedTableFunction", &QUALIFIED_TABLE_FUNCTION_OPS}, - {"TableFunctionArguments", &TABLE_FUNCTION_ARGUMENTS_OPS}, - {"FunctionArgument", &FUNCTION_ARGUMENT_OPS}, - {"NamedFunctionArgument", &NAMED_FUNCTION_ARGUMENT_OPS}, - {"PositionalFunctionArgument", &POSITIONAL_FUNCTION_ARGUMENT_OPS}, - {"NamedParameter", &NAMED_PARAMETER_OPS}, - {"TableAlias", &TABLE_ALIAS_OPS}, - {"TableAliasAs", &TABLE_ALIAS_AS_OPS}, - {"TableAliasWithoutAs", &TABLE_ALIAS_WITHOUT_AS_OPS}, - {"AtClause", &AT_CLAUSE_OPS}, - {"AtSpecifier", &AT_SPECIFIER_OPS}, - {"AtUnit", &AT_UNIT_OPS}, - {"VersionAtUnit", &VERSION_AT_UNIT_OPS}, - {"TimestampAtUnit", &TIMESTAMP_AT_UNIT_OPS}, - {"JoinClause", &JOIN_CLAUSE_OPS}, - {"NearestJoinClause", &NEAREST_JOIN_CLAUSE_OPS}, - {"NearestJoinAliased", &NEAREST_JOIN_ALIASED_OPS}, - {"NearestJoinBare", &NEAREST_JOIN_BARE_OPS}, - {"NearestBareTableRef", &NEAREST_BARE_TABLE_REF_OPS}, - {"NearestValuesRef", &NEAREST_VALUES_REF_OPS}, - {"NearestTableFunction", &NEAREST_TABLE_FUNCTION_OPS}, - {"NearestTableSubquery", &NEAREST_TABLE_SUBQUERY_OPS}, - {"NearestBaseTableRef", &NEAREST_BASE_TABLE_REF_OPS}, - {"NearestParensTableRef", &NEAREST_PARENS_TABLE_REF_OPS}, - {"ApproxOrExact", &APPROX_OR_EXACT_OPS}, - {"NearestApprox", &NEAREST_APPROX_OPS}, - {"NearestExact", &NEAREST_EXACT_OPS}, - {"DistanceOrSimilarity", &DISTANCE_OR_SIMILARITY_OPS}, - {"NearestDistance", &NEAREST_DISTANCE_OPS}, - {"NearestSimilarity", &NEAREST_SIMILARITY_OPS}, - {"RegularJoinClause", ®ULAR_JOIN_CLAUSE_OPS}, - {"JoinByClause", &JOIN_BY_CLAUSE_OPS}, - {"Asof", &ASOF_OPS}, - {"JoinWithoutOnClause", &JOIN_WITHOUT_ON_CLAUSE_OPS}, - {"JoinQualifier", &JOIN_QUALIFIER_OPS}, - {"OnClause", &ON_CLAUSE_OPS}, - {"UsingClause", &USING_CLAUSE_OPS}, - {"UsingColumnName", &USING_COLUMN_NAME_OPS}, - {"JoinType", &JOIN_TYPE_OPS}, - {"JoinPrefix", &JOIN_PREFIX_OPS}, - {"CrossJoinPrefix", &CROSS_JOIN_PREFIX_OPS}, - {"NaturalJoinPrefix", &NATURAL_JOIN_PREFIX_OPS}, - {"PositionalJoinPrefix", &POSITIONAL_JOIN_PREFIX_OPS}, - {"FullJoin", &FULL_JOIN_OPS}, - {"LeftJoin", &LEFT_JOIN_OPS}, - {"RightJoin", &RIGHT_JOIN_OPS}, - {"SemiJoin", &SEMI_JOIN_OPS}, - {"AntiJoin", &ANTI_JOIN_OPS}, - {"InnerJoin", &INNER_JOIN_OPS}, - {"FromClause", &FROM_CLAUSE_OPS}, - {"WhereClause", &WHERE_CLAUSE_OPS}, - {"GroupByClause", &GROUP_BY_CLAUSE_OPS}, - {"HavingClause", &HAVING_CLAUSE_OPS}, - {"QualifyClause", &QUALIFY_CLAUSE_OPS}, - {"SampleClause", &SAMPLE_CLAUSE_OPS}, - {"SelectSampleClause", &SELECT_SAMPLE_CLAUSE_OPS}, - {"WindowClause", &WINDOW_CLAUSE_OPS}, - {"WindowDefinition", &WINDOW_DEFINITION_OPS}, - {"SampleEntry", &SAMPLE_ENTRY_OPS}, - {"SampleEntryCount", &SAMPLE_ENTRY_COUNT_OPS}, - {"SampleEntryFunction", &SAMPLE_ENTRY_FUNCTION_OPS}, - {"SampleFunction", &SAMPLE_FUNCTION_OPS}, - {"SampleProperties", &SAMPLE_PROPERTIES_OPS}, - {"RepeatableSample", &REPEATABLE_SAMPLE_OPS}, - {"SampleSeed", &SAMPLE_SEED_OPS}, - {"SampleCount", &SAMPLE_COUNT_OPS}, - {"SampleValue", &SAMPLE_VALUE_OPS}, - {"SampleUnit", &SAMPLE_UNIT_OPS}, - {"SamplePercentage", &SAMPLE_PERCENTAGE_OPS}, - {"SampleRows", &SAMPLE_ROWS_OPS}, - {"GroupByExpressions", &GROUP_BY_EXPRESSIONS_OPS}, - {"GroupByAll", &GROUP_BY_ALL_OPS}, - {"GroupByList", &GROUP_BY_LIST_OPS}, - {"GroupByExpression", &GROUP_BY_EXPRESSION_OPS}, - {"GroupByBaseExpression", &GROUP_BY_BASE_EXPRESSION_OPS}, - {"EmptyGroupingItem", &EMPTY_GROUPING_ITEM_OPS}, - {"CubeOrRollupClause", &CUBE_OR_ROLLUP_CLAUSE_OPS}, - {"CubeOrRollup", &CUBE_OR_ROLLUP_OPS}, - {"CubeKeyword", &CUBE_KEYWORD_OPS}, - {"RollupKeyword", &ROLLUP_KEYWORD_OPS}, - {"GroupingSetsClause", &GROUPING_SETS_CLAUSE_OPS}, - {"SubqueryReference", &SUBQUERY_REFERENCE_OPS}, - {"OrderByExpression", &ORDER_BY_EXPRESSION_OPS}, - {"DescOrAsc", &DESC_OR_ASC_OPS}, - {"DescendingOrder", &DESCENDING_ORDER_OPS}, - {"AscendingOrder", &ASCENDING_ORDER_OPS}, - {"NullsFirstOrLast", &NULLS_FIRST_OR_LAST_OPS}, - {"NullsFirst", &NULLS_FIRST_OPS}, - {"NullsLast", &NULLS_LAST_OPS}, - {"OrderByClause", &ORDER_BY_CLAUSE_OPS}, - {"OrderByExpressions", &ORDER_BY_EXPRESSIONS_OPS}, - {"OrderByExpressionList", &ORDER_BY_EXPRESSION_LIST_OPS}, - {"OrderByAll", &ORDER_BY_ALL_OPS}, - {"LimitClause", &LIMIT_CLAUSE_OPS}, - {"OffsetClause", &OFFSET_CLAUSE_OPS}, - {"OffsetValue", &OFFSET_VALUE_OPS}, - {"LimitValue", &LIMIT_VALUE_OPS}, - {"LimitAll", &LIMIT_ALL_OPS}, - {"LimitLiteralPercent", &LIMIT_LITERAL_PERCENT_OPS}, - {"LimitExpression", &LIMIT_EXPRESSION_OPS}, - {"FetchClause", &FETCH_CLAUSE_OPS}, - {"FetchClauseWithoutValue", &FETCH_CLAUSE_WITHOUT_VALUE_OPS}, - {"FetchClauseWithValue", &FETCH_CLAUSE_WITH_VALUE_OPS}, - {"FetchValue", &FETCH_VALUE_OPS}, - {"AliasedExpression", &ALIASED_EXPRESSION_OPS}, - {"ColIdExpression", &COL_ID_EXPRESSION_OPS}, - {"ExpressionAsCollabel", &EXPRESSION_AS_COLLABEL_OPS}, - {"ExpressionOptIdentifier", &EXPRESSION_OPT_IDENTIFIER_OPS}, - {"ValuesClause", &VALUES_CLAUSE_OPS}, - {"ValuesExpressions", &VALUES_EXPRESSIONS_OPS}, - {"SetStatement", &SET_STATEMENT_OPS}, - {"SetKeywordStatement", &SET_KEYWORD_STATEMENT_OPS}, - {"VariableAssignment", &VARIABLE_ASSIGNMENT_OPS}, - {"SetAssignmentOrTimeZone", &SET_ASSIGNMENT_OR_TIME_ZONE_OPS}, - {"ResetStatement", &RESET_STATEMENT_OPS}, - {"ResetTarget", &RESET_TARGET_OPS}, - {"ResetTimeZone", &RESET_TIME_ZONE_OPS}, - {"ResetVariableOrSetting", &RESET_VARIABLE_OR_SETTING_OPS}, - {"SetSchema", &SET_SCHEMA_OPS}, - {"StandardAssignment", &STANDARD_ASSIGNMENT_OPS}, - {"SetVariableOrSetting", &SET_VARIABLE_OR_SETTING_OPS}, - {"SetTimeZone", &SET_TIME_ZONE_OPS}, - {"ZoneValue", &ZONE_VALUE_OPS}, - {"ZoneLocal", &ZONE_LOCAL_OPS}, - {"ZoneDefault", &ZONE_DEFAULT_OPS}, - {"ZoneStringLiteral", &ZONE_STRING_LITERAL_OPS}, - {"ZoneIdentifier", &ZONE_IDENTIFIER_OPS}, - {"ZoneIntervalWithInterval", &ZONE_INTERVAL_WITH_INTERVAL_OPS}, - {"ZoneIntervalWithPrecision", &ZONE_INTERVAL_WITH_PRECISION_OPS}, - {"SetSetting", &SET_SETTING_OPS}, - {"SetVariable", &SET_VARIABLE_OPS}, - {"VariableScope", &VARIABLE_SCOPE_OPS}, - {"SettingScope", &SETTING_SCOPE_OPS}, - {"LocalScope", &LOCAL_SCOPE_OPS}, - {"SessionScope", &SESSION_SCOPE_OPS}, - {"GlobalScope", &GLOBAL_SCOPE_OPS}, - {"SetAssignment", &SET_ASSIGNMENT_OPS}, - {"VariableList", &VARIABLE_LIST_OPS}, - {"TransactionStatement", &TRANSACTION_STATEMENT_OPS}, - {"BeginTransaction", &BEGIN_TRANSACTION_OPS}, - {"RollbackTransaction", &ROLLBACK_TRANSACTION_OPS}, - {"CommitTransaction", &COMMIT_TRANSACTION_OPS}, - {"ReadOrWrite", &READ_OR_WRITE_OPS}, - {"ReadOnlyOrReadWrite", &READ_ONLY_OR_READ_WRITE_OPS}, - {"ReadOnly", &READ_ONLY_OPS}, - {"ReadWrite", &READ_WRITE_OPS}, - {"UpdateStatement", &UPDATE_STATEMENT_OPS}, - {"UpdateTarget", &UPDATE_TARGET_OPS}, - {"BaseTableSet", &BASE_TABLE_SET_OPS}, - {"BaseTableAliasSet", &BASE_TABLE_ALIAS_SET_OPS}, - {"UpdateAlias", &UPDATE_ALIAS_OPS}, - {"UpdateSetClauseList", &UPDATE_SET_CLAUSE_LIST_OPS}, - {"UpdateSetClause", &UPDATE_SET_CLAUSE_OPS}, - {"UpdateSetTuple", &UPDATE_SET_TUPLE_OPS}, - {"UpdateSetElement", &UPDATE_SET_ELEMENT_OPS}, - {"UpdateSetColumnTarget", &UPDATE_SET_COLUMN_TARGET_OPS}, - {"UseStatement", &USE_STATEMENT_OPS}, - {"UseTarget", &USE_TARGET_OPS}, - {"SchemaNameAsUseTarget", &SCHEMA_NAME_AS_USE_TARGET_OPS}, - {"CatalogNameAsUseTarget", &CATALOG_NAME_AS_USE_TARGET_OPS}, - {"UseTargetCatalogSchema", &USE_TARGET_CATALOG_SCHEMA_OPS}, - {"DotIdentifier", &DOT_IDENTIFIER_OPS}, - {"VacuumStatement", &VACUUM_STATEMENT_OPS}, - {"VacuumOptions", &VACUUM_OPTIONS_OPS}, - {"VacuumParensOptions", &VACUUM_PARENS_OPTIONS_OPS}, - {"VacuumLegacyOptions", &VACUUM_LEGACY_OPTIONS_OPS}, - {"VacuumOption", &VACUUM_OPTION_OPS}, - {"OptAnalyze", &OPT_ANALYZE_OPS}, - {"OptFull", &OPT_FULL_OPS}, - {"OptFreeze", &OPT_FREEZE_OPS}, - {"OptVerbose", &OPT_VERBOSE_OPS}, - {"NameList", &NAME_LIST_OPS}, - }; + static const case_insensitive_map_t result = BuildGeneratedTransformFrameOps(); return result; } @@ -4488,13 +9286,6 @@ PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAlterStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AlterOptions), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAlterStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4503,44 +9294,6 @@ PEGTransformerFactory::FinalizeAlterStatementTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAlterOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeAlterTableStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(3)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::AlterTableOptions), list_items[child_idx].get()}, - 2 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(2)}, 1); - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAlterTableStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4561,18 +9314,6 @@ PEGTransformerFactory::FinalizeAlterTableStmtTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterSchemaStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::AlterSchemaOptions), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 1); - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAlterSchemaStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4586,55 +9327,6 @@ PEGTransformerFactory::FinalizeAlterSchemaStmtTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterSchemaOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAlterSchemaOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeAlterTableOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAlterTableOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeAddConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TopLevelConstraint), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAddConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4643,21 +9335,6 @@ PEGTransformerFactory::FinalizeAddConstraintTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &drop_behavior_opt = list_pr.GetChild(4).Cast(); - if (drop_behavior_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DropBehavior), drop_behavior_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::ConstraintName), list_pr.GetChild(3)}, 1); - auto &if_exists_opt = list_pr.GetChild(2).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4674,17 +9351,6 @@ PEGTransformerFactory::FinalizeDropConstraintTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAddColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::AddColumnEntry), list_pr.GetChild(3)}, 1); - auto &if_not_exists_opt = list_pr.GetChild(2).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAddColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -4700,35 +9366,6 @@ arena_ptr PEGTransformerFactory::FinalizeAddColumnTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAddColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(3).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(4 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColumnConstraint), repeat_children[child_idx].get()}, - 3 + child_idx); - } - } else { - process.ReserveChildSlots(4 - 1); - } - auto &generated_column_opt = list_pr.GetChild(2).Cast(); - if (generated_column_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::GeneratedColumn), generated_column_opt.GetResult()}, 2); - } - auto &type_opt = list_pr.GetChild(1).Cast(); - if (type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Type), type_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::DottedIdentifier), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAddColumnEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4763,21 +9400,6 @@ PEGTransformerFactory::FinalizeAddColumnEntryTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDropColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &drop_behavior_opt = list_pr.GetChild(4).Cast(); - if (drop_behavior_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DropBehavior), drop_behavior_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::NestedColumnName), list_pr.GetChild(3)}, 1); - auto &if_exists_opt = list_pr.GetChild(2).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -4797,14 +9419,6 @@ PEGTransformerFactory::FinalizeDropColumnTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::AlterColumnEntry), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::NestedColumnName), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAlterColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -4818,14 +9432,6 @@ PEGTransformerFactory::FinalizeAlterColumnTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRenameColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(4)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::NestedColumnName), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRenameColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -4838,26 +9444,6 @@ PEGTransformerFactory::FinalizeRenameColumnTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNestedColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(0).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::IdentifierDot), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeNestedColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4883,11 +9469,6 @@ PEGTransformerFactory::FinalizeNestedColumnNameTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIdentifierDotTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIdentifierDotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4897,13 +9478,6 @@ PEGTransformerFactory::FinalizeIdentifierDotTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRenameAlterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRenameAlterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id_or_string = process.TakeResult(0); @@ -4911,18 +9485,6 @@ PEGTransformerFactory::FinalizeRenameAlterTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetPartitionedByTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(3))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeSetPartitionedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4937,11 +9499,6 @@ PEGTransformerFactory::FinalizeSetPartitionedByTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeResetPartitionedByTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeResetPartitionedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4949,14 +9506,6 @@ PEGTransformerFactory::FinalizeResetPartitionedByTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetSortedByTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::OrderByExpressions), ExtractResultFromParens(list_pr.GetChild(3))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSetSortedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto order_by_expressions = process.TakeResult>(0); @@ -4964,11 +9513,6 @@ PEGTransformerFactory::FinalizeSetSortedByTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeResetSortedByTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeResetSortedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -4976,13 +9520,6 @@ PEGTransformerFactory::FinalizeResetSortedByTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RelOptionList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSetOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto rel_option_list = process.TakeResult>>(0); @@ -4990,13 +9527,6 @@ PEGTransformerFactory::FinalizeSetOptionsTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeResetOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RelOptionList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeResetOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto rel_option_list = process.TakeResult>>(0); @@ -5004,55 +9534,6 @@ PEGTransformerFactory::FinalizeResetOptionsTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAlterColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeAddOrDropDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAddOrDropDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeAddDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAddDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -5060,24 +9541,12 @@ PEGTransformerFactory::FinalizeAddDefaultTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDropDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformDropDefault(transformer); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeChangeNullabilityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::DropOrSet), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeChangeNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5086,24 +9555,6 @@ PEGTransformerFactory::FinalizeChangeNullabilityTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropOrSetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDropOrSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -5127,11 +9578,6 @@ arena_ptr PEGTransformerFactory::FinalizeDropOrSetTrampoli return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDropNullabilityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDropNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5139,11 +9585,6 @@ PEGTransformerFactory::FinalizeDropNullabilityTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSetNullabilityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSetNullabilityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5151,24 +9592,6 @@ PEGTransformerFactory::FinalizeSetNullabilityTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAlterTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &using_expression_opt = list_pr.GetChild(4).Cast(); - if (using_expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::UsingExpression), using_expression_opt.GetResult()}, 2); - } - auto &column_collation_opt = list_pr.GetChild(3).Cast(); - if (column_collation_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ColumnCollation), column_collation_opt.GetResult()}, 1); - } - auto &type_opt = list_pr.GetChild(2).Cast(); - if (type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Type), type_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAlterTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -5192,13 +9615,6 @@ arena_ptr PEGTransformerFactory::FinalizeAlterTypeTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUsingExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUsingExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5207,18 +9623,6 @@ PEGTransformerFactory::FinalizeUsingExpressionTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterViewStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::RenameAlter), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(2)}, 1); - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAlterViewStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5232,18 +9636,6 @@ PEGTransformerFactory::FinalizeAlterViewStmtTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterSequenceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::AlterSequenceOptions), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedSequenceName), list_pr.GetChild(2)}, 1); - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAlterSequenceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5258,22 +9650,6 @@ PEGTransformerFactory::FinalizeAlterSequenceStmtTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeQualifiedSequenceNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &schema_qualification_opt = list_pr.GetChild(1).Cast(); - if (schema_qualification_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), schema_qualification_opt.GetResult()}, - 1); - } - auto &catalog_qualification_opt = list_pr.GetChild(0).Cast(); - if (catalog_qualification_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), catalog_qualification_opt.GetResult()}, - 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5292,34 +9668,6 @@ PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAlterSequenceOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAlterSequenceOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRenameAlterSequenceOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RenameAlter), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRenameAlterSequenceOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5328,20 +9676,6 @@ PEGTransformerFactory::FinalizeRenameAlterSequenceOptionsTrampoline(PEGTransform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetSequenceOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(0).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SequenceOption), repeat_children[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeSetSequenceOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5358,16 +9692,6 @@ PEGTransformerFactory::FinalizeSetSequenceOptionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAlterDatabaseStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAlterDatabaseStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5382,21 +9706,6 @@ PEGTransformerFactory::FinalizeAlterDatabaseStmtTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAnalyzeStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &analyze_target_opt = list_pr.GetChild(2).Cast(); - if (analyze_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AnalyzeTarget), analyze_target_opt.GetResult()}, 2); - } - auto &analyze_verbose_opt = list_pr.GetChild(1).Cast(); - if (analyze_verbose_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AnalyzeVerbose), analyze_verbose_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::AnalyzeKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAnalyzeStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5413,17 +9722,6 @@ PEGTransformerFactory::FinalizeAnalyzeStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAnalyzeTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &name_list_opt = list_pr.GetChild(1).Cast(); - if (name_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::NameList), name_list_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAnalyzeTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5436,11 +9734,6 @@ PEGTransformerFactory::FinalizeAnalyzeTargetTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeAnalyzeVerboseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAnalyzeVerboseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5448,29 +9741,6 @@ PEGTransformerFactory::FinalizeAnalyzeVerboseTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAttachStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &attach_options_opt = list_pr.GetChild(6).Cast(); - if (attach_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AttachOptions), attach_options_opt.GetResult()}, 4); - } - auto &attach_alias_opt = list_pr.GetChild(5).Cast(); - if (attach_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AttachAlias), attach_alias_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::DatabasePath), list_pr.GetChild(4)}, 2); - auto &if_not_exists_opt = list_pr.GetChild(2).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 1); - } - auto &or_replace_opt = list_pr.GetChild(1).Cast(); - if (or_replace_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrReplace), or_replace_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAttachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5500,13 +9770,6 @@ PEGTransformerFactory::FinalizeAttachStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDatabasePathTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDatabasePathTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -5514,13 +9777,6 @@ PEGTransformerFactory::FinalizeDatabasePathTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAttachAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAttachAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id = process.TakeResult(0); @@ -5528,13 +9784,6 @@ PEGTransformerFactory::FinalizeAttachAliasTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAttachOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::GenericCopyOptionList), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAttachOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5543,14 +9792,6 @@ PEGTransformerFactory::FinalizeAttachOptionsTrampoline(PEGTransformer &transform return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeCallStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::TableFunctionArguments), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTableFunction), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCallStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5560,16 +9801,6 @@ PEGTransformerFactory::FinalizeCallStatementTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCheckpointStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &checkpoint_force_opt = list_pr.GetChild(0).Cast(); - if (checkpoint_force_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CheckpointForce), checkpoint_force_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCheckpointStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5587,11 +9818,6 @@ PEGTransformerFactory::FinalizeCheckpointStatementTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCheckpointForceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCheckpointForceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5599,15 +9825,6 @@ PEGTransformerFactory::FinalizeCheckpointForceTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::CommentValue), list_pr.GetChild(5)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::CommentTarget), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::CommentOnType), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5618,34 +9835,6 @@ PEGTransformerFactory::FinalizeCommentStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCommentTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCommentTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeCommentStringLiteralIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::StringLiteralIdentifier), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentStringLiteralIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5654,43 +9843,12 @@ PEGTransformerFactory::FinalizeCommentStringLiteralIdentifierTrampoline(PEGTrans return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeCommentOnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCommentOnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCommentTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCommentTable(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentSequenceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentSequenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5698,11 +9856,6 @@ PEGTransformerFactory::FinalizeCommentSequenceTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5710,11 +9863,6 @@ PEGTransformerFactory::FinalizeCommentFunctionTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentMacroTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentMacroTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5722,33 +9870,18 @@ PEGTransformerFactory::FinalizeCommentMacroTableTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentMacroTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentMacroTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCommentMacro(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentViewTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentViewTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCommentView(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentDatabaseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentDatabaseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5756,22 +9889,12 @@ PEGTransformerFactory::FinalizeCommentDatabaseTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCommentIndex(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentSchemaTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5779,22 +9902,12 @@ PEGTransformerFactory::FinalizeCommentSchemaTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCommentType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommentColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5802,31 +9915,6 @@ PEGTransformerFactory::FinalizeCommentColumnTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCommentValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCommentValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeStringLiteralValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeStringLiteralValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5836,11 +9924,6 @@ PEGTransformerFactory::FinalizeStringLiteralValueTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAnalyzeKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAnalyzeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5848,24 +9931,12 @@ PEGTransformerFactory::FinalizeAnalyzeKeywordTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIndexNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIndexNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = process.parse_result.Cast().identifier.GetIdentifierName(); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeConstraintNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeConstraintNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5874,22 +9945,12 @@ PEGTransformerFactory::FinalizeConstraintNameTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSequenceNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSequenceNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = process.parse_result.Cast().identifier.GetIdentifierName(); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCollationNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCollationNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5899,11 +9960,6 @@ PEGTransformerFactory::FinalizeCollationNameTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNumberLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNumberLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5911,11 +9967,6 @@ PEGTransformerFactory::FinalizeNumberLiteralTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -5923,26 +9974,6 @@ PEGTransformerFactory::FinalizeStringLiteralTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ArrayBounds), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TypeVariations), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -5967,57 +9998,6 @@ arena_ptr PEGTransformerFactory::FinalizeTypeTrampoline(PE return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTypeVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTypeVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSimpleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSimpleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCharacterSimpleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &type_modifiers_opt = list_pr.GetChild(1).Cast(); - if (type_modifiers_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeModifiers), type_modifiers_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCharacterSimpleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6029,17 +10009,6 @@ PEGTransformerFactory::FinalizeCharacterSimpleTypeTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeQualifiedSimpleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &type_modifiers_opt = list_pr.GetChild(1).Cast(); - if (type_modifiers_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeModifiers), type_modifiers_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTypeName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeQualifiedSimpleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6052,75 +10021,6 @@ PEGTransformerFactory::FinalizeQualifiedSimpleTypeTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntervalTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIntervalTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIntervalIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIntervalIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIntervalWithSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIntervalWithSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIntervalWithRangeSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IntervalToIntervalAsType), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIntervalWithRangeSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6129,13 +10029,6 @@ PEGTransformerFactory::FinalizeIntervalWithRangeSpecifierTrampoline(PEGTransform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntervalWithSimpleSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Interval), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIntervalWithSimpleSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6144,11 +10037,6 @@ PEGTransformerFactory::FinalizeIntervalWithSimpleSpecifierTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntervalWithoutSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIntervalWithoutSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6156,20 +10044,6 @@ PEGTransformerFactory::FinalizeIntervalWithoutSpecifierTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntervalToIntervalAsTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - return; - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIntervalToIntervalAsTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6184,55 +10058,30 @@ PEGTransformerFactory::FinalizeIntervalToIntervalAsTypeTrampoline(PEGTransformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeYearKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeYearKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformYearKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMonthKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMonthKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformMonthKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDayKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDayKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformDayKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeHourKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeHourKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformHourKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMinuteKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMinuteKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6240,11 +10089,6 @@ PEGTransformerFactory::FinalizeMinuteKeywordTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSecondKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6252,11 +10096,6 @@ PEGTransformerFactory::FinalizeSecondKeywordTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMillisecondKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMillisecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6264,11 +10103,6 @@ PEGTransformerFactory::FinalizeMillisecondKeywordTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMicrosecondKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMicrosecondKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6276,22 +10110,12 @@ PEGTransformerFactory::FinalizeMicrosecondKeywordTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWeekKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWeekKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWeekKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuarterKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuarterKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6299,11 +10123,6 @@ PEGTransformerFactory::FinalizeQuarterKeywordTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDecadeKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDecadeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6311,11 +10130,6 @@ PEGTransformerFactory::FinalizeDecadeKeywordTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCenturyKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCenturyKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6323,11 +10137,6 @@ PEGTransformerFactory::FinalizeCenturyKeywordTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMillenniumKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMillenniumKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6335,55 +10144,6 @@ PEGTransformerFactory::FinalizeMillenniumKeywordTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeIntervalToIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIntervalToIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeYearToMonthTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::MonthKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::YearKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeYearToMonthTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto year_keyword = process.TakeResult(0); @@ -6392,14 +10152,6 @@ PEGTransformerFactory::FinalizeYearToMonthTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDayToHourTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::HourKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::DayKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDayToHourTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto day_keyword = process.TakeResult(0); @@ -6408,14 +10160,6 @@ arena_ptr PEGTransformerFactory::FinalizeDayToHourTrampoli return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDayToMinuteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::MinuteKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::DayKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDayToMinuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto day_keyword = process.TakeResult(0); @@ -6424,14 +10168,6 @@ PEGTransformerFactory::FinalizeDayToMinuteTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDayToSecondTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SecondKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::DayKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDayToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto day_keyword = process.TakeResult(0); @@ -6440,14 +10176,6 @@ PEGTransformerFactory::FinalizeDayToSecondTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeHourToMinuteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::MinuteKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::HourKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeHourToMinuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto hour_keyword = process.TakeResult(0); @@ -6456,14 +10184,6 @@ PEGTransformerFactory::FinalizeHourToMinuteTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeHourToSecondTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SecondKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::HourKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeHourToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto hour_keyword = process.TakeResult(0); @@ -6472,14 +10192,6 @@ PEGTransformerFactory::FinalizeHourToSecondTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMinuteToSecondTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SecondKeyword), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::MinuteKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMinuteToSecondTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6489,24 +10201,6 @@ PEGTransformerFactory::FinalizeMinuteToSecondTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBitTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = list_pr.GetChild(2).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_opt.GetResult())); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeBitTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -6532,17 +10226,6 @@ arena_ptr PEGTransformerFactory::FinalizeBitTypeTrampoline return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeGeometryTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(expression_opt.GetResult())}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeGeometryTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional> expression {}; @@ -6553,57 +10236,12 @@ PEGTransformerFactory::FinalizeGeometryTypeTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeVariantTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeVariantTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformVariantType(transformer); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNumericTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeNumericTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSimpleNumericTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && - (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR || - choice_result.type == ParseResultType::CHOICE || choice_result.type == ParseResultType::LIST)) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSimpleNumericTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6629,109 +10267,48 @@ PEGTransformerFactory::FinalizeSimpleNumericTypeTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDecimalNumericTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDecimalNumericTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIntTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIntTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformIntType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIntegerTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIntegerTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformIntegerType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSmallintTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSmallintTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSmallintType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBigintTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeBigintTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformBigintType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRealTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRealTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformRealType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBooleanTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeBooleanTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformBooleanType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDoubleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDoubleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformDoubleType(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFloatTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFloatTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -6744,16 +10321,6 @@ arena_ptr PEGTransformerFactory::FinalizeFloatTypeTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDecimalTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &type_modifiers_opt = list_pr.GetChild(1).Cast(); - if (type_modifiers_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeModifiers), type_modifiers_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDecimalTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional>> type_modifiers {}; @@ -6764,16 +10331,6 @@ PEGTransformerFactory::FinalizeDecimalTypeTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDecTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &type_modifiers_opt = list_pr.GetChild(1).Cast(); - if (type_modifiers_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeModifiers), type_modifiers_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDecTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional>> type_modifiers {}; @@ -6784,16 +10341,6 @@ arena_ptr PEGTransformerFactory::FinalizeDecTypeTrampoline return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNumericModTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &type_modifiers_opt = list_pr.GetChild(1).Cast(); - if (type_modifiers_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeModifiers), type_modifiers_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNumericModTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6805,32 +10352,6 @@ PEGTransformerFactory::FinalizeNumericModTypeTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeQualifiedTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeQualifiedTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeTypeNameAsQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTypeNameAsQualifiedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6840,22 +10361,6 @@ PEGTransformerFactory::FinalizeTypeNameAsQualifiedNameTrampoline(PEGTransformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCatalogReservedSchemaTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(1).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ReservedSchemaQualification), repeat_children[child_idx].get()}, - 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaTypeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6875,13 +10380,6 @@ PEGTransformerFactory::FinalizeCatalogReservedSchemaTypeNameTrampoline(PEGTransf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSchemaReservedTypeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaReservedTypeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6892,24 +10390,6 @@ PEGTransformerFactory::FinalizeSchemaReservedTypeNameTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTypeModifiersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeTypeModifiersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -6933,27 +10413,6 @@ PEGTransformerFactory::FinalizeTypeModifiersTrampoline(PEGTransformer &transform return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeNestedTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ArrayBounds), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TypeVariations), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNestedTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -6978,16 +10437,6 @@ PEGTransformerFactory::FinalizeNestedTypeTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &col_id_type_list_opt = list_pr.GetChild(1).Cast(); - if (col_id_type_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ColIdTypeList), col_id_type_list_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeRowTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional>>> col_id_type_list {}; @@ -6998,13 +10447,6 @@ arena_ptr PEGTransformerFactory::FinalizeRowTypeTrampoline return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetofTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::NestedType), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSetofTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto nested_type = process.TakeResult>(0); @@ -7012,13 +10454,6 @@ arena_ptr PEGTransformerFactory::FinalizeSetofTypeTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUnionTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdTypeList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUnionTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id_type_list = process.TakeResult>>>(0); @@ -7026,18 +10461,6 @@ arena_ptr PEGTransformerFactory::FinalizeUnionTypeTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColIdTypeListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdType), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeColIdTypeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7052,24 +10475,6 @@ PEGTransformerFactory::FinalizeColIdTypeListTrampoline(PEGTransformer &transform return transformer.MakeResult>>>(std::move(result)); } -void PEGTransformerFactory::InitializeMapTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_opt.GetResult())); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::NestedType), list_items[child_idx].get()}, 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeMapTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -7092,18 +10497,6 @@ arena_ptr PEGTransformerFactory::FinalizeMapTypeTrampoline return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTupleTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(1))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::NestedType), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeTupleTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -7117,14 +10510,6 @@ arena_ptr PEGTransformerFactory::FinalizeTupleTypeTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColIdTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::NestedType), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColIdTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id = process.TakeResult(0); @@ -7133,44 +10518,12 @@ arena_ptr PEGTransformerFactory::FinalizeColIdTypeTrampoli return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeArrayBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeArrayBoundsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeArrayKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeArrayKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformArrayKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeArrayKeywordWithBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SquareBracketsArray), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeArrayKeywordWithBoundsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7179,16 +10532,6 @@ PEGTransformerFactory::FinalizeArrayKeywordWithBoundsTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSquareBracketsArrayTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSquareBracketsArrayTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7200,21 +10543,6 @@ PEGTransformerFactory::FinalizeSquareBracketsArrayTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTimeTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &time_zone_opt = list_pr.GetChild(2).Cast(); - if (time_zone_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TimeZone), time_zone_opt.GetResult()}, 2); - } - auto &type_modifiers_opt = list_pr.GetChild(1).Cast(); - if (type_modifiers_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeModifiers), type_modifiers_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TimeOrTimestamp), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTimeTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto time_or_timestamp = process.TakeResult(0); @@ -7230,43 +10558,12 @@ arena_ptr PEGTransformerFactory::FinalizeTimeTypeTrampolin return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTimeOrTimestampTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTimeOrTimestampTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeTimeTypeIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTimeTypeIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformTimeTypeId(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTimestampTypeIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTimestampTypeIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7274,13 +10571,6 @@ PEGTransformerFactory::FinalizeTimestampTypeIdTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTimeZoneTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::WithOrWithout), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto with_or_without = process.TakeResult(0); @@ -7288,59 +10578,18 @@ arena_ptr PEGTransformerFactory::FinalizeTimeZoneTrampolin return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWithOrWithoutTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeWithOrWithoutTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeWithRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWithRule(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWithoutRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithoutRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWithoutRule(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeConnectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &session_target_opt = list_pr.GetChild(1).Cast(); - if (session_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SessionTarget), session_target_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeConnectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7352,11 +10601,6 @@ PEGTransformerFactory::FinalizeConnectStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDisconnectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDisconnectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7364,32 +10608,6 @@ PEGTransformerFactory::FinalizeDisconnectStatementTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeLocalSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLocalSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7397,17 +10615,6 @@ PEGTransformerFactory::FinalizeLocalSessionTargetTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeStringSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &generic_copy_option_list_opt = list_pr.GetChild(1).Cast(); - if (generic_copy_option_list_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::GenericCopyOptionList), generic_copy_option_list_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeStringSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7421,11 +10628,6 @@ PEGTransformerFactory::FinalizeStringSessionTargetTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCatalogSessionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogSessionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7435,13 +10637,6 @@ PEGTransformerFactory::FinalizeCatalogSessionTargetTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::CopyVariations), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7450,48 +10645,6 @@ PEGTransformerFactory::FinalizeCopyStatementTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCopyTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(6); - auto ©_options_opt = list_pr.GetChild(5).Cast(); - if (copy_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CopyOptions), copy_options_opt.GetResult()}, 5); - } - auto ©_legacy_option_opt = list_pr.GetChild(4).Cast(); - if (copy_legacy_option_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CopyLegacyOption), copy_legacy_option_opt.GetResult()}, 4); - } - process.PushChild({transformer.GetRule(PEGRuleId::CopyFileName), list_pr.GetChild(3)}, 3); - process.PushChild({transformer.GetRule(PEGRuleId::FromOrTo), list_pr.GetChild(2)}, 2); - auto &insert_column_list_opt = list_pr.GetChild(1).Cast(); - if (insert_column_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InsertColumnList), insert_column_list_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto base_table_name = process.TakeResult>(0); @@ -7514,61 +10667,18 @@ arena_ptr PEGTransformerFactory::FinalizeCopyTableTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFromOrToTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeFromOrToTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCopyFromTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyFromTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCopyFrom(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCopyToTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyToTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCopyTo(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCopySelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto ©_options_opt = list_pr.GetChild(3).Cast(); - if (copy_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CopyOptions), copy_options_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::CopyFileName), list_pr.GetChild(2)}, 1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopySelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto select_statement_internal = process.TakeResult>(0); @@ -7582,52 +10692,6 @@ PEGTransformerFactory::FinalizeCopySelectTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyFileNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyFileNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCopyFileNameExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyFileNameExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCopyFileNameStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyFileNameStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7637,11 +10701,6 @@ PEGTransformerFactory::FinalizeCopyFileNameStringLiteralTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyFileNameIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyFileNameIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7651,13 +10710,6 @@ PEGTransformerFactory::FinalizeCopyFileNameIdentifierTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyFileNameIdentifierColIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IdentifierColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyFileNameIdentifierColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7666,20 +10718,6 @@ PEGTransformerFactory::FinalizeCopyFileNameIdentifierColIdTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIdentifierColIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(1).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CopyFileNameSuffix), repeat_children[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeIdentifierColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7697,25 +10735,6 @@ PEGTransformerFactory::FinalizeIdentifierColIdTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCopyFileNameSuffixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyFileNameSuffixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCopyLegacyOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyLegacyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7728,13 +10747,6 @@ PEGTransformerFactory::FinalizeCopyLegacyOptionTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCopyOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::CopyOptionList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -7746,48 +10758,6 @@ PEGTransformerFactory::FinalizeCopyOptionsTrampoline(PEGTransformer &transformer return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeCopyOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeSpecializedOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SpecializedOptionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SpecializedOption), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSpecializedOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7813,13 +10783,6 @@ PEGTransformerFactory::FinalizeSpecializedOptionListTrampoline(PEGTransformer &t return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeSpecializedOptionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SpecializedOption), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSpecializedOptionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7832,107 +10795,36 @@ PEGTransformerFactory::FinalizeSpecializedOptionTailTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSpecializedOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSpecializedOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSingleOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSingleOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeBinaryOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeBinaryOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformBinaryOption(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFreezeOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFreezeOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformFreezeOption(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOidsOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOidsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformOidsOption(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCsvOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCsvOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCsvOption(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeHeaderOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeHeaderOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformHeaderOption(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNullAsOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNullAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -7944,11 +10836,6 @@ PEGTransformerFactory::FinalizeNullAsOptionTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDelimiterAsOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDelimiterAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7961,11 +10848,6 @@ PEGTransformerFactory::FinalizeDelimiterAsOptionTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuoteAsOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuoteAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7978,11 +10860,6 @@ PEGTransformerFactory::FinalizeQuoteAsOptionTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeEscapeAsOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeEscapeAsOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -7995,11 +10872,6 @@ PEGTransformerFactory::FinalizeEscapeAsOptionTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeEncodingOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeEncodingOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8009,17 +10881,6 @@ PEGTransformerFactory::FinalizeEncodingOptionTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeForceQuoteOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::StarSymbolColumnList), list_pr.GetChild(2)}, 1); - auto &force_quote_opt = list_pr.GetChild(0).Cast(); - if (force_quote_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ForceQuote), force_quote_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeForceQuoteOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8032,23 +10893,6 @@ PEGTransformerFactory::FinalizeForceQuoteOptionTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeStarSymbolColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && (choice_result.Name() == "StarSymbol")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeStarSymbolColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8059,24 +10903,12 @@ PEGTransformerFactory::FinalizeStarSymbolColumnListTrampoline(PEGTransformer &tr return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeForceQuoteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeForceQuoteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformForceQuote(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePartitionByOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PartitionByColumnList), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePartitionByOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8085,32 +10917,6 @@ PEGTransformerFactory::FinalizePartitionByOptionTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeStarPartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeStarPartitionByColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8118,13 +10924,6 @@ PEGTransformerFactory::FinalizeStarPartitionByColumnListTrampoline(PEGTransforme return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeParenthesizedPartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnList), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeParenthesizedPartitionByColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8133,13 +10932,6 @@ PEGTransformerFactory::FinalizeParenthesizedPartitionByColumnListTrampoline(PEGT return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeSinglePartitionByColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSinglePartitionByColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8148,17 +10940,6 @@ PEGTransformerFactory::FinalizeSinglePartitionByColumnListTrampoline(PEGTransfor return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeForceNullOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnList), list_pr.GetChild(3)}, 1); - auto &force_not_null_opt = list_pr.GetChild(1).Cast(); - if (force_not_null_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ForceNotNull), force_not_null_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeForceNullOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8171,30 +10952,12 @@ PEGTransformerFactory::FinalizeForceNullOptionTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeForceNotNullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeForceNotNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformForceNotNull(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCopyGenericOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CopyGenericOption), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeCopyGenericOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8209,38 +10972,6 @@ PEGTransformerFactory::FinalizeCopyGenericOptionListTrampoline(PEGTransformer &t return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeCopyGenericOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyGenericOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeOrderByCopyOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &generic_copy_option_value_opt = list_pr.GetChild(2).Cast(); - if (generic_copy_option_value_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::GenericCopyOptionValue), generic_copy_option_value_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeOrderByCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8252,17 +10983,6 @@ PEGTransformerFactory::FinalizeOrderByCopyOptionTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePartitionedByCopyOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &generic_copy_option_value_opt = list_pr.GetChild(2).Cast(); - if (generic_copy_option_value_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::GenericCopyOptionValue), generic_copy_option_value_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizePartitionedByCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8274,19 +10994,6 @@ PEGTransformerFactory::FinalizePartitionedByCopyOptionTrampoline(PEGTransformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGenericCopyOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::GenericCopyOption), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeGenericCopyOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8301,17 +11008,6 @@ PEGTransformerFactory::FinalizeGenericCopyOptionListTrampoline(PEGTransformer &t return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeGenericCopyOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &generic_copy_option_value_opt = list_pr.GetChild(1).Cast(); - if (generic_copy_option_value_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::GenericCopyOptionValue), generic_copy_option_value_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeGenericCopyOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8325,35 +11021,6 @@ PEGTransformerFactory::FinalizeGenericCopyOptionTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGenericCopyOptionValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeGenericCopyOptionValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeGenericCopyOptionOrderListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::GenericCopyOptionParenthesizedExpressionList), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeGenericCopyOptionOrderListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8363,13 +11030,6 @@ PEGTransformerFactory::FinalizeGenericCopyOptionOrderListTrampoline(PEGTransform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeGenericCopyOptionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeGenericCopyOptionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8378,14 +11038,6 @@ PEGTransformerFactory::FinalizeGenericCopyOptionExpressionTrampoline(PEGTransfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeGenericCopyOptionParenthesizedExpressionListTrampoline( - PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::OrderByExpressionList), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeGenericCopyOptionParenthesizedExpressionListTrampoline( PEGTransformer &transformer, GeneratedTransformProcess &process) { auto order_by_expression_list = process.TakeResult>(0); @@ -8394,36 +11046,6 @@ arena_ptr PEGTransformerFactory::FinalizeGenericCopyOption return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyFromDatabaseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCopyFromDatabaseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCopyFromDatabaseWithFlagTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::CopyDatabaseFlag), list_pr.GetChild(5)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(4)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyFromDatabaseWithFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8434,14 +11056,6 @@ PEGTransformerFactory::FinalizeCopyFromDatabaseWithFlagTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyFromDatabaseWithoutFlagTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(4)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyFromDatabaseWithoutFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8451,13 +11065,6 @@ PEGTransformerFactory::FinalizeCopyFromDatabaseWithoutFlagTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCopyDatabaseFlagTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaOrData), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyDatabaseFlagTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8466,83 +11073,18 @@ PEGTransformerFactory::FinalizeCopyDatabaseFlagTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSchemaOrDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSchemaOrDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCopySchemaTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopySchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCopySchema(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCopyDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCopyDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCopyData(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateIndexStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(8))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(7 + dynamic_child_count - 1); - auto &where_clause_opt = list_pr.GetChild(10).Cast(); - if (where_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WhereClause), where_clause_opt.GetResult()}, - 6 + dynamic_child_count - 1); - } - auto &with_list_opt = list_pr.GetChild(9).Cast(); - if (with_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithList), with_list_opt.GetResult()}, - 5 + dynamic_child_count - 1); - } - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::IndexElement), list_items[child_idx].get()}, 4 + child_idx); - } - auto &index_type_opt = list_pr.GetChild(7).Cast(); - if (index_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IndexType), index_type_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(6)}, 2); - auto &if_not_exists_opt = list_pr.GetChild(3).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 1); - } - auto &unique_index_opt = list_pr.GetChild(0).Cast(); - if (unique_index_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::UniqueIndex), unique_index_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateIndexStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8589,13 +11131,6 @@ PEGTransformerFactory::FinalizeCreateIndexStmtTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWithListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RelOptionOrOids), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWithListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto rel_option_or_oids = process.TakeResult>>(0); @@ -8603,39 +11138,6 @@ arena_ptr PEGTransformerFactory::FinalizeWithListTrampolin return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeRelOptionOrOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRelOptionOrOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRelOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::RelOption), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeRelOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8650,12 +11152,6 @@ PEGTransformerFactory::FinalizeRelOptionListTrampoline(PEGTransformer &transform return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::WithOrWithoutOids), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto with_or_without_oids = process.TakeResult(0); @@ -8663,64 +11159,18 @@ arena_ptr PEGTransformerFactory::FinalizeOidsTrampoline(PE return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeWithOrWithoutOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeWithOrWithoutOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeWithOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWithOids(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWithoutOidsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithoutOidsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWithoutOids(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIndexElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &nulls_first_or_last_opt = list_pr.GetChild(2).Cast(); - if (nulls_first_or_last_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::NullsFirstOrLast), nulls_first_or_last_opt.GetResult()}, 2); - } - auto &desc_or_asc_opt = list_pr.GetChild(1).Cast(); - if (desc_or_asc_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DescOrAsc), desc_or_asc_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIndexElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -8736,22 +11186,12 @@ PEGTransformerFactory::FinalizeIndexElementTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUniqueIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeUniqueIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformUniqueIndex(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIndexTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIndexTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -8760,18 +11200,6 @@ arena_ptr PEGTransformerFactory::FinalizeIndexTypeTrampoli return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRelOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &rel_option_argument_opt_opt = list_pr.GetChild(1).Cast(); - if (rel_option_argument_opt_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::RelOptionArgumentOpt), rel_option_argument_opt_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::RelOptionName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRelOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto rel_option_name = process.TakeResult(0); @@ -8783,34 +11211,6 @@ arena_ptr PEGTransformerFactory::FinalizeRelOptionTrampoli return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeRelOptionNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process && - (choice_result.Name() == "DottedColLabel" || choice_result.Name() == "StringLiteral")) { - return; - } - if (!has_transform_process && - (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR || - choice_result.type == ParseResultType::CHOICE || choice_result.type == ParseResultType::LIST)) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRelOptionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8836,30 +11236,9 @@ PEGTransformerFactory::FinalizeRelOptionNameTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDottedColLabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::DotColLabel), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDottedColLabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +arena_ptr +PEGTransformerFactory::FinalizeDottedColLabelTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); idx_t dynamic_child_count = 0; auto &dynamic_repeat_opt = list_pr.GetChild(1).Cast(); @@ -8882,13 +11261,6 @@ PEGTransformerFactory::FinalizeDottedColLabelTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRelOptionArgumentOptTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::DefArg), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRelOptionArgumentOptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8897,33 +11269,6 @@ PEGTransformerFactory::FinalizeRelOptionArgumentOptTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDefArgTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeDefArgTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeDefArgNullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::NullLiteral), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDefArgNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto null_literal = process.TakeResult(0); @@ -8931,11 +11276,6 @@ PEGTransformerFactory::FinalizeDefArgNullTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDefArgKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDefArgKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8945,11 +11285,6 @@ PEGTransformerFactory::FinalizeDefArgKeywordTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDefArgStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDefArgStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -8959,36 +11294,12 @@ PEGTransformerFactory::FinalizeDefArgStringLiteralTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNoneLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNoneLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNoneLiteral(transformer); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateMacroStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(3)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(4 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::MacroDefinition), list_items[child_idx].get()}, - 3 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 2); - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::MacroOrFunction), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCreateMacroStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9010,56 +11321,12 @@ PEGTransformerFactory::FinalizeCreateMacroStmtTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeReturnsTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Type), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeReturnsTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeMacroOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMacroOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeMacroKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMacroKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformMacroKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFunctionKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFunctionKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9067,21 +11334,6 @@ PEGTransformerFactory::FinalizeFunctionKeywordTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMacroDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::MacroDefinitionBody), list_pr.GetChild(3)}, 2); - auto &returns_type_opt = list_pr.GetChild(1).Cast(); - if (returns_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReturnsType), returns_type_opt.GetResult()}, 1); - } - auto ¯o_parameters_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); - if (macro_parameters_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::MacroParameters), macro_parameters_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9099,39 +11351,6 @@ PEGTransformerFactory::FinalizeMacroDefinitionTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMacroDefinitionBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMacroDefinitionBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeMacroParametersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::MacroParameter), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeMacroParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9146,38 +11365,6 @@ PEGTransformerFactory::FinalizeMacroParametersTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMacroParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMacroParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeSimpleParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &type_opt = list_pr.GetChild(1).Cast(); - if (type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Type), type_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TypeFuncName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSimpleParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9190,13 +11377,6 @@ PEGTransformerFactory::FinalizeSimpleParameterTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeScalarMacroDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeScalarMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9205,13 +11385,6 @@ PEGTransformerFactory::FinalizeScalarMacroDefinitionTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableMacroDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableMacroDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9220,21 +11393,6 @@ PEGTransformerFactory::FinalizeTableMacroDefinitionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateSchemaStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &with_option_list_opt = list_pr.GetChild(3).Cast(); - if (with_option_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithOptionList), with_option_list_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 1); - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateSchemaStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9251,13 +11409,6 @@ PEGTransformerFactory::FinalizeCreateSchemaStmtTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWithOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RelOptionList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWithOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9266,26 +11417,6 @@ PEGTransformerFactory::FinalizeWithOptionListTrampoline(PEGTransformer &transfor return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateSecretStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - process.PushChild({transformer.GetRule(PEGRuleId::GenericCopyOptionList), list_pr.GetChild(4)}, 3); - auto &secret_storage_specifier_opt = list_pr.GetChild(3).Cast(); - if (secret_storage_specifier_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::SecretStorageSpecifier), secret_storage_specifier_opt.GetResult()}, 2); - } - auto &secret_name_opt = list_pr.GetChild(2).Cast(); - if (secret_name_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SecretName), secret_name_opt.GetResult()}, 1); - } - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateSecretStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9307,11 +11438,6 @@ PEGTransformerFactory::FinalizeCreateSecretStmtTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSecretStorageSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSecretStorageSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9321,13 +11447,6 @@ PEGTransformerFactory::FinalizeSecretStorageSpecifierTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSecretNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSecretNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id = process.TakeResult(0); @@ -9335,31 +11454,6 @@ PEGTransformerFactory::FinalizeSecretNameTrampoline(PEGTransformer &transformer, return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateSequenceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(3).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SequenceOption), repeat_children[child_idx].get()}, - 2 + child_idx); - } - } else { - process.ReserveChildSlots(3 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 1); - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateSequenceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9389,76 +11483,18 @@ PEGTransformerFactory::FinalizeCreateSequenceStmtTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSequenceOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSequenceOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSeqSetCycleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSeqSetCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSeqCycleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSeqCycle(transformer); return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqNoCycleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqNoCycleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSeqNoCycle(transformer); return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqSetIncrementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqSetIncrementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9471,14 +11507,6 @@ PEGTransformerFactory::FinalizeSeqSetIncrementTrampoline(PEGTransformer &transfo return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqSetMinMaxTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::SeqMinOrMax), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqSetMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto seq_min_or_max = process.TakeResult(0); @@ -9487,13 +11515,6 @@ PEGTransformerFactory::FinalizeSeqSetMinMaxTrampoline(PEGTransformer &transforme return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqNoMinMaxTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SeqMinOrMax), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqNoMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto seq_min_or_max = process.TakeResult(0); @@ -9501,13 +11522,6 @@ PEGTransformerFactory::FinalizeSeqNoMinMaxTrampoline(PEGTransformer &transformer return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqStartWithTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqStartWithTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -9519,13 +11533,6 @@ PEGTransformerFactory::FinalizeSeqStartWithTrampoline(PEGTransformer &transforme return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqOwnedByTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqOwnedByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto qualified_name = process.TakeResult(0); @@ -9533,24 +11540,6 @@ PEGTransformerFactory::FinalizeSeqOwnedByTrampoline(PEGTransformer &transformer, return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSeqMinOrMaxTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSeqMinOrMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -9574,43 +11563,18 @@ PEGTransformerFactory::FinalizeSeqMinOrMaxTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMinValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMinValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformMinValue(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMaxValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMaxValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformMaxValue(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::CreateStatementVariation), list_pr.GetChild(3)}, 2); - auto &temporary_opt = list_pr.GetChild(2).Cast(); - if (temporary_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Temporary), temporary_opt.GetResult()}, 1); - } - auto &or_replace_opt = list_pr.GetChild(1).Cast(); - if (or_replace_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrReplace), or_replace_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9627,74 +11591,18 @@ PEGTransformerFactory::FinalizeCreateStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateStatementVariationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCreateStatementVariationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeOrReplaceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOrReplaceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformOrReplace(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTemporaryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeTemporaryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializePersistentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformPersistent(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTempPersistentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTempPersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9702,11 +11610,6 @@ PEGTransformerFactory::FinalizeTempPersistentTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTemporaryPersistentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTemporaryPersistentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9714,22 +11617,6 @@ PEGTransformerFactory::FinalizeTemporaryPersistentTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateTableStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &commit_action_opt = list_pr.GetChild(4).Cast(); - if (commit_action_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CommitAction), commit_action_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::CreateTableDefinition), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 1); - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateTableStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9748,51 +11635,6 @@ PEGTransformerFactory::FinalizeCreateTableStmtTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateTableDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCreateTableDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeCreateTableAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &with_data_opt = list_pr.GetChild(5).Cast(); - if (with_data_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithData), with_data_opt.GetResult()}, 4); - } - process.PushChild({transformer.GetRule(PEGRuleId::Statement), list_pr.GetChild(4)}, 3); - auto &with_list_opt = list_pr.GetChild(2).Cast(); - if (with_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithList), with_list_opt.GetResult()}, 2); - } - auto &partition_sorted_options_opt = list_pr.GetChild(1).Cast(); - if (partition_sorted_options_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::PartitionSortedOptions), partition_sorted_options_opt.GetResult()}, 1); - } - auto &identifier_list_opt = list_pr.GetChild(0).Cast(); - if (identifier_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IdentifierList), identifier_list_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9818,38 +11660,6 @@ PEGTransformerFactory::FinalizeCreateTableAsTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePartitionSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePartitionSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializePartitionOptSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &sorted_options_opt = list_pr.GetChild(1).Cast(); - if (sorted_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SortedOptions), sorted_options_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::PartitionOptions), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePartitionOptSortedOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9863,17 +11673,6 @@ PEGTransformerFactory::FinalizePartitionOptSortedOptionsTrampoline(PEGTransforme return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSortedOptPartitionOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &partition_options_opt = list_pr.GetChild(1).Cast(); - if (partition_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::PartitionOptions), partition_options_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SortedOptions), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSortedOptPartitionOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9887,18 +11686,6 @@ PEGTransformerFactory::FinalizeSortedOptPartitionOptionsTrampoline(PEGTransforme return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePartitionOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(2))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizePartitionOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9913,18 +11700,6 @@ PEGTransformerFactory::FinalizePartitionOptionsTrampoline(PEGTransformer &transf return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSortedOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(2))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeSortedOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -9939,53 +11714,18 @@ PEGTransformerFactory::FinalizeSortedOptionsTrampoline(PEGTransformer &transform return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeWithDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeWithDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeWithDataOnlyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithDataOnlyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWithDataOnly(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWithNoDataTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithNoDataTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformWithNoData(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIdentifierListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIdentifierListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10000,26 +11740,6 @@ PEGTransformerFactory::FinalizeIdentifierListTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCreateColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &with_list_opt = list_pr.GetChild(2).Cast(); - if (with_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithList), with_list_opt.GetResult()}, 2); - } - auto &partition_sorted_options_opt = list_pr.GetChild(1).Cast(); - if (partition_sorted_options_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::PartitionSortedOptions), partition_sorted_options_opt.GetResult()}, 1); - } - auto &create_table_column_list_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); - if (create_table_column_list_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::CreateTableColumnList), create_table_column_list_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10040,46 +11760,12 @@ PEGTransformerFactory::FinalizeCreateColumnListTrampoline(PEGTransformer &transf return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIfNotExistsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIfNotExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformIfNotExists(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSchemaReservedIdentifierOrStringLiteralTrampoline( - PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedIdentifierOrStringLiteral), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10090,24 +11776,6 @@ PEGTransformerFactory::FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCatalogReservedSchemaIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(1).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedIdentifierOrStringLiteral), list_pr.GetChild(2)}, - 2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ReservedSchemaQualification), repeat_children[child_idx].get()}, - 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10127,26 +11795,6 @@ PEGTransformerFactory::FinalizeCatalogReservedSchemaIdentifierTrampoline(PEGTran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && - (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR || - choice_result.type == ParseResultType::CHOICE || choice_result.type == ParseResultType::LIST)) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10172,27 +11820,6 @@ PEGTransformerFactory::FinalizeIdentifierOrStringLiteralTrampoline(PEGTransforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process && (choice_result.Name() == "StringLiteral")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReservedIdentifierOrStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10215,11 +11842,6 @@ PEGTransformerFactory::FinalizeReservedIdentifierOrStringLiteralTrampoline(PEGTr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCatalogQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10229,11 +11851,6 @@ PEGTransformerFactory::FinalizeCatalogQualificationTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSchemaQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10243,11 +11860,6 @@ PEGTransformerFactory::FinalizeSchemaQualificationTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReservedSchemaQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeReservedSchemaQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10257,11 +11869,6 @@ PEGTransformerFactory::FinalizeReservedSchemaQualificationTrampoline(PEGTransfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTableQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTableQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10271,11 +11878,6 @@ PEGTransformerFactory::FinalizeTableQualificationTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReservedTableQualificationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeReservedTableQualificationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10285,19 +11887,6 @@ PEGTransformerFactory::FinalizeReservedTableQualificationTrampoline(PEGTransform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateTableColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CreateTableColumnElement), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateTableColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10312,49 +11901,14 @@ PEGTransformerFactory::FinalizeCreateTableColumnListTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCreateTableColumnElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr -PEGTransformerFactory::FinalizeCreateTableColumnElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); +PEGTransformerFactory::FinalizeCreateTableColumnDefinitionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto column_definition = process.TakeResult(0); + auto result = TransformCreateTableColumnDefinition(transformer, std::move(column_definition)); return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCreateTableColumnDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnDefinition), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCreateTableColumnDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto column_definition = process.TakeResult(0); - auto result = TransformCreateTableColumnDefinition(transformer, std::move(column_definition)); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeCreateTableConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TopLevelConstraint), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCreateTableConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10363,34 +11917,6 @@ PEGTransformerFactory::FinalizeCreateTableConstraintTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeColumnDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(3).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColumnConstraint), repeat_children[child_idx].get()}, - 2 + child_idx); - } - } else { - process.ReserveChildSlots(3 - 1); - } - auto &generated_column_opt = list_pr.GetChild(2).Cast(); - if (generated_column_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::GeneratedColumn), generated_column_opt.GetResult()}, 1); - } - auto &type_opt = list_pr.GetChild(1).Cast(); - if (type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Type), type_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeColumnDefinitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10425,34 +11951,6 @@ PEGTransformerFactory::FinalizeColumnDefinitionTrampoline(PEGTransformer &transf return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeNameableColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnConstraintElement), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNameableColumnConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10465,41 +11963,6 @@ PEGTransformerFactory::FinalizeNameableColumnConstraintTrampoline(PEGTransformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeColumnConstraintElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeColumnConstraintElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeNotNullConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNotNullConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10508,11 +11971,6 @@ PEGTransformerFactory::FinalizeNotNullConstraintTrampoline(PEGTransformer &trans return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeNullConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNullConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10520,11 +11978,6 @@ PEGTransformerFactory::FinalizeNullConstraintTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNotNullColumnConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotNullColumnConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10532,16 +11985,6 @@ PEGTransformerFactory::FinalizeNotNullColumnConstraintTrampoline(PEGTransformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUniqueConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &constraint_timing_opt = list_pr.GetChild(1).Cast(); - if (constraint_timing_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ConstraintTiming), constraint_timing_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeUniqueConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10553,16 +11996,6 @@ PEGTransformerFactory::FinalizeUniqueConstraintTrampoline(PEGTransformer &transf return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePrimaryKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &constraint_timing_opt = list_pr.GetChild(2).Cast(); - if (constraint_timing_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ConstraintTiming), constraint_timing_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizePrimaryKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10574,32 +12007,6 @@ PEGTransformerFactory::FinalizePrimaryKeyConstraintTrampoline(PEGTransformer &tr return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeConstraintTimingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeConstraintTimingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeImmediateConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeImmediateConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10607,11 +12014,6 @@ PEGTransformerFactory::FinalizeImmediateConstraintTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeferredConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDeferredConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10619,13 +12021,6 @@ PEGTransformerFactory::FinalizeDeferredConstraintTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDefaultValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnDefaultExpr), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDefaultValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto column_default_expr = process.TakeResult>(0); @@ -10633,13 +12028,6 @@ PEGTransformerFactory::FinalizeDefaultValueTrampoline(PEGTransformer &transforme return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCheckConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCheckConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10648,22 +12036,6 @@ PEGTransformerFactory::FinalizeCheckConstraintTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeForeignKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &key_actions_opt = list_pr.GetChild(3).Cast(); - if (key_actions_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::KeyActions), key_actions_opt.GetResult()}, 2); - } - auto &column_list_opt = list_pr.GetChild(2).Cast(); - if (column_list_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::ColumnList), ExtractResultFromParens(column_list_opt.GetResult())}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeForeignKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10680,13 +12052,6 @@ PEGTransformerFactory::FinalizeForeignKeyConstraintTrampoline(PEGTransformer &tr return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeColumnCollationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::DottedIdentifier), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColumnCollationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10695,13 +12060,6 @@ PEGTransformerFactory::FinalizeColumnCollationTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeColumnCompressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColumnCompressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10710,37 +12068,6 @@ PEGTransformerFactory::FinalizeColumnCompressionTrampoline(PEGTransformer &trans return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeKeyActionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeKeyActionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeUpdateFirstKeyActionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &delete_action_opt = list_pr.GetChild(1).Cast(); - if (delete_action_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DeleteAction), delete_action_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::UpdateAction), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateFirstKeyActionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10753,17 +12080,6 @@ PEGTransformerFactory::FinalizeUpdateFirstKeyActionsTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeleteFirstKeyActionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &update_action_opt = list_pr.GetChild(1).Cast(); - if (update_action_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::UpdateAction), update_action_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::DeleteAction), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDeleteFirstKeyActionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10776,13 +12092,6 @@ PEGTransformerFactory::FinalizeDeleteFirstKeyActionsTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUpdateActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::KeyAction), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto key_action = process.TakeResult(0); @@ -10790,13 +12099,6 @@ PEGTransformerFactory::FinalizeUpdateActionTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeleteActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::KeyAction), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDeleteActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto key_action = process.TakeResult(0); @@ -10804,24 +12106,6 @@ PEGTransformerFactory::FinalizeDeleteActionTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -10845,22 +12129,12 @@ arena_ptr PEGTransformerFactory::FinalizeKeyActionTrampoli return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNoKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNoKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNoKeyAction(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRestrictKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRestrictKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10868,11 +12142,6 @@ PEGTransformerFactory::FinalizeRestrictKeyActionTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCascadeKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCascadeKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10880,11 +12149,6 @@ PEGTransformerFactory::FinalizeCascadeKeyActionTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSetNullKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSetNullKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10892,11 +12156,6 @@ PEGTransformerFactory::FinalizeSetNullKeyActionTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSetDefaultKeyActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSetDefaultKeyActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10904,13 +12163,6 @@ PEGTransformerFactory::FinalizeSetDefaultKeyActionTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTopLevelConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TopLevelConstraintList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTopLevelConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10923,34 +12175,6 @@ PEGTransformerFactory::FinalizeTopLevelConstraintTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTopLevelConstraintListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTopLevelConstraintListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeTopCheckConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::CheckConstraint), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTopCheckConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10959,17 +12183,6 @@ PEGTransformerFactory::FinalizeTopCheckConstraintTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTopPrimaryKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &constraint_timing_opt = list_pr.GetChild(3).Cast(); - if (constraint_timing_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ConstraintTiming), constraint_timing_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColumnIdList), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTopPrimaryKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -10982,17 +12195,6 @@ PEGTransformerFactory::FinalizeTopPrimaryKeyConstraintTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTopUniqueConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &constraint_timing_opt = list_pr.GetChild(2).Cast(); - if (constraint_timing_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ConstraintTiming), constraint_timing_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColumnIdList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTopUniqueConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11005,14 +12207,6 @@ PEGTransformerFactory::FinalizeTopUniqueConstraintTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTopForeignKeyConstraintTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ForeignKeyConstraint), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnIdList), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTopForeignKeyConstraintTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11022,18 +12216,6 @@ PEGTransformerFactory::FinalizeTopForeignKeyConstraintTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColumnIdListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeColumnIdListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -11047,26 +12229,6 @@ PEGTransformerFactory::FinalizeColumnIdListTrampoline(PEGTransformer &transforme return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeDottedIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::DotColLabel), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeDottedIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11092,13 +12254,6 @@ PEGTransformerFactory::FinalizeDottedIdentifierTrampoline(PEGTransformer &transf return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeDotColLabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDotColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_label = process.TakeResult(0); @@ -11106,39 +12261,12 @@ PEGTransformerFactory::FinalizeDotColLabelTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = process.parse_result.Cast().identifier.GetIdentifierName(); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process && - (choice_result.Name() == "UnreservedKeyword" || choice_result.Name() == "ColumnNameKeyword" || - choice_result.Name() == "Identifier")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColIdTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { Identifier result; @@ -11160,24 +12288,6 @@ arena_ptr PEGTransformerFactory::FinalizeColIdTrampoline(P return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColIdOrStringTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColIdOrStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11200,28 +12310,6 @@ PEGTransformerFactory::FinalizeColIdOrStringTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTypeFuncNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process && (choice_result.Name() == "UnreservedKeyword" || - choice_result.Name() == "TypeFuncKeyword" || choice_result.Name() == "Identifier")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTypeFuncNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { Identifier result; @@ -11243,28 +12331,6 @@ PEGTransformerFactory::FinalizeTypeFuncNameTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTypeFuncKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process && - (choice_result.Name() == "TypeNameKeyword" || choice_result.Name() == "FuncNameKeyword")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTypeFuncKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11289,30 +12355,6 @@ PEGTransformerFactory::FinalizeTypeFuncKeywordTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColLabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process && - (choice_result.Name() == "ReservedKeyword" || choice_result.Name() == "UnreservedKeyword" || - choice_result.Name() == "ColumnNameKeyword" || choice_result.Name() == "FuncNameKeyword" || - choice_result.Name() == "TypeNameKeyword")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -11336,24 +12378,6 @@ arena_ptr PEGTransformerFactory::FinalizeColLabelTrampolin return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColLabelOrStringTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColLabelOrStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11376,13 +12400,6 @@ PEGTransformerFactory::FinalizeColLabelOrStringTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColLabelIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColLabelIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11391,11 +12408,6 @@ PEGTransformerFactory::FinalizeColLabelIdentifierTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeStringLiteralIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeStringLiteralIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11405,22 +12417,6 @@ PEGTransformerFactory::FinalizeStringLiteralIdentifierTrampoline(PEGTransformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGeneratedColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &generated_column_type_opt = list_pr.GetChild(3).Cast(); - if (generated_column_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::GeneratedColumnType), generated_column_type_opt.GetResult()}, - 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(list_pr.GetChild(2))}, 1); - auto &generated_opt = list_pr.GetChild(0).Cast(); - if (generated_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Generated), generated_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11437,31 +12433,6 @@ PEGTransformerFactory::FinalizeGeneratedColumnTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeGeneratedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeGeneratedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeGeneratedAlwaysTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGeneratedAlwaysTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11469,11 +12440,6 @@ PEGTransformerFactory::FinalizeGeneratedAlwaysTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGeneratedByDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGeneratedByDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11481,34 +12447,6 @@ PEGTransformerFactory::FinalizeGeneratedByDefaultTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGeneratedColumnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeGeneratedColumnTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCommitActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PreserveOrDelete), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCommitActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto preserve_or_delete = process.TakeResult(0); @@ -11516,54 +12454,18 @@ PEGTransformerFactory::FinalizeCommitActionTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePreserveOrDeleteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePreserveOrDeleteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializePreserveRowsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePreserveRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformPreserveRows(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeleteRowsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDeleteRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformDeleteRows(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVirtualGeneratedColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeVirtualGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11571,11 +12473,6 @@ PEGTransformerFactory::FinalizeVirtualGeneratedColumnTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeStoredGeneratedColumnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeStoredGeneratedColumnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11583,29 +12480,6 @@ PEGTransformerFactory::FinalizeStoredGeneratedColumnTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateTriggerStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(8); - process.PushChild({transformer.GetRule(PEGRuleId::TriggerBody), list_pr.GetChild(9)}, 7); - auto &for_each_clause_opt = list_pr.GetChild(8).Cast(); - if (for_each_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ForEachClause), for_each_clause_opt.GetResult()}, 6); - } - auto &referencing_clause_opt = list_pr.GetChild(7).Cast(); - if (referencing_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReferencingClause), referencing_clause_opt.GetResult()}, 5); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(6)}, 4); - process.PushChild({transformer.GetRule(PEGRuleId::TriggerEvent), list_pr.GetChild(4)}, 3); - process.PushChild({transformer.GetRule(PEGRuleId::TriggerTiming), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::TriggerName), list_pr.GetChild(2)}, 1); - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateTriggerStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11632,31 +12506,6 @@ PEGTransformerFactory::FinalizeCreateTriggerStmtTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTriggerBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTriggerBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeTriggerNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -11665,17 +12514,6 @@ PEGTransformerFactory::FinalizeTriggerNameTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReferencingClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &referencing_item_1_opt = list_pr.GetChild(2).Cast(); - if (referencing_item_1_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReferencingItem), referencing_item_1_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ReferencingItem), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReferencingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11688,34 +12526,6 @@ PEGTransformerFactory::FinalizeReferencingClauseTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReferencingItemTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeReferencingItemTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeReferencingNewTableAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(3)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReferencingNewTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11724,13 +12534,6 @@ PEGTransformerFactory::FinalizeReferencingNewTableAsTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReferencingOldTableAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(3)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReferencingOldTableAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11739,55 +12542,19 @@ PEGTransformerFactory::FinalizeReferencingOldTableAsTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerTimingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr -PEGTransformerFactory::FinalizeTriggerTimingTrampoline(PEGTransformer &transformer, +PEGTransformerFactory::FinalizeTriggerBeforeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); + auto result = TransformTriggerBefore(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerBeforeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTriggerBeforeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = TransformTriggerBefore(transformer); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeTriggerAfterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerAfterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformTriggerAfter(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerInsteadOfTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerInsteadOfTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11795,31 +12562,6 @@ PEGTransformerFactory::FinalizeTriggerInsteadOfTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerEventTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTriggerEventTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeTriggerEventInsertTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerEventInsertTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11827,11 +12569,6 @@ PEGTransformerFactory::FinalizeTriggerEventInsertTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerEventDeleteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerEventDeleteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11839,11 +12576,6 @@ PEGTransformerFactory::FinalizeTriggerEventDeleteTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerEventUpdateTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerEventUpdateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11851,13 +12583,6 @@ PEGTransformerFactory::FinalizeTriggerEventUpdateTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerEventUpdateOfTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TriggerColumnList), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTriggerEventUpdateOfTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11866,18 +12591,6 @@ PEGTransformerFactory::FinalizeTriggerEventUpdateOfTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTriggerColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeTriggerColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11892,43 +12605,12 @@ PEGTransformerFactory::FinalizeTriggerColumnListTrampoline(PEGTransformer &trans return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeForEachClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeForEachClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeForEachRowTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeForEachRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformForEachRow(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeForEachStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeForEachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11936,18 +12618,6 @@ PEGTransformerFactory::FinalizeForEachStatementTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateTypeStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::CreateType), list_pr.GetChild(4)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(2)}, 1); - auto &if_not_exists_opt = list_pr.GetChild(1).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateTypeStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11961,33 +12631,6 @@ PEGTransformerFactory::FinalizeCreateTypeStmtTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCreateTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCreateTypeFromTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Type), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCreateTypeFromTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -11996,14 +12639,6 @@ PEGTransformerFactory::FinalizeCreateTypeFromTypeTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeEnumSelectTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeEnumSelectTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12012,26 +12647,6 @@ PEGTransformerFactory::FinalizeEnumSelectTypeTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeEnumStringLiteralListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(2).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ArrayBounds), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeEnumStringLiteralListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12068,34 +12683,6 @@ PEGTransformerFactory::FinalizeEnumStringLiteralListTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateViewStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(7); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(8)}, 6); - auto &with_list_opt = list_pr.GetChild(6).Cast(); - if (with_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithList), with_list_opt.GetResult()}, 5); - } - auto &insert_column_list_opt = list_pr.GetChild(5).Cast(); - if (insert_column_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InsertColumnList), insert_column_list_opt.GetResult()}, 4); - } - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(4)}, 3); - auto &if_not_exists_opt = list_pr.GetChild(3).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 2); - } - auto &create_recursive_opt = list_pr.GetChild(1).Cast(); - if (create_recursive_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CreateRecursive), create_recursive_opt.GetResult()}, 1); - } - auto &create_secure_opt = list_pr.GetChild(0).Cast(); - if (create_secure_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CreateSecure), create_secure_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateViewStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12127,11 +12714,6 @@ PEGTransformerFactory::FinalizeCreateViewStmtTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCreateRecursiveTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCreateRecursiveTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12139,28 +12721,12 @@ PEGTransformerFactory::FinalizeCreateRecursiveTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCreateSecureTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCreateSecureTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCreateSecure(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeallocateStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(2)}, 1); - auto &deallocate_prepare_opt = list_pr.GetChild(1).Cast(); - if (deallocate_prepare_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DeallocatePrepare), deallocate_prepare_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDeallocateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12173,11 +12739,6 @@ PEGTransformerFactory::FinalizeDeallocateStatementTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDeallocatePrepareTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDeallocatePrepareTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12185,29 +12746,6 @@ PEGTransformerFactory::FinalizeDeallocatePrepareTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeleteStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &returning_clause_opt = list_pr.GetChild(6).Cast(); - if (returning_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReturningClause), returning_clause_opt.GetResult()}, 4); - } - auto &where_clause_opt = list_pr.GetChild(5).Cast(); - if (where_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WhereClause), where_clause_opt.GetResult()}, 3); - } - auto &delete_using_clause_opt = list_pr.GetChild(4).Cast(); - if (delete_using_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DeleteUsingClause), delete_using_clause_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::TargetOptAlias), list_pr.GetChild(3)}, 1); - auto &with_clause_opt = list_pr.GetChild(0).Cast(); - if (with_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithClause), with_clause_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDeleteStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12234,17 +12772,6 @@ PEGTransformerFactory::FinalizeDeleteStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTruncateStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &truncate_options_opt = list_pr.GetChild(3).Cast(); - if (truncate_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TruncateOptions), truncate_options_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTruncateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12261,39 +12788,6 @@ PEGTransformerFactory::FinalizeTruncateStatementTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTruncateOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTruncateOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeTruncateAliasOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &truncate_drop_behavior_opt = list_pr.GetChild(1).Cast(); - if (truncate_drop_behavior_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::TruncateDropBehavior), truncate_drop_behavior_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TargetAlias), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTruncateAliasOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12306,13 +12800,6 @@ PEGTransformerFactory::FinalizeTruncateAliasOptionsTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTruncateDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::DropBehavior), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTruncateDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12321,17 +12808,6 @@ PEGTransformerFactory::FinalizeTruncateDropBehaviorTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTargetOptAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &target_alias_opt = list_pr.GetChild(1).Cast(); - if (target_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TargetAlias), target_alias_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTargetOptAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12344,13 +12820,6 @@ PEGTransformerFactory::FinalizeTargetOptAliasTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTargetAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTargetAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -12362,18 +12831,6 @@ PEGTransformerFactory::FinalizeTargetAliasTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDeleteUsingClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeDeleteUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12388,20 +12845,6 @@ PEGTransformerFactory::FinalizeDeleteUsingClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeDescribeStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDescribeStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12410,12 +12853,20 @@ PEGTransformerFactory::FinalizeDescribeStatementTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeShowDeprecatedSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +arena_ptr +PEGTransformerFactory::FinalizeShowExternalResourcesTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ShowRule), list_pr.GetChild(0)}, 0); + auto show_rule = process.TakeResult(0); + bool has_result {}; + auto &has_result_opt = list_pr.GetChild(1).Cast(); + has_result = has_result_opt.HasResult(); + optional show_external_resources_type {}; + if (process.child_results[1]) { + show_external_resources_type = process.TakeResult(1); + } + auto result = TransformShowExternalResources(transformer, show_rule, has_result, show_external_resources_type); + return transformer.MakeResult>(std::move(result)); } arena_ptr @@ -12427,14 +12878,6 @@ PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDescribeSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::DescribeOrSummarize), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDescribeSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12444,13 +12887,6 @@ PEGTransformerFactory::FinalizeDescribeSelectTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeShowAllTablesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ShowOrDescribe), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeShowAllTablesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12463,14 +12899,6 @@ PEGTransformerFactory::FinalizeShowAllTablesTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeShowTablesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ShowOrDescribe), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeShowTablesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto show_or_describe = process.TakeResult(0); @@ -12479,17 +12907,6 @@ PEGTransformerFactory::FinalizeShowTablesTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeShowByNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &show_target_opt = list_pr.GetChild(1).Cast(); - if (show_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ShowTarget), show_target_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ShowRule), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeShowByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto show_rule = process.TakeResult(0); @@ -12501,17 +12918,6 @@ PEGTransformerFactory::FinalizeShowByNameTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDescribeByNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &describe_target_opt = list_pr.GetChild(1).Cast(); - if (describe_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DescribeTarget), describe_target_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::DescribeOrSummarize), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDescribeByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12524,58 +12930,13 @@ PEGTransformerFactory::FinalizeDescribeByNameTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDescribeOrSummarizeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); +arena_ptr +PEGTransformerFactory::FinalizeShowTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { + DescribeTarget result {}; + if (process.child_results[0]) { + result = process.TakeResult(0); } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDescribeOrSummarizeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeShowTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && (choice_result.Name() == "ShowSpecialForm")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeShowTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - DescribeTarget result {}; - if (process.child_results[0]) { - result = process.TakeResult(0); - } - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeShowDeprecatedQualifiedTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTableName), list_pr.GetChild(0)}, 0); + return transformer.MakeResult(std::move(result)); } arena_ptr @@ -12586,11 +12947,6 @@ PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline(PEGTra return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeShowSettingNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeShowSettingNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12600,34 +12956,6 @@ PEGTransformerFactory::FinalizeShowSettingNameTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDescribeTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDescribeTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeDescribeBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12636,11 +12964,6 @@ PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDescribeStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12650,13 +12973,6 @@ PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSummarizeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SummarizeRule), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSummarizeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto summarize_rule = process.TakeResult(0); @@ -12664,11 +12980,6 @@ arena_ptr PEGTransformerFactory::FinalizeSummarizeTrampoli return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSummarizeRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSummarizeRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12676,63 +12987,12 @@ PEGTransformerFactory::FinalizeSummarizeRuleTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeShowOrDescribeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeShowOrDescribeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeShowRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeShowRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformShowRule(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDescribeRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDescribeRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeDescribeLongRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDescribeLongRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12740,27 +13000,12 @@ PEGTransformerFactory::FinalizeDescribeLongRuleTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDescRuleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDescRuleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformDescRule(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDetachStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &if_exists_opt = list_pr.GetChild(2).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDetachStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12777,17 +13022,6 @@ PEGTransformerFactory::FinalizeDetachStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &drop_behavior_opt = list_pr.GetChild(2).Cast(); - if (drop_behavior_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DropBehavior), drop_behavior_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::DropEntries), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDropStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12800,38 +13034,6 @@ PEGTransformerFactory::FinalizeDropStatementTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDropEntriesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeDropTriggerTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(4)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::TriggerName), list_pr.GetChild(2)}, 1); - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropTriggerTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional if_exists {}; @@ -12844,23 +13046,6 @@ PEGTransformerFactory::FinalizeDropTriggerTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_items[child_idx].get()}, 2 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableOrView), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDropTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -12879,24 +13064,6 @@ arena_ptr PEGTransformerFactory::FinalizeDropTableTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTableFunction), list_items[child_idx].get()}, - 2 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::CommentMacroTable), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDropTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -12916,24 +13083,6 @@ PEGTransformerFactory::FinalizeDropTableFunctionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::FunctionIdentifier), list_items[child_idx].get()}, - 2 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::FunctionTypeMacro), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDropFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -12952,22 +13101,6 @@ PEGTransformerFactory::FinalizeDropFunctionTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropSchemaTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedName), list_items[child_idx].get()}, 1 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -12985,23 +13118,6 @@ PEGTransformerFactory::FinalizeDropSchemaTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedIndexName), list_items[child_idx].get()}, - 1 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -13019,32 +13135,6 @@ arena_ptr PEGTransformerFactory::FinalizeDropIndexTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeQualifiedIndexNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeQualifiedIndexNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeQualifiedIndexNameStringTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQualifiedIndexNameStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13054,13 +13144,6 @@ PEGTransformerFactory::FinalizeQualifiedIndexNameStringTrampoline(PEGTransformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSchemaReservedIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13071,14 +13154,6 @@ PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCatalogReservedSchemaIndexTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedSchemaQualification), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13091,23 +13166,6 @@ PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline(PEGTransform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDropSequenceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedSequenceName), list_items[child_idx].get()}, - 1 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropSequenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -13125,22 +13183,6 @@ PEGTransformerFactory::FinalizeDropSequenceTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropCollationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CollationName), list_items[child_idx].get()}, 1 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropCollationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13159,23 +13201,6 @@ PEGTransformerFactory::FinalizeDropCollationTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTypeName), list_items[child_idx].get()}, - 1 + child_idx); - } - auto &if_exists_opt = list_pr.GetChild(1).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropTypeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -13193,25 +13218,6 @@ arena_ptr PEGTransformerFactory::FinalizeDropTypeTrampolin return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDropSecretTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &drop_secret_storage_opt = list_pr.GetChild(4).Cast(); - if (drop_secret_storage_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DropSecretStorage), drop_secret_storage_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::SecretName), list_pr.GetChild(3)}, 2); - auto &if_exists_opt = list_pr.GetChild(2).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 1); - } - auto &temporary_opt = list_pr.GetChild(0).Cast(); - if (temporary_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Temporary), temporary_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropSecretTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional temporary {}; @@ -13231,31 +13237,6 @@ PEGTransformerFactory::FinalizeDropSecretTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableOrViewTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTableOrViewTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeMaterializedViewEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMaterializedViewEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13263,42 +13244,11 @@ PEGTransformerFactory::FinalizeMaterializedViewEntryTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFunctionTypeMacroTrampoline(PEGTransformer &transformer, +arena_ptr +PEGTransformerFactory::FinalizeFunctionTypeMacroKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFunctionTypeMacroTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeFunctionTypeMacroKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFunctionTypeMacroKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = TransformFunctionTypeMacroKeyword(transformer); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeFunctionTypeFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); + auto result = TransformFunctionTypeMacroKeyword(transformer); + return transformer.MakeResult(result); } arena_ptr @@ -13308,31 +13258,6 @@ PEGTransformerFactory::FinalizeFunctionTypeFunctionTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCascadeDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCascadeDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13340,11 +13265,6 @@ PEGTransformerFactory::FinalizeCascadeDropBehaviorTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRestrictDropBehaviorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRestrictDropBehaviorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13352,22 +13272,12 @@ PEGTransformerFactory::FinalizeRestrictDropBehaviorTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIfExistsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIfExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformIfExists(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDropSecretStorageTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDropSecretStorageTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13377,18 +13287,6 @@ PEGTransformerFactory::FinalizeDropSecretStorageTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExecuteStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &table_function_arguments_opt = list_pr.GetChild(2).Cast(); - if (table_function_arguments_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::TableFunctionArguments), table_function_arguments_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExecuteStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13401,21 +13299,6 @@ PEGTransformerFactory::FinalizeExecuteStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExplainStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::ExplainableStatements), list_pr.GetChild(3)}, 2); - auto &explain_option_list_opt = list_pr.GetChild(2).Cast(); - if (explain_option_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExplainOptionList), explain_option_list_opt.GetResult()}, 1); - } - auto &analyze_keyword_opt = list_pr.GetChild(1).Cast(); - if (analyze_keyword_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AnalyzeKeyword), analyze_keyword_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeExplainStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13433,18 +13316,6 @@ PEGTransformerFactory::FinalizeExplainStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExplainOptionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ExplainOption), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeExplainOptionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13459,17 +13330,6 @@ PEGTransformerFactory::FinalizeExplainOptionListTrampoline(PEGTransformer &trans return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeExplainOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ExplainOptionName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExplainOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13482,28 +13342,6 @@ PEGTransformerFactory::FinalizeExplainOptionTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExplainOptionNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process && - (choice_result.Name() == "FuncNameKeyword" || choice_result.Name() == "TypeNameKeyword")) { - return; - } - if (!has_transform_process) { - return; - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExplainOptionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13518,13 +13356,6 @@ PEGTransformerFactory::FinalizeExplainOptionNameTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExplainSelectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13533,41 +13364,6 @@ PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExplainableStatementsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExplainableStatementsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeExportStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &export_options_opt = list_pr.GetChild(4).Cast(); - if (export_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExportOptions), export_options_opt.GetResult()}, 1); - } - auto &export_source_opt = list_pr.GetChild(2).Cast(); - if (export_source_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExportSource), export_source_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeExportStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13585,11 +13381,6 @@ PEGTransformerFactory::FinalizeExportStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExportSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExportSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -13598,32 +13389,6 @@ PEGTransformerFactory::FinalizeExportSourceTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExportOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExportOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeImportStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeImportStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13633,20 +13398,6 @@ PEGTransformerFactory::FinalizeImportStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColumnReferenceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColumnReferenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13655,24 +13406,6 @@ PEGTransformerFactory::FinalizeColumnReferenceTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNestedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(3).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(4 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ReservedSchemaQualification), repeat_children[child_idx].get()}, - 3 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::ReservedSchemaQualification), list_pr.GetChild(2)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedSchemaQualification), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13695,15 +13428,6 @@ PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCatalogReservedSchemaTableColumnNameTrampoline( - PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedTableQualification), list_pr.GetChild(2)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedSchemaQualification), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13718,14 +13442,6 @@ PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline(PE return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSchemaReservedTableColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ReservedTableQualification), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13738,13 +13454,6 @@ PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline(PEGTransf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableReservedColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TableQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13755,26 +13464,6 @@ PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFunctionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &over_clause_opt = list_pr.GetChild(5).Cast(); - if (over_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OverClause), over_clause_opt.GetResult()}, 4); - } - auto &filter_clause_opt = list_pr.GetChild(3).Cast(); - if (filter_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::FilterClause), filter_clause_opt.GetResult()}, 3); - } - auto &within_group_clause_opt = list_pr.GetChild(2).Cast(); - if (within_group_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithinGroupClause), within_group_clause_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::FunctionExpressionArguments), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::FunctionIdentifier), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFunctionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13802,15 +13491,6 @@ PEGTransformerFactory::FinalizeFunctionExpressionTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFunctionExpressionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::FunctionExpressionArgumentList), ExtractResultFromParens(list_pr.GetChild(0))}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13819,30 +13499,6 @@ PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline(PEGTransfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFunctionExpressionArgumentListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &ignore_or_respect_nulls_opt = list_pr.GetChild(3).Cast(); - if (ignore_or_respect_nulls_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::IgnoreOrRespectNulls), ignore_or_respect_nulls_opt.GetResult()}, 3); - } - auto &order_by_clause_opt = list_pr.GetChild(2).Cast(); - if (order_by_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrderByClause), order_by_clause_opt.GetResult()}, 2); - } - auto &function_argument_list_opt = list_pr.GetChild(1).Cast(); - if (function_argument_list_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::FunctionArgumentList), function_argument_list_opt.GetResult()}, 1); - } - auto &distinct_or_all_opt = list_pr.GetChild(0).Cast(); - if (distinct_or_all_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DistinctOrAll), distinct_or_all_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13868,19 +13524,6 @@ PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline(PEGTrans return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFunctionArgumentListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::FunctionArgument), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13895,32 +13538,6 @@ PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFunctionIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFunctionIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeFunctionNameAsQualifiedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13930,28 +13547,6 @@ PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline(PEGTransfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCatalogReservedSchemaFunctionNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ReservedSchemaQualification), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13979,13 +13574,6 @@ PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline(PEGTr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSchemaReservedFunctionNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -13996,32 +13584,6 @@ PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline(PEGTransform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDistinctOrAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDistinctOrAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeDistinctKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDistinctKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14029,24 +13591,12 @@ PEGTransformerFactory::FinalizeDistinctKeywordTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAllKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAllKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformAllKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWithinGroupClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OrderByClause), ExtractResultFromParens(list_pr.GetChild(2))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14055,13 +13605,6 @@ PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFilterClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::FilterClauseExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFilterClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto filter_clause_expression = process.TakeResult>(0); @@ -14069,14 +13612,6 @@ PEGTransformerFactory::FinalizeFilterClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFilterClauseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::FilterClauseContents), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14085,13 +13620,6 @@ PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFilterClauseContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14104,67 +13632,18 @@ PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIgnoreOrRespectNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIgnoreOrRespectNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeIgnoreNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIgnoreNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformIgnoreNulls(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRespectNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRespectNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformRespectNulls(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeParenthesisExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeParenthesisExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14188,20 +13667,6 @@ PEGTransformerFactory::FinalizeParenthesisExpressionTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeConstantLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeConstantLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14210,47 +13675,24 @@ PEGTransformerFactory::FinalizeConstantLiteralTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNullLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNullLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNullLiteral(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTrueLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTrueLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformTrueLiteral(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFalseLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFalseLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformFalseLiteral(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCastExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::CastArguments), ExtractResultFromParens(list_pr.GetChild(1))}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::CastOrTryCast), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCastExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14260,14 +13702,6 @@ PEGTransformerFactory::FinalizeCastExpressionTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCastArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Type), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCastArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14277,43 +13711,12 @@ PEGTransformerFactory::FinalizeCastArgumentsTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCastOrTryCastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeCastOrTryCastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCastKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCastKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCastKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTryCastKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTryCastKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14321,13 +13724,6 @@ PEGTransformerFactory::FinalizeTryCastKeywordTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColIdDotTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColIdDotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id = process.TakeResult(0); @@ -14335,28 +13731,6 @@ arena_ptr PEGTransformerFactory::FinalizeColIdDotTrampolin return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeStarExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &rename_list_opt = list_pr.GetChild(4).Cast(); - if (rename_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::RenameList), rename_list_opt.GetResult()}, 3); - } - auto &replace_list_opt = list_pr.GetChild(3).Cast(); - if (replace_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReplaceList), replace_list_opt.GetResult()}, 2); - } - auto &exclude_list_opt = list_pr.GetChild(2).Cast(); - if (exclude_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExcludeList), exclude_list_opt.GetResult()}, 1); - } - auto &star_qualifier_list_opt = list_pr.GetChild(0).Cast(); - if (star_qualifier_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::StarQualifierList), star_qualifier_list_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeStarExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14381,19 +13755,6 @@ PEGTransformerFactory::FinalizeStarExpressionTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeStarQualifierListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(0).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdDot), repeat_children[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeStarQualifierListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14410,13 +13771,6 @@ PEGTransformerFactory::FinalizeStarQualifierListTrampoline(PEGTransformer &trans return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeExcludeListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ExcludeNames), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto exclude_names = process.TakeResult(0); @@ -14424,38 +13778,6 @@ PEGTransformerFactory::FinalizeExcludeListTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeNamesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExcludeNamesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeExcludeNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ExcludeName), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeExcludeNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14470,13 +13792,6 @@ PEGTransformerFactory::FinalizeExcludeNameListTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeNameSingleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ExcludeName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14485,33 +13800,6 @@ PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExcludeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeExcludeDottedNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::DottedIdentifier), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14520,13 +13808,6 @@ PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14535,13 +13816,6 @@ PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReplaceListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ReplaceEntries), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReplaceListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto replace_entries = process.TakeResult>>(0); @@ -14549,34 +13823,6 @@ PEGTransformerFactory::FinalizeReplaceListTrampoline(PEGTransformer &transformer return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeReplaceEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeReplaceEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeReplaceEntrySingleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ReplaceEntry), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14585,18 +13831,6 @@ PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline(PEGTransformer &tran return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeReplaceEntryListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ReplaceEntry), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeReplaceEntryListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14611,14 +13845,6 @@ PEGTransformerFactory::FinalizeReplaceEntryListTrampoline(PEGTransformer &transf return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeReplaceEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnReference), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReplaceEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -14627,13 +13853,6 @@ PEGTransformerFactory::FinalizeReplaceEntryTrampoline(PEGTransformer &transforme return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeRenameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RenameEntries), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRenameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto rename_entries = process.TakeResult>(0); @@ -14641,39 +13860,6 @@ PEGTransformerFactory::FinalizeRenameListTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeRenameEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRenameEntriesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeRenameEntryListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::RenameEntry), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeRenameEntryListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14688,13 +13874,6 @@ PEGTransformerFactory::FinalizeRenameEntryListTrampoline(PEGTransformer &transfo return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeSingleRenameEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RenameEntry), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14703,13 +13882,6 @@ PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline(PEGTransformer &trans return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeRenameEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ExcludeName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRenameEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -14719,21 +13891,6 @@ PEGTransformerFactory::FinalizeRenameEntryTrampoline(PEGTransformer &transformer return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeSubqueryExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::SubqueryReference), list_pr.GetChild(2)}, 2); - auto &subquery_exists_opt = list_pr.GetChild(1).Cast(); - if (subquery_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SubqueryExists), subquery_exists_opt.GetResult()}, 1); - } - auto &subquery_not_opt = list_pr.GetChild(0).Cast(); - if (subquery_not_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SubqueryNot), subquery_not_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14751,22 +13908,12 @@ PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSubqueryNotTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSubqueryNotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSubqueryNot(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSubqueryExistsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSubqueryExistsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14774,60 +13921,69 @@ PEGTransformerFactory::FinalizeSubqueryExistsTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCaseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +arena_ptr +PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(2).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - auto &case_else_opt = list_pr.GetChild(3).Cast(); - if (case_else_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CaseElse), case_else_opt.GetResult()}, - 2 + dynamic_child_count - 1); - } - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CaseWhenThen), repeat_children[child_idx].get()}, - 1 + child_idx); + auto &dynamic_repeat_pr = list_pr.GetChild(2).Cast(); + auto dynamic_repeat_children = dynamic_repeat_pr.GetChildren(); + auto dynamic_child_count = dynamic_repeat_children.size(); + auto expression = process.TakeResult>(0); + vector simple_case_when_then; + simple_case_when_then.reserve(dynamic_child_count); + for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { + simple_case_when_then.push_back(process.TakeResult(i)); } - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); + optional> case_else {}; + if (process.child_results[2 + dynamic_child_count - 1]) { + case_else = process.TakeResult>(2 + dynamic_child_count - 1); } + auto result = TransformSimpleCaseExpression(transformer, std::move(expression), std::move(simple_case_when_then), + std::move(case_else)); + return transformer.MakeResult>(std::move(result)); } arena_ptr -PEGTransformerFactory::FinalizeCaseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); - auto &dynamic_repeat_pr = list_pr.GetChild(2).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(); - optional> expression {}; - if (process.child_results[0]) { - expression = process.TakeResult>(0); - } vector case_when_then; case_when_then.reserve(dynamic_child_count); - for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { + for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { case_when_then.push_back(process.TakeResult(i)); } optional> case_else {}; - if (process.child_results[2 + dynamic_child_count - 1]) { - case_else = process.TakeResult>(2 + dynamic_child_count - 1); + if (process.child_results[1 + dynamic_child_count - 1]) { + case_else = process.TakeResult>(1 + dynamic_child_count - 1); } - auto result = - TransformCaseExpression(transformer, std::move(expression), std::move(case_when_then), std::move(case_else)); + auto result = TransformSearchedCaseExpression(transformer, std::move(case_when_then), std::move(case_else)); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCaseWhenThenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +arena_ptr +PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); + auto dynamic_child_count = CountParseResultsFromList(list_pr.GetChild(1)); + vector simple_case_when_operand; + simple_case_when_operand.reserve(dynamic_child_count); + for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { + simple_case_when_operand.push_back(process.TakeResult(i)); + } + auto expression = process.TakeResult>(1 + dynamic_child_count - 1); + auto result = TransformSimpleCaseWhenThen(transformer, std::move(simple_case_when_operand), std::move(expression)); + return transformer.MakeResult(std::move(result)); +} + +arena_ptr +PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto expression = process.TakeResult>(0); + auto result = TransformSimpleCaseWhenEquals(transformer, std::move(expression)); + return transformer.MakeResult(std::move(result)); } arena_ptr @@ -14838,13 +13994,6 @@ PEGTransformerFactory::FinalizeCaseWhenThenTrampoline(PEGTransformer &transforme return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCaseElseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCaseElseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -14852,13 +14001,6 @@ arena_ptr PEGTransformerFactory::FinalizeCaseElseTrampolin return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTypeLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Type), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTypeLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -14868,17 +14010,6 @@ PEGTransformerFactory::FinalizeTypeLiteralTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntervalLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &interval_opt = list_pr.GetChild(2).Cast(); - if (interval_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Interval), interval_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::IntervalParameter), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIntervalLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14891,32 +14022,6 @@ PEGTransformerFactory::FinalizeIntervalLiteralTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntervalParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIntervalParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIntervalStringParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -14926,19 +14031,6 @@ PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFrameClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &window_exclude_clause_opt = list_pr.GetChild(2).Cast(); - if (window_exclude_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WindowExcludeClause), window_exclude_clause_opt.GetResult()}, - 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::FrameExtent), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Framing), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFrameClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto framing = process.TakeResult(0); @@ -14951,24 +14043,6 @@ PEGTransformerFactory::FinalizeFrameClauseTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFramingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -14992,33 +14066,18 @@ arena_ptr PEGTransformerFactory::FinalizeFramingTrampoline return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRowsFramingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRowsFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformRowsFraming(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRangeFramingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRangeFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformRangeFraming(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGroupsFramingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupsFramingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15026,33 +14085,6 @@ PEGTransformerFactory::FinalizeGroupsFramingTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFrameExtentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSingleFrameExtentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::FrameBound), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15061,14 +14093,6 @@ PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBetweenFrameExtentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::FrameBound), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::FrameBound), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15078,33 +14102,6 @@ PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFrameBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFrameBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeFrameUnboundedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PrecedingOrFollowing), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFrameUnboundedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15113,14 +14110,6 @@ PEGTransformerFactory::FinalizeFrameUnboundedTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFrameExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::PrecedingOrFollowing), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFrameExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15130,11 +14119,6 @@ PEGTransformerFactory::FinalizeFrameExpressionTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFrameCurrentRowTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15142,32 +14126,6 @@ PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePrecedingOrFollowingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePrecedingOrFollowingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializePrecedingFrameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePrecedingFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15175,11 +14133,6 @@ PEGTransformerFactory::FinalizePrecedingFrameTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFollowingFrameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFollowingFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15187,13 +14140,6 @@ PEGTransformerFactory::FinalizeFollowingFrameTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWindowExcludeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::WindowExcludeElement), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15202,32 +14148,6 @@ PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWindowExcludeElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeWindowExcludeElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeExcludeCurrentRowTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeCurrentRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15235,33 +14155,18 @@ PEGTransformerFactory::FinalizeExcludeCurrentRowTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeGroupTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeGroupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformExcludeGroup(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeTiesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeTiesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformExcludeTies(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeNoOthersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeNoOthersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15269,31 +14174,6 @@ PEGTransformerFactory::FinalizeExcludeNoOthersTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWindowFrameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeWindowFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIdentifierWindowFrameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIdentifierWindowFrameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15303,11 +14183,6 @@ PEGTransformerFactory::FinalizeIdentifierWindowFrameTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeParensIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeParensIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15317,52 +14192,12 @@ PEGTransformerFactory::FinalizeParensIdentifierTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWindowFrameDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeWindowFrameDefinitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeWindowFrameNameContentsParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::WindowFrameNameContents), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto window_frame_name_contents = process.TakeResult>(0); - auto result = TransformWindowFrameNameContentsParens(transformer, std::move(window_frame_name_contents)); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeWindowFrameNameContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::WindowFrameContents), list_pr.GetChild(1)}, 1); - auto &base_window_name_opt = list_pr.GetChild(0).Cast(); - if (base_window_name_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::BaseWindowName), base_window_name_opt.GetResult()}, 0); - } +arena_ptr +PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto window_frame_name_contents = process.TakeResult>(0); + auto result = TransformWindowFrameNameContentsParens(transformer, std::move(window_frame_name_contents)); + return transformer.MakeResult>(std::move(result)); } arena_ptr @@ -15377,14 +14212,6 @@ PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWindowFrameContentsParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::WindowFrameContents), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15393,24 +14220,6 @@ PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWindowFrameContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &frame_clause_opt = list_pr.GetChild(2).Cast(); - if (frame_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::FrameClause), frame_clause_opt.GetResult()}, 2); - } - auto &order_by_clause_opt = list_pr.GetChild(1).Cast(); - if (order_by_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrderByClause), order_by_clause_opt.GetResult()}, 1); - } - auto &window_partition_opt = list_pr.GetChild(0).Cast(); - if (window_partition_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WindowPartition), window_partition_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15431,11 +14240,6 @@ PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBaseWindowNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeBaseWindowNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15445,18 +14249,6 @@ PEGTransformerFactory::FinalizeBaseWindowNameTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWindowPartitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeWindowPartitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15471,34 +14263,6 @@ PEGTransformerFactory::FinalizeWindowPartitionTrampoline(PEGTransformer &transfo return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeArrayBoundedListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::BoundedListExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15511,14 +14275,6 @@ PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline(PEGTransform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeArrayParensSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeArrayParensSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15527,24 +14283,6 @@ PEGTransformerFactory::FinalizeArrayParensSelectTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBoundedListExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15568,25 +14306,6 @@ PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline(PEGTransformer &t return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeStructExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::StructField), list_items[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeStructExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15610,14 +14329,6 @@ PEGTransformerFactory::FinalizeStructExpressionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeStructFieldTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeStructFieldTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_id_or_string = process.TakeResult(0); @@ -15626,13 +14337,6 @@ PEGTransformerFactory::FinalizeStructFieldTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMapExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::MapStructExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMapExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15641,25 +14345,6 @@ PEGTransformerFactory::FinalizeMapExpressionTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMapStructExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::MapStructField), list_items[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeMapStructExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15683,14 +14368,6 @@ PEGTransformerFactory::FinalizeMapStructExpressionTrampoline(PEGTransformer &tra return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeMapStructFieldTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMapStructFieldTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15700,25 +14377,6 @@ PEGTransformerFactory::FinalizeMapStructFieldTrampoline(PEGTransformer &transfor return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeGroupingExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = ExtractResultFromParens(list_pr.GetChild(1)).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::GroupingOrGroupingId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupingExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15743,32 +14401,6 @@ PEGTransformerFactory::FinalizeGroupingExpressionTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeGroupingOrGroupingIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeGroupingOrGroupingIdTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeGroupingKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupingKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15776,11 +14408,6 @@ PEGTransformerFactory::FinalizeGroupingKeywordTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGroupingIdKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupingIdKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15788,31 +14415,6 @@ PEGTransformerFactory::FinalizeGroupingIdKeywordTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeQuestionMarkNumberedParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuestionMarkNumberedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15822,11 +14424,6 @@ PEGTransformerFactory::FinalizeQuestionMarkNumberedParameterTrampoline(PEGTransf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAnonymousParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAnonymousParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15834,11 +14431,6 @@ PEGTransformerFactory::FinalizeAnonymousParameterTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNumberedParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNumberedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15848,13 +14440,6 @@ PEGTransformerFactory::FinalizeNumberedParameterTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColLabelParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColLabelParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15863,11 +14448,6 @@ PEGTransformerFactory::FinalizeColLabelParameterTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePositionalExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePositionalExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15877,11 +14457,6 @@ PEGTransformerFactory::FinalizePositionalExpressionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDefaultExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDefaultExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15889,26 +14464,6 @@ PEGTransformerFactory::FinalizeDefaultExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeListComprehensionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(3)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(4 + dynamic_child_count - 1); - auto &list_comprehension_filter_opt = list_pr.GetChild(6).Cast(); - if (list_comprehension_filter_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::ListComprehensionFilter), list_comprehension_filter_opt.GetResult()}, - 3 + dynamic_child_count - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(5)}, 2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15930,13 +14485,6 @@ PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeListComprehensionFilterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15945,13 +14493,6 @@ PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeParensExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeParensExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15960,14 +14501,6 @@ PEGTransformerFactory::FinalizeParensExpressionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMeasureSemanticsExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::FunctionExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::MeasureSemantics), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15977,47 +14510,6 @@ PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline(PEGTransform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSingleExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSingleExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LambdaArrowExpression), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeColumnDefaultExprTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColDefOrExpr), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16026,27 +14518,6 @@ PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SingleArrowPair), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::LogicalOrExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16073,13 +14544,6 @@ PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSingleArrowPairTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LogicalOrExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSingleArrowPairTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16088,28 +14552,6 @@ PEGTransformerFactory::FinalizeSingleArrowPairTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLogicalOrExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::LogicalOrExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::LogicalAndExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16136,13 +14578,6 @@ PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLogicalOrExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LogicalAndExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16151,28 +14586,6 @@ PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColDefOrExprTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ColDefOrExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColDefAndExpr), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColDefOrExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -16198,13 +14611,6 @@ PEGTransformerFactory::FinalizeColDefOrExprTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColDefOrExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColDefAndExpr), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16213,28 +14619,6 @@ PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLogicalAndExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::LogicalAndExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::LogicalNotExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16261,13 +14645,6 @@ PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLogicalAndExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LogicalNotExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16276,28 +14653,6 @@ PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColDefAndExprTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ColDefAndExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::IsDistinctFromExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColDefAndExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16324,13 +14679,6 @@ PEGTransformerFactory::FinalizeColDefAndExprTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColDefAndExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IsDistinctFromExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16339,17 +14687,6 @@ PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLogicalNotExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::IsExpression), list_pr.GetChild(1)}, 1); - auto ¬_expression_opt = list_pr.GetChild(0).Cast(); - if (not_expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::NotExpression), not_expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16362,20 +14699,6 @@ PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNotExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(0).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::NotKeyword), repeat_children[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeNotExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16392,29 +14715,12 @@ PEGTransformerFactory::FinalizeNotExpressionTrampoline(PEGTransformer &transform return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeNotKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNotKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeIsExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &is_expression_continuation_opt = list_pr.GetChild(1).Cast(); - if (is_expression_continuation_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::IsExpressionContinuation), is_expression_continuation_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::IsDistinctFromExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto is_distinct_from_expression = process.TakeResult>(0); @@ -16427,27 +14733,6 @@ PEGTransformerFactory::FinalizeIsExpressionTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsExpressionContinuationTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::IsExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::IsTest), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16473,34 +14758,6 @@ PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIsExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeIsTestTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IsTest), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsTestTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto is_test = process.TakeResult>(0); @@ -16508,13 +14765,6 @@ PEGTransformerFactory::FinalizeIsTestTailTrampoline(PEGTransformer &transformer, return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIsDistinctTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IsDistinctFromTail), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsDistinctTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16523,13 +14773,6 @@ PEGTransformerFactory::FinalizeIsDistinctTailTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIsComparisonTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ComparisonExpressionTail), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsComparisonTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16538,13 +14781,6 @@ PEGTransformerFactory::FinalizeIsComparisonTailTrampoline(PEGTransformer &transf return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIsOtherOperatorTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorTail), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16553,13 +14789,6 @@ PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline(PEGTransformer &tra return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIsCastTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::CastOperator), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsCastTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto cast_operator = process.TakeResult>(0); @@ -16567,33 +14796,6 @@ PEGTransformerFactory::FinalizeIsCastTailTrampoline(PEGTransformer &transformer, return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIsTestTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeIsTestTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIsLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IsLiteralValue), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -16605,32 +14807,6 @@ arena_ptr PEGTransformerFactory::FinalizeIsLiteralTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsLiteralValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIsLiteralValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeUnknownLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeUnknownLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16638,31 +14814,6 @@ PEGTransformerFactory::FinalizeUnknownLiteralTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNotNullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeNotNullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeNotNullKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotNullKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16670,11 +14821,6 @@ PEGTransformerFactory::FinalizeNotNullKeywordTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNotNullOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotNullOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16682,13 +14828,6 @@ PEGTransformerFactory::FinalizeNotNullOperatorTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsNullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IsNullOperator), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsNullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto is_null_operator = process.TakeResult>(0); @@ -16696,11 +14835,6 @@ arena_ptr PEGTransformerFactory::FinalizeIsNullTrampoline( return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsNullOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIsNullOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16708,27 +14842,6 @@ PEGTransformerFactory::FinalizeIsNullOperatorTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsDistinctFromExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::IsDistinctFromTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ComparisonExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16755,14 +14868,6 @@ PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIsDistinctFromTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ComparisonExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::IsDistinctFromOp), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16772,11 +14877,6 @@ PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline(PEGTransformer &tran return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIsDistinctFromOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16788,28 +14888,6 @@ PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeComparisonExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ComparisonExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BetweenInLikeExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeComparisonExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16836,14 +14914,6 @@ PEGTransformerFactory::FinalizeComparisonExpressionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeComparisonExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ComparisonOperand), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ComparisonOperator), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16853,35 +14923,6 @@ PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline(PEGTransformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeComparisonOperandTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeComparisonOperandTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeNotComparisonOperandTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::IsExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::NotExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16891,32 +14932,6 @@ PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeComparisonOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeComparisonOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeOperatorEqualTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorEqualTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16924,11 +14939,6 @@ PEGTransformerFactory::FinalizeOperatorEqualTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOperatorNotEqualTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorNotEqualTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16936,11 +14946,6 @@ PEGTransformerFactory::FinalizeOperatorNotEqualTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOperatorLessThanTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorLessThanTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16948,11 +14953,6 @@ PEGTransformerFactory::FinalizeOperatorLessThanTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOperatorGreaterThanTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorGreaterThanTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16960,11 +14960,6 @@ PEGTransformerFactory::FinalizeOperatorGreaterThanTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOperatorLessThanEqualsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorLessThanEqualsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16972,11 +14967,6 @@ PEGTransformerFactory::FinalizeOperatorLessThanEqualsTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOperatorGreaterThanEqualsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16984,37 +14974,6 @@ PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline(PEGTransforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBetweenInLikeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - auto &between_like_op_opt = list_pr.GetChild(2).Cast(); - if (between_like_op_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::BetweenLikeOp), between_like_op_opt.GetResult()}, - 2 + dynamic_child_count - 1); - } - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::InPredicate), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(3 - 1); - auto &between_like_op_opt = list_pr.GetChild(2).Cast(); - if (between_like_op_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::BetweenLikeOp), between_like_op_opt.GetResult()}, - 2 + dynamic_child_count - 1); - } - } - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17045,27 +15004,6 @@ PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInPredicateTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(2).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CastOperator), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::InClause), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInPredicateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -17093,13 +15031,6 @@ PEGTransformerFactory::FinalizeInPredicateTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeBetweenLikeOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::BetweenLikeOpExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17112,39 +15043,6 @@ PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeBetweenLikeOpExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeBetweenLikeOpExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeLikeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &escape_clause_opt = list_pr.GetChild(2).Cast(); - if (escape_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::EscapeClause), escape_clause_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::LikeVariations), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLikeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto like_variations = process.TakeResult(0); @@ -17158,13 +15056,6 @@ PEGTransformerFactory::FinalizeLikeClauseTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeEscapeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeEscapeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto other_operator_expression = process.TakeResult>(0); @@ -17172,24 +15063,6 @@ PEGTransformerFactory::FinalizeEscapeClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLikeVariationsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLikeVariationsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17214,44 +15087,24 @@ PEGTransformerFactory::FinalizeLikeVariationsTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeLikeTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLikeTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformLikeToken(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeILikeTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeILikeTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformILikeToken(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGlobTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGlobTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformGlobToken(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSimilarToTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSimilarToTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17259,11 +15112,6 @@ PEGTransformerFactory::FinalizeSimilarToTokenTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRegexMatchTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRegexMatchTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17271,11 +15119,6 @@ PEGTransformerFactory::FinalizeRegexMatchTokenTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRegexInsensitiveMatchTokenTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRegexInsensitiveMatchTokenTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17283,33 +15126,18 @@ PEGTransformerFactory::FinalizeRegexInsensitiveMatchTokenTrampoline(PEGTransform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNotILikeOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotILikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNotILikeOp(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNotLikeOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotLikeOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNotLikeOp(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNotRegexInsensitiveMatchOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotRegexInsensitiveMatchOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17317,11 +15145,6 @@ PEGTransformerFactory::FinalizeNotRegexInsensitiveMatchOpTrampoline(PEGTransform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNotSimilarToOpTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17329,13 +15152,6 @@ PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeInClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::InExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto in_expression = process.TakeResult>(0); @@ -17343,33 +15159,6 @@ arena_ptr PEGTransformerFactory::FinalizeInClauseTrampolin return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeInExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeInContainsExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInContainsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17378,18 +15167,6 @@ PEGTransformerFactory::FinalizeInContainsExpressionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeInExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17404,14 +15181,6 @@ PEGTransformerFactory::FinalizeInExpressionListTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInSelectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17420,14 +15189,6 @@ PEGTransformerFactory::FinalizeInSelectStatementTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBetweenClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(4)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBetweenClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17442,41 +15203,6 @@ PEGTransformerFactory::FinalizeBetweenClauseTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOtherOperatorExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::InfixOtherOperatorExpression), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOtherOperatorExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeInfixOtherOperatorExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BitwiseExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17503,49 +15229,24 @@ PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline(PEGTransfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOtherOperatorTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::BitwiseExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperator), list_pr.GetChild(0)}, 0); -} - arena_ptr -PEGTransformerFactory::FinalizeOtherOperatorTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto other_operator = process.TakeResult(0); - auto bitwise_expression = process.TakeResult>(1); - auto result = TransformOtherOperatorTail(transformer, std::move(other_operator), std::move(bitwise_expression)); +PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto any_all_parsed_operator = process.TakeResult(0); + auto subquery_reference = process.TakeResult>(1); + auto result = + TransformAnyAllSubqueryTail(transformer, std::move(any_all_parsed_operator), std::move(subquery_reference)); return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOtherOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr -PEGTransformerFactory::FinalizeOtherOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeAnyAllParsedOperatorTrampoline(PEGTransformer &transformer, +PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AnyAllOperator), list_pr.GetChild(0)}, 0); + auto other_operator = process.TakeResult(0); + auto bitwise_expression = process.TakeResult>(1); + auto result = + TransformOtherOperatorExpressionTail(transformer, std::move(other_operator), std::move(bitwise_expression)); + return transformer.MakeResult(std::move(result)); } arena_ptr @@ -17556,26 +15257,6 @@ PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline(PEGTransformer &tr return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeNamedOtherOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && - (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR || - choice_result.type == ParseResultType::CHOICE || choice_result.type == ParseResultType::LIST)) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17601,11 +15282,6 @@ PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline(PEGTransformer &tran return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOperatorLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOperatorLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17613,11 +15289,6 @@ PEGTransformerFactory::FinalizeOperatorLiteralTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAnyOperatorLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17625,13 +15296,6 @@ PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAnyAllOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AnyOrAll), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17642,56 +15306,18 @@ PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline(PEGTransformer &transfor return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeAnyOrAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeAnyOrAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSubqueryAnyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSubqueryAnyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSubqueryAny(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSubqueryAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSubqueryAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSubqueryAll(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQualifiedOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::QualifiedOperatorContents), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17700,29 +15326,9 @@ PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQualifiedOperatorContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(0).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdDot), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - -arena_ptr -PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +arena_ptr +PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); idx_t dynamic_child_count = 0; auto &dynamic_repeat_opt = list_pr.GetChild(0).Cast(); @@ -17745,27 +15351,6 @@ PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline(PEGTransforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBitwiseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::BitwiseExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TildeExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17792,14 +15377,6 @@ PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBitwiseExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::TildeExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::BitOperator), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17809,11 +15386,6 @@ PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeBitOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeBitOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -17822,30 +15394,6 @@ PEGTransformerFactory::FinalizeBitOperatorTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTildeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(0).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - process.PushChild({transformer.GetRule(PEGRuleId::AdditiveExpression), list_pr.GetChild(1)}, - 1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::TildePrefixOperator), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - process.PushChild({transformer.GetRule(PEGRuleId::AdditiveExpression), list_pr.GetChild(1)}, - 1 + dynamic_child_count - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeTildeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17871,28 +15419,6 @@ PEGTransformerFactory::FinalizeTildeExpressionTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAdditiveExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::AdditiveExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::MultiplicativeExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17919,14 +15445,6 @@ PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAdditiveExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::MultiplicativeExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Term), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17937,10 +15455,6 @@ PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline(PEGTransformer & return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -17949,28 +15463,6 @@ arena_ptr PEGTransformerFactory::FinalizeTermTrampoline(PE return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMultiplicativeExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::MultiplicativeExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ExponentiationExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -17997,14 +15489,6 @@ PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMultiplicativeExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ExponentiationExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Factor), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18014,11 +15498,6 @@ PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline(PEGTransfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFactorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFactorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -18027,28 +15506,6 @@ arena_ptr PEGTransformerFactory::FinalizeFactorTrampoline( return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExponentiationExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ExponentiationExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::CollateExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18075,14 +15532,6 @@ PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExponentiationExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::CollateExpression), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ExponentOperator), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18092,11 +15541,6 @@ PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline(PEGTransfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeExponentOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExponentOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18106,27 +15550,6 @@ PEGTransformerFactory::FinalizeExponentOperatorTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCollateExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::CollateExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::AtTimeZoneExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCollateExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18153,13 +15576,6 @@ PEGTransformerFactory::FinalizeCollateExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCollateExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AtTimeZoneExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18168,28 +15584,6 @@ PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAtTimeZoneExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::AtTimeZoneExpressionTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::UnaryExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18216,13 +15610,6 @@ PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAtTimeZoneExpressionTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::UnaryExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18231,34 +15618,6 @@ PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUnaryExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeUnaryExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCustomPrefixExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TildeExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18269,24 +15628,6 @@ PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePrefixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18311,11 +15652,6 @@ PEGTransformerFactory::FinalizePrefixOperatorTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeMinusPrefixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMinusPrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18323,11 +15659,6 @@ PEGTransformerFactory::FinalizeMinusPrefixOperatorTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePlusPrefixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePlusPrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18335,11 +15666,6 @@ PEGTransformerFactory::FinalizePlusPrefixOperatorTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTildePrefixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18347,17 +15673,6 @@ PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBaseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &indirection_list_opt = list_pr.GetChild(1).Cast(); - if (indirection_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IndirectionList), indirection_list_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SingleExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBaseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18370,20 +15685,6 @@ PEGTransformerFactory::FinalizeBaseExpressionTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIndirectionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(0).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Indirection), repeat_children[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeIndirectionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18400,33 +15701,6 @@ PEGTransformerFactory::FinalizeIndirectionListTrampoline(PEGTransformer &transfo return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeIndirectionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIndirectionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCastOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Type), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCastOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto type = process.TakeResult(0); @@ -18434,33 +15708,6 @@ PEGTransformerFactory::FinalizeCastOperatorTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDotOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDotOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeDotMethodOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::MethodExpression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18469,13 +15716,6 @@ PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDotColumnOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18484,14 +15724,6 @@ PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMethodExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::MethodExpressionArguments), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMethodExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18501,15 +15733,6 @@ PEGTransformerFactory::FinalizeMethodExpressionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMethodExpressionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::MethodExpressionArgumentList), ExtractResultFromParens(list_pr.GetChild(0))}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18518,30 +15741,6 @@ PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline(PEGTransforme return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMethodExpressionArgumentListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &ignore_or_respect_nulls_opt = list_pr.GetChild(3).Cast(); - if (ignore_or_respect_nulls_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::IgnoreOrRespectNulls), ignore_or_respect_nulls_opt.GetResult()}, 3); - } - auto &order_by_clause_opt = list_pr.GetChild(2).Cast(); - if (order_by_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrderByClause), order_by_clause_opt.GetResult()}, 2); - } - auto &method_function_arguments_opt = list_pr.GetChild(1).Cast(); - if (method_function_arguments_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::MethodFunctionArguments), method_function_arguments_opt.GetResult()}, 1); - } - auto &distinct_or_all_opt = list_pr.GetChild(0).Cast(); - if (distinct_or_all_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DistinctOrAll), distinct_or_all_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18567,19 +15766,6 @@ PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline(PEGTransfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMethodFunctionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::FunctionArgument), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18594,13 +15780,6 @@ PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSliceExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SliceBound), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSliceExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18609,20 +15788,6 @@ PEGTransformerFactory::FinalizeSliceExpressionTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &slice_upper_bound_opt = list_pr.GetChild(1).Cast(); - if (slice_upper_bound_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SliceUpperBound), slice_upper_bound_opt.GetResult()}, 1); - } - auto &expression_opt = list_pr.GetChild(0).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional> expression {}; @@ -18637,53 +15802,14 @@ PEGTransformerFactory::FinalizeSliceBoundTrampoline(PEGTransformer &transformer, return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSliceUpperBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr -PEGTransformerFactory::FinalizeSliceUpperBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); +PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto step_slice_bound = process.TakeResult>(0); + auto result = TransformMinusStepSliceBound(transformer, std::move(step_slice_bound)); return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeMinusStepSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::StepSliceBound), list_pr.GetChild(2)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto step_slice_bound = process.TakeResult>(0); - auto result = TransformMinusStepSliceBound(transformer, std::move(step_slice_bound)); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeEndStepSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &step_slice_bound_opt = list_pr.GetChild(1).Cast(); - if (step_slice_bound_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::StepSliceBound), step_slice_bound_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::EndSliceBound), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18696,16 +15822,6 @@ PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline(PEGTransformer &trans return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeEndSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeEndSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18717,16 +15833,6 @@ PEGTransformerFactory::FinalizeEndSliceBoundTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeStepSliceBoundTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeStepSliceBoundTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18738,11 +15844,6 @@ PEGTransformerFactory::FinalizeStepSliceBoundTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePostfixOperatorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePostfixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18750,39 +15851,6 @@ PEGTransformerFactory::FinalizePostfixOperatorTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSpecialFunctionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSpecialFunctionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCoalesceExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(1))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18797,13 +15865,6 @@ PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUnpackExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUnpackExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18812,13 +15873,6 @@ PEGTransformerFactory::FinalizeUnpackExpressionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTryExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTryExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18827,13 +15881,6 @@ PEGTransformerFactory::FinalizeTryExpressionTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeColumnsExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), ExtractResultFromParens(list_pr.GetChild(2))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeColumnsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18846,14 +15893,6 @@ PEGTransformerFactory::FinalizeColumnsExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExtractExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ExtractArguments), ExtractResultFromParens(list_pr.GetChild(1))}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizeExtractExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18862,14 +15901,6 @@ PEGTransformerFactory::FinalizeExtractExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExtractArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ExtractArgument), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExtractArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18879,19 +15910,6 @@ PEGTransformerFactory::FinalizeExtractArgumentsTrampoline(PEGTransformer &transf return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeLambdaExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(3)}, 1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeLambdaExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18907,14 +15925,6 @@ PEGTransformerFactory::FinalizeLambdaExpressionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNullIfExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::NullIfArguments), ExtractResultFromParens(list_pr.GetChild(1))}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizeNullIfExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18923,14 +15933,6 @@ PEGTransformerFactory::FinalizeNullIfExpressionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNullIfArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18940,14 +15942,6 @@ PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline(PEGTransformer &transfo return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializePositionExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PositionArguments), ExtractResultFromParens(list_pr.GetChild(1))}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizePositionExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18956,14 +15950,6 @@ PEGTransformerFactory::FinalizePositionExpressionTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePositionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::OtherOperatorExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePositionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18973,24 +15959,6 @@ PEGTransformerFactory::FinalizePositionArgumentsTrampoline(PEGTransformer &trans return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeRowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = ExtractResultFromParens(list_pr.GetChild(1)).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeRowExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19014,14 +15982,6 @@ PEGTransformerFactory::FinalizeRowExpressionTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSubstringExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SubstringArguments), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSubstringExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19030,39 +15990,6 @@ PEGTransformerFactory::FinalizeSubstringExpressionTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSubstringArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSubstringArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSubstringExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19077,14 +16004,6 @@ PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline(PEGTransformer return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSubstringParametersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SubstringFromFor), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSubstringParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19094,38 +16013,6 @@ PEGTransformerFactory::FinalizeSubstringParametersTrampoline(PEGTransformer &tra return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSubstringFromForTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSubstringFromForTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSubstringFromOptionalForTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &for_expression_opt = list_pr.GetChild(1).Cast(); - if (for_expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ForExpression), for_expression_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::FromExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19138,13 +16025,6 @@ PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline(PEGTransformer return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSubstringForTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ForExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSubstringForTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto for_expression = process.TakeResult>(0); @@ -19152,13 +16032,6 @@ PEGTransformerFactory::FinalizeSubstringForTrampoline(PEGTransformer &transforme return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeTrimExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TrimArguments), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTrimExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19167,26 +16040,6 @@ PEGTransformerFactory::FinalizeTrimExpressionTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTrimArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(2)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 2 + child_idx); - } - auto &trim_source_opt = list_pr.GetChild(1).Cast(); - if (trim_source_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TrimSource), trim_source_opt.GetResult()}, 1); - } - auto &trim_direction_opt = list_pr.GetChild(0).Cast(); - if (trim_direction_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TrimDirection), trim_direction_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeTrimArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19209,24 +16062,6 @@ PEGTransformerFactory::FinalizeTrimArgumentsTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeTrimDirectionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTrimDirectionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19251,49 +16086,24 @@ PEGTransformerFactory::FinalizeTrimDirectionTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTrimBothTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTrimBothTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformTrimBoth(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTrimLeadingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTrimLeadingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformTrimLeading(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTrimTrailingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTrimTrailingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformTrimTrailing(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTrimSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &expression_opt = list_pr.GetChild(0).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeTrimSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional> expression {}; @@ -19304,14 +16114,6 @@ PEGTransformerFactory::FinalizeTrimSourceTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOverlayExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OverlayArguments), ExtractResultFromParens(list_pr.GetChild(1))}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizeOverlayExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19320,40 +16122,6 @@ PEGTransformerFactory::FinalizeOverlayExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOverlayArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOverlayArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeOverlayParametersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &for_expression_opt = list_pr.GetChild(4).Cast(); - if (for_expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ForExpression), for_expression_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::FromExpression), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOverlayParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19369,13 +16137,6 @@ PEGTransformerFactory::FinalizeOverlayParametersTrampoline(PEGTransformer &trans return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeFromExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFromExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19384,13 +16145,6 @@ PEGTransformerFactory::FinalizeFromExpressionTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeForExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeForExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19399,18 +16153,6 @@ PEGTransformerFactory::FinalizeForExpressionTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOverlayExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19425,34 +16167,6 @@ PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline(PEGTransformer &t return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeExtractArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExtractArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeExtractDatePartArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ExtractDatePart), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19461,11 +16175,6 @@ PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExtractIdentifierArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19475,11 +16184,6 @@ PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExtractStringArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19489,64 +16193,6 @@ PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExtractDatePartTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExtractDatePartTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeExternalResourceStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExternalResourceStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCreateExternalResourceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &external_resource_creation_options_opt = list_pr.GetChild(4).Cast(); - if (external_resource_creation_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExternalResourceCreationOptions), - external_resource_creation_options_opt.GetResult()}, - 1); - } - auto &attach_alias_opt = list_pr.GetChild(3).Cast(); - if (attach_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AttachAlias), attach_alias_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19565,17 +16211,6 @@ PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline(PEGTransform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRegisterExternalResourceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(5)}, 1); - auto &attach_alias_opt = list_pr.GetChild(3).Cast(); - if (attach_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AttachAlias), attach_alias_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19591,13 +16226,6 @@ PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline(PEGTransfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDestroyExternalResourceStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19606,65 +16234,6 @@ PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeShowExternalResourcesStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &show_all_modifier_opt = list_pr.GetChild(1).Cast(); - if (show_all_modifier_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ShowAllModifier), show_all_modifier_opt.GetResult()}, 0); - } -} - -arena_ptr -PEGTransformerFactory::FinalizeShowExternalResourcesStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - optional show_all_modifier {}; - if (process.child_results[0]) { - show_all_modifier = process.TakeResult(0); - } - auto result = TransformShowExternalResourcesStmt(transformer, show_all_modifier); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeShowAllModifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - -arena_ptr -PEGTransformerFactory::FinalizeShowAllModifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = TransformShowAllModifier(transformer); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeExternalResourceCreationOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::GenericCopyOptionList), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExternalResourceCreationOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeAttachToExternalResourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &attach_options_opt = list_pr.GetChild(4).Cast(); - if (attach_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AttachOptions), attach_options_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::AttachAlias), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ExternalResourceSource), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19679,17 +16248,6 @@ PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeConnectToExternalResourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &attach_options_opt = list_pr.GetChild(3).Cast(); - if (attach_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AttachOptions), attach_options_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ExternalResourceSource), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19702,39 +16260,6 @@ PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExternalResourceSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExternalResourceSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeExternalResourceCreateClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &external_resource_creation_options_opt = list_pr.GetChild(4).Cast(); - if (external_resource_creation_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExternalResourceCreationOptions), - external_resource_creation_options_opt.GetResult()}, - 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19749,13 +16274,6 @@ PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline(PEGTransfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExternalResourceReferenceClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19764,38 +16282,6 @@ PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline(PEGTran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInsertStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(8); - auto &returning_clause_opt = list_pr.GetChild(10).Cast(); - if (returning_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReturningClause), returning_clause_opt.GetResult()}, 7); - } - auto &on_conflict_clause_opt = list_pr.GetChild(9).Cast(); - if (on_conflict_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OnConflictClause), on_conflict_clause_opt.GetResult()}, 6); - } - process.PushChild({transformer.GetRule(PEGRuleId::InsertValues), list_pr.GetChild(8)}, 5); - auto &insert_column_list_opt = list_pr.GetChild(6).Cast(); - if (insert_column_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InsertColumnList), insert_column_list_opt.GetResult()}, 4); - } - auto &by_name_or_position_opt = list_pr.GetChild(5).Cast(); - if (by_name_or_position_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ByNameOrPosition), by_name_or_position_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::InsertTarget), list_pr.GetChild(4)}, 2); - auto &or_action_opt = list_pr.GetChild(2).Cast(); - if (or_action_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrAction), or_action_opt.GetResult()}, 1); - } - auto &with_clause_opt = list_pr.GetChild(0).Cast(); - if (with_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithClause), with_clause_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeInsertStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19836,31 +16322,6 @@ PEGTransformerFactory::FinalizeInsertStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOrActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeOrActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeInsertOrReplaceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertOrReplaceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19868,11 +16329,6 @@ PEGTransformerFactory::FinalizeInsertOrReplaceTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeInsertOrIgnoreTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertOrIgnoreTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19880,71 +16336,12 @@ PEGTransformerFactory::FinalizeInsertOrIgnoreTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeInsertByNameOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::InsertByName), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeInsertByNameOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeInsertByPositionOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::InsertByPosition), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeInsertByPositionOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeInsertByNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertByNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformInsertByName(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeInsertByPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertByPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -19952,17 +16349,6 @@ PEGTransformerFactory::FinalizeInsertByPositionTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeInsertTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &insert_alias_opt = list_pr.GetChild(1).Cast(); - if (insert_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InsertAlias), insert_alias_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto base_table_name = process.TakeResult>(0); @@ -19974,11 +16360,6 @@ PEGTransformerFactory::FinalizeInsertTargetTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInsertAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -19987,18 +16368,6 @@ PEGTransformerFactory::FinalizeInsertAliasTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -20012,13 +16381,6 @@ PEGTransformerFactory::FinalizeColumnListTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeInsertColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColumnList), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20027,33 +16389,6 @@ PEGTransformerFactory::FinalizeInsertColumnListTrampoline(PEGTransformer &transf return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeInsertValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeInsertValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeSelectInsertValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20062,11 +16397,6 @@ PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline(PEGTransformer &tran return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDefaultValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDefaultValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20074,17 +16404,6 @@ PEGTransformerFactory::FinalizeDefaultValuesTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOnConflictClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::OnConflictAction), list_pr.GetChild(3)}, 1); - auto &on_conflict_target_opt = list_pr.GetChild(2).Cast(); - if (on_conflict_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OnConflictTarget), on_conflict_target_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeOnConflictClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20097,38 +16416,6 @@ PEGTransformerFactory::FinalizeOnConflictClauseTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOnConflictTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOnConflictTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeOnConflictExpressionTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &where_clause_opt = list_pr.GetChild(1).Cast(); - if (where_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WhereClause), where_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColumnIdList), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20141,13 +16428,6 @@ PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline(PEGTransform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOnConflictIndexTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ConstraintName), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20156,38 +16436,6 @@ PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOnConflictActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOnConflictActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeOnConflictUpdateTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &where_clause_opt = list_pr.GetChild(4).Cast(); - if (where_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WhereClause), where_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::UpdateSetClauseList), list_pr.GetChild(3)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20200,11 +16448,6 @@ PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOnConflictNothingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOnConflictNothingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20212,13 +16455,6 @@ PEGTransformerFactory::FinalizeOnConflictNothingTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeReturningClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReturningClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20227,21 +16463,6 @@ PEGTransformerFactory::FinalizeReturningClauseTrampoline(PEGTransformer &transfo return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeLoadStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &extension_alias_opt = list_pr.GetChild(3).Cast(); - if (extension_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ExtensionAlias), extension_alias_opt.GetResult()}, 2); - } - auto &from_source_opt = list_pr.GetChild(2).Cast(); - if (from_source_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::FromSource), from_source_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLoadStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20258,11 +16479,6 @@ PEGTransformerFactory::FinalizeLoadStatementTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExtensionAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExtensionAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20272,25 +16488,6 @@ PEGTransformerFactory::FinalizeExtensionAliasTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeInstallStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &version_number_opt = list_pr.GetChild(5).Cast(); - if (version_number_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::VersionNumber), version_number_opt.GetResult()}, 3); - } - auto &from_source_opt = list_pr.GetChild(4).Cast(); - if (from_source_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::FromSource), from_source_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::IdentifierOrStringLiteral), list_pr.GetChild(3)}, 1); - auto &install_and_load_opt = list_pr.GetChild(2).Cast(); - if (install_and_load_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InstallAndLoad), install_and_load_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeInstallStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20316,11 +16513,6 @@ PEGTransformerFactory::FinalizeInstallStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInstallAndLoadTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInstallAndLoadTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20328,11 +16520,6 @@ PEGTransformerFactory::FinalizeInstallAndLoadTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUpdateExtensionsStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20353,31 +16540,6 @@ PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFromSourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFromSourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeFromSourceIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20387,11 +16549,6 @@ PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFromSourceStringTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFromSourceStringTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20401,13 +16558,6 @@ PEGTransformerFactory::FinalizeFromSourceStringTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVersionNumberTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::IdentifierOrStringLiteral), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeVersionNumberTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20416,48 +16566,6 @@ PEGTransformerFactory::FinalizeVersionNumberTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExtensionRepositoryStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeExtensionRepositoryStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCreateExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &repository_public_key_opt = list_pr.GetChild(7).Cast(); - if (repository_public_key_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::RepositoryPublicKey), repository_public_key_opt.GetResult()}, - 4); - } - process.PushChild({transformer.GetRule(PEGRuleId::RepositoryPrefix), list_pr.GetChild(6)}, 3); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(5)}, 2); - auto &if_not_exists_opt = list_pr.GetChild(4).Cast(); - if (if_not_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfNotExists), if_not_exists_opt.GetResult()}, 1); - } - auto &or_replace_opt = list_pr.GetChild(1).Cast(); - if (or_replace_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrReplace), or_replace_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20480,11 +16588,6 @@ PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline(PEGTransf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRepositoryPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20497,11 +16600,6 @@ PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRepositoryPublicKeyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20520,17 +16618,6 @@ PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline(PEGTransformer &tra return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeDropExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(4)}, 1); - auto &if_exists_opt = list_pr.GetChild(3).Cast(); - if (if_exists_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::IfExists), if_exists_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20543,18 +16630,6 @@ PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableMatchRecognizeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &table_alias_opt = list_pr.GetChild(2).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 1); - } - process.PushChild( - {transformer.GetRule(PEGRuleId::MatchRecognizeBody), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20567,20 +16642,6 @@ PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMatchRecognizeBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(0).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::MatchRecognizeClause), repeat_children[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20597,34 +16658,6 @@ PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMatchRecognizeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMatchRecognizeClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeMRPartitionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::WindowPartition), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRPartitionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto window_partition = process.TakeResult>>(0); @@ -20632,13 +16665,6 @@ PEGTransformerFactory::FinalizeMRPartitionTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMROrderByTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OrderByClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMROrderByTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto order_by_clause = process.TakeResult>(0); @@ -20646,13 +16672,6 @@ arena_ptr PEGTransformerFactory::FinalizeMROrderByTrampoli return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRMeasuresTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::MeasuresClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRMeasuresTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto measures_clause = process.TakeResult>>(0); @@ -20660,13 +16679,6 @@ PEGTransformerFactory::FinalizeMRMeasuresTrampoline(PEGTransformer &transformer, return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRRowsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RowsPerMatch), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto rows_per_match = process.TakeResult(0); @@ -20674,13 +16686,6 @@ arena_ptr PEGTransformerFactory::FinalizeMRRowsTrampoline( return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRSkipTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AfterMatchSkip), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRSkipTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto after_match_skip = process.TakeResult(0); @@ -20688,13 +16693,6 @@ arena_ptr PEGTransformerFactory::FinalizeMRSkipTrampoline( return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRPatternTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PatternClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRPatternTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto pattern_clause = process.TakeResult>(0); @@ -20702,13 +16700,6 @@ arena_ptr PEGTransformerFactory::FinalizeMRPatternTrampoli return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRSubsetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SubsetClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRSubsetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto subset_clause = process.TakeResult>(0); @@ -20716,24 +16707,12 @@ arena_ptr PEGTransformerFactory::FinalizeMRSubsetTrampolin return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRDefineAutoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMRDefineAutoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformMRDefineAuto(transformer); return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMRDefineTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::DefineClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMRDefineTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto define_clause = process.TakeResult>>(0); @@ -20741,19 +16720,6 @@ arena_ptr PEGTransformerFactory::FinalizeMRDefineTrampolin return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeMeasuresClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::MeasuresElement), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeMeasuresClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20768,14 +16734,6 @@ PEGTransformerFactory::FinalizeMeasuresClauseTrampoline(PEGTransformer &transfor return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeMeasuresElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMeasuresElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20785,32 +16743,6 @@ PEGTransformerFactory::FinalizeMeasuresElementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMeasureSemanticsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMeasureSemanticsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeRunningSemanticsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRunningSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20818,11 +16750,6 @@ PEGTransformerFactory::FinalizeRunningSemanticsTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFinalSemanticsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFinalSemanticsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20830,31 +16757,6 @@ PEGTransformerFactory::FinalizeFinalSemanticsTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRowsPerMatchTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRowsPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeOneRowPerMatchTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20862,17 +16764,6 @@ PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAllRowsPerMatchTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &all_rows_empty_matches_opt = list_pr.GetChild(4).Cast(); - if (all_rows_empty_matches_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AllRowsEmptyMatches), all_rows_empty_matches_opt.GetResult()}, - 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20884,32 +16775,6 @@ PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAllRowsEmptyMatchesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAllRowsEmptyMatchesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeShowEmptyMatchesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeShowEmptyMatchesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20917,11 +16782,6 @@ PEGTransformerFactory::FinalizeShowEmptyMatchesTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOmitEmptyMatchesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOmitEmptyMatchesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20929,11 +16789,6 @@ PEGTransformerFactory::FinalizeOmitEmptyMatchesTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeWithUnmatchedRowsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20941,46 +16796,6 @@ PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAfterMatchSkipTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AfterMatchSkipTarget), list_pr.GetChild(3)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAfterMatchSkipTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeAfterMatchSkipTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAfterMatchSkipTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeSkipToNextRowTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSkipToNextRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -20988,11 +16803,6 @@ PEGTransformerFactory::FinalizeSkipToNextRowTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSkipPastLastRowTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21000,13 +16810,6 @@ PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSkipToFirstVarTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21015,13 +16818,6 @@ PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSkipToLastVarTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSkipToLastVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21030,13 +16826,6 @@ PEGTransformerFactory::FinalizeSkipToLastVarTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSkipToVarTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSkipToVarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_label_or_string = process.TakeResult(0); @@ -21044,41 +16833,6 @@ arena_ptr PEGTransformerFactory::FinalizeSkipToVarTrampoli return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePatternClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RowPattern), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePatternClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRowPatternTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::RowPatternAlternative), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::RowPatternTerm), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -21103,34 +16857,6 @@ PEGTransformerFactory::FinalizeRowPatternTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternAlternativeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RowPatternTerm), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRowPatternAlternativeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRowPatternTermTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(0).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::RowPatternFactor), repeat_children[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternTermTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21147,18 +16873,6 @@ PEGTransformerFactory::FinalizeRowPatternTermTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternFactorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &row_pattern_quantifier_opt = list_pr.GetChild(1).Cast(); - if (row_pattern_quantifier_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::RowPatternQuantifier), row_pattern_quantifier_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::RowPatternPrimary), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternFactorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21171,39 +16885,6 @@ PEGTransformerFactory::FinalizeRowPatternFactorTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternPrimaryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRowPatternPrimaryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRowPatternPermuteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(1))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::RowPattern), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21214,70 +16895,20 @@ PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline(PEGTransformer &trans for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { row_pattern.push_back(process.TakeResult>(i)); } - auto result = TransformRowPatternPermute(transformer, std::move(row_pattern)); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRowPatternAnchorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRowPatternAnchorTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializePatternStartTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - -arena_ptr -PEGTransformerFactory::FinalizePatternStartTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = TransformPatternStart(transformer); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializePatternEndTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - -arena_ptr -PEGTransformerFactory::FinalizePatternEndTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = TransformPatternEnd(transformer); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeRowPatternGroupTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RowPattern), ExtractResultFromParens(list_pr.GetChild(0))}, 0); + auto result = TransformRowPatternPermute(transformer, std::move(row_pattern)); + return transformer.MakeResult>(std::move(result)); } arena_ptr -PEGTransformerFactory::FinalizeRowPatternGroupTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); +PEGTransformerFactory::FinalizePatternStartTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { + auto result = TransformPatternStart(transformer); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternEmptyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); +arena_ptr +PEGTransformerFactory::FinalizePatternEndTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { + auto result = TransformPatternEnd(transformer); + return transformer.MakeResult>(std::move(result)); } arena_ptr @@ -21287,13 +16918,6 @@ PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternExclusionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::RowPattern), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21302,13 +16926,6 @@ PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternLabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternLabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21317,18 +16934,6 @@ PEGTransformerFactory::FinalizeRowPatternLabelTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRowPatternQuantifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &quantifier_reluctant_opt = list_pr.GetChild(1).Cast(); - if (quantifier_reluctant_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::QuantifierReluctant), quantifier_reluctant_opt.GetResult()}, - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::RowPatternQuantifierKind), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21341,32 +16946,6 @@ PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRowPatternQuantifierKindTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeRowPatternQuantifierKindTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeQuantifierReluctantTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierReluctantTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21374,11 +16953,6 @@ PEGTransformerFactory::FinalizeQuantifierReluctantTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierStarTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierStarTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21386,11 +16960,6 @@ PEGTransformerFactory::FinalizeQuantifierStarTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierPlusTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierPlusTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21398,11 +16967,6 @@ PEGTransformerFactory::FinalizeQuantifierPlusTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierOptionalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21410,46 +16974,6 @@ PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline(PEGTransformer &tran return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierRangeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::QuantifierBounds), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeQuantifierRangeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeQuantifierBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeQuantifierBoundsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeQuantifierMinMaxTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierMinMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21460,11 +16984,6 @@ PEGTransformerFactory::FinalizeQuantifierMinMaxTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierMinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierMinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21474,11 +16993,6 @@ PEGTransformerFactory::FinalizeQuantifierMinTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierMaxTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierMaxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21488,11 +17002,6 @@ PEGTransformerFactory::FinalizeQuantifierMaxTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQuantifierExactTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeQuantifierExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21502,18 +17011,6 @@ PEGTransformerFactory::FinalizeQuantifierExactTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSubsetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SubsetElement), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeSubsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -21527,20 +17024,6 @@ PEGTransformerFactory::FinalizeSubsetClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSubsetElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(2))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_items[child_idx].get()}, - 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSubsetElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21556,18 +17039,6 @@ PEGTransformerFactory::FinalizeSubsetElementTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDefineClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::DefineElement), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeDefineClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -21581,14 +17052,6 @@ PEGTransformerFactory::FinalizeDefineClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeDefineElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeDefineElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21598,32 +17061,6 @@ PEGTransformerFactory::FinalizeDefineElementTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMergeIntoStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(6).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(6 + dynamic_child_count - 1); - auto &returning_clause_opt = list_pr.GetChild(7).Cast(); - if (returning_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReturningClause), returning_clause_opt.GetResult()}, - 5 + dynamic_child_count - 1); - } - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::MergeMatch), repeat_children[child_idx].get()}, - 4 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::JoinQualifier), list_pr.GetChild(5)}, 3); - process.PushChild({transformer.GetRule(PEGRuleId::MergeIntoUsingClause), list_pr.GetChild(4)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::TargetOptAlias), list_pr.GetChild(3)}, 1); - auto &with_clause_opt = list_pr.GetChild(0).Cast(); - if (with_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithClause), with_clause_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21653,13 +17090,6 @@ PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMergeIntoUsingClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21668,37 +17098,6 @@ PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeMergeMatchTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMergeMatchTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>>(0); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeMatchedClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::MatchedClauseAction), list_pr.GetChild(4)}, 1); - auto &and_expression_opt = list_pr.GetChild(2).Cast(); - if (and_expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AndExpression), and_expression_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeMatchedClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21711,37 +17110,6 @@ PEGTransformerFactory::FinalizeMatchedClauseTrampoline(PEGTransformer &transform return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeMatchedClauseActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeMatchedClauseActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeUpdateMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &update_match_info_opt = list_pr.GetChild(1).Cast(); - if (update_match_info_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::UpdateMatchInfo), update_match_info_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21753,34 +17121,6 @@ PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateMatchInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeUpdateMatchInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeUpdateMatchSetActionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::UpdateMatchSetClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21789,13 +17129,6 @@ PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ByNameOrPosition), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21804,11 +17137,6 @@ PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDeleteMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21816,16 +17144,6 @@ PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInsertMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &insert_match_info_opt = list_pr.GetChild(1).Cast(); - if (insert_match_info_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InsertMatchInfo), insert_match_info_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21837,32 +17155,6 @@ PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInsertMatchInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeInsertMatchInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeInsertDefaultValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21870,16 +17162,6 @@ PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInsertByNameOrPositionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &by_name_or_position_opt = list_pr.GetChild(0).Cast(); - if (by_name_or_position_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ByNameOrPosition), by_name_or_position_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21895,22 +17177,6 @@ PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeInsertValuesListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(2))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 1 + child_idx); - } - auto &insert_column_list_opt = list_pr.GetChild(0).Cast(); - if (insert_column_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::InsertColumnList), insert_column_list_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeInsertValuesListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -21929,26 +17195,11 @@ PEGTransformerFactory::FinalizeInsertValuesListTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeDoNothingMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = TransformDoNothingMatchClause(transformer); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeErrorMatchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &expression_opt = list_pr.GetChild(1).Cast(); - if (expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Expression), expression_opt.GetResult()}, 0); - } + GeneratedTransformProcess &process) { + auto result = TransformDoNothingMatchClause(transformer); + return transformer.MakeResult>(std::move(result)); } arena_ptr @@ -21962,37 +17213,6 @@ PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateMatchSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::UpdateMatchSetInfo), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeUpdateMatchSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeUpdateMatchSetInfoTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && (choice_result.Name() == "StarSymbol")) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22003,13 +17223,6 @@ PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAndExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAndExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22018,21 +17231,6 @@ PEGTransformerFactory::FinalizeAndExpressionTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNotMatchedClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::MatchedClauseAction), list_pr.GetChild(6)}, 2); - auto &and_expression_opt = list_pr.GetChild(4).Cast(); - if (and_expression_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AndExpression), and_expression_opt.GetResult()}, 1); - } - auto &by_source_or_target_opt = list_pr.GetChild(3).Cast(); - if (by_source_or_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::BySourceOrTarget), by_source_or_target_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22050,56 +17248,18 @@ PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline(PEGTransformer &transf return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeBySourceOrTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeBySourceOrTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeBySourceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeBySourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformBySource(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeByTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeByTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformByTarget(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePivotOnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PivotColumnList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotOnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto pivot_column_list = process.TakeResult>(0); @@ -22107,13 +17267,6 @@ arena_ptr PEGTransformerFactory::FinalizePivotOnTrampoline return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePivotUsingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotUsingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto target_list = process.TakeResult>>(0); @@ -22121,19 +17274,6 @@ PEGTransformerFactory::FinalizePivotUsingTrampoline(PEGTransformer &transformer, return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializePivotColumnListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::PivotColumnEntry), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizePivotColumnListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22148,34 +17288,6 @@ PEGTransformerFactory::FinalizePivotColumnListTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePivotColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePivotColumnEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializePivotColumnExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22184,15 +17296,6 @@ PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePivotColumnSubqueryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(2))}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::BaseExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22203,14 +17306,6 @@ PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline(PEGTransformer &tra return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeIntoNameValuesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::OptionalParensNameList), list_pr.GetChild(4)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIntoNameValuesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22220,39 +17315,6 @@ PEGTransformerFactory::FinalizeIntoNameValuesTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOptionalParensNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOptionalParensNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeParenthesizedNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22267,18 +17329,6 @@ PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline(PEGTransformer &t return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeBareNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeBareNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -22292,77 +17342,18 @@ PEGTransformerFactory::FinalizeBareNameListTrampoline(PEGTransformer &transforme return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeIncludeOrExcludeNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeIncludeOrExcludeNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeIncludeNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeIncludeNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformIncludeNulls(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeExcludeNullsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeExcludeNullsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformExcludeNulls(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUnpivotHeaderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeUnpivotHeaderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeUnpivotHeaderSingleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22371,18 +17362,6 @@ PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline(PEGTransformer &tra return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeUnpivotHeaderListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22397,13 +17376,6 @@ PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline(PEGTransformer &trans return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializePragmaStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PragmaAssignOrFunction), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePragmaStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22412,34 +17384,6 @@ PEGTransformerFactory::FinalizePragmaStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePragmaAssignOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePragmaAssignOrFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializePragmaAssignTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::VariableList), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePragmaAssignTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -22449,16 +17393,6 @@ PEGTransformerFactory::FinalizePragmaAssignTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePragmaFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &pragma_parameters_opt = list_pr.GetChild(1).Cast(); - if (pragma_parameters_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::PragmaParameters), pragma_parameters_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizePragmaFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22472,18 +17406,6 @@ PEGTransformerFactory::FinalizePragmaFunctionTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePragmaParametersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizePragmaParametersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22498,18 +17420,6 @@ PEGTransformerFactory::FinalizePragmaParametersTrampoline(PEGTransformer &transf return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializePrepareStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::Statement), list_pr.GetChild(4)}, 2); - auto &type_list_opt = list_pr.GetChild(2).Cast(); - if (type_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TypeList), type_list_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePrepareStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22523,18 +17433,6 @@ PEGTransformerFactory::FinalizePrepareStatementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTypeListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Type), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeTypeListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -22548,13 +17446,6 @@ arena_ptr PEGTransformerFactory::FinalizeTypeListTrampolin return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeSelectStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SelectStatementInternal), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22563,27 +17454,6 @@ PEGTransformerFactory::FinalizeSelectStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSelectSetOpChainTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SelectSetOpChainTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::IntersectChain), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22611,42 +17481,13 @@ PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSelectSetOpChainTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::IntersectChain), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::SetopClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto setop_clause = process.TakeResult>(0); - auto intersect_chain = process.TakeResult>(1); - auto result = TransformSelectSetOpChainTail(transformer, std::move(setop_clause), std::move(intersect_chain)); - return transformer.MakeResult, unique_ptr>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeIntersectChainTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::IntersectChainTail), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SelectAtom), list_pr.GetChild(0)}, 0); + auto intersect_chain = process.TakeResult>(1); + auto result = TransformSelectSetOpChainTail(transformer, std::move(setop_clause), std::move(intersect_chain)); + return transformer.MakeResult, unique_ptr>>(std::move(result)); } arena_ptr @@ -22675,14 +17516,6 @@ PEGTransformerFactory::FinalizeIntersectChainTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeIntersectChainTailTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SelectAtom), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::SetIntersectClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeIntersectChainTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22692,16 +17525,6 @@ PEGTransformerFactory::FinalizeIntersectChainTailTrampoline(PEGTransformer &tran return transformer.MakeResult, unique_ptr>>(std::move(result)); } -void PEGTransformerFactory::InitializeSetIntersectClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &distinct_or_all_opt = list_pr.GetChild(1).Cast(); - if (distinct_or_all_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DistinctOrAll), distinct_or_all_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22713,34 +17536,6 @@ PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSelectAtomTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSelectAtomTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSelectParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto select_statement_internal = process.TakeResult>(0); @@ -22748,17 +17543,6 @@ PEGTransformerFactory::FinalizeSelectParensTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetopClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &distinct_or_all_opt = list_pr.GetChild(1).Cast(); - if (distinct_or_all_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DistinctOrAll), distinct_or_all_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SetopType), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSetopClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -22774,83 +17558,18 @@ PEGTransformerFactory::FinalizeSetopClauseTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetopTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeSetopTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSetopUnionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSetopUnionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSetopUnion(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSetopExceptTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSetopExceptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSetopExcept(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSelectStatementTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSelectStatementTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeResultModifiersTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &limit_offset_opt = list_pr.GetChild(1).Cast(); - if (limit_offset_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::LimitOffset), limit_offset_opt.GetResult()}, 1); - } - auto &order_by_clause_opt = list_pr.GetChild(0).Cast(); - if (order_by_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OrderByClause), order_by_clause_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeResultModifiersTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22866,37 +17585,6 @@ PEGTransformerFactory::FinalizeResultModifiersTrampoline(PEGTransformer &transfo return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeLimitOffsetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeLimitOffsetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeLimitOffsetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &offset_clause_opt = list_pr.GetChild(1).Cast(); - if (offset_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OffsetClause), offset_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::LimitClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22909,17 +17597,6 @@ PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOffsetLimitClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &limit_clause_opt = list_pr.GetChild(1).Cast(); - if (limit_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::LimitClause), limit_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::OffsetClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22932,14 +17609,6 @@ PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOffsetFetchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::FetchClause), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::OffsetClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22949,14 +17618,6 @@ PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFetchOffsetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::OffsetClause), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::FetchClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22966,13 +17627,6 @@ PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFetchOnlyClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::FetchClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22981,13 +17635,6 @@ PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -22996,34 +17643,6 @@ PEGTransformerFactory::FinalizeTableStatementTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOptionalParensSimpleSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOptionalParensSimpleSelectTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSimpleSelectParensTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SimpleSelect), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23032,37 +17651,6 @@ PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSelectFromTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSelectFromTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSelectFromClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &from_clause_opt = list_pr.GetChild(1).Cast(); - if (from_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::FromClause), from_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SelectClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectFromClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23075,17 +17663,6 @@ PEGTransformerFactory::FinalizeSelectFromClauseTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFromSelectClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &select_clause_opt = list_pr.GetChild(1).Cast(); - if (select_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SelectClause), select_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::FromClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeFromSelectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23098,26 +17675,6 @@ PEGTransformerFactory::FinalizeFromSelectClauseTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWithStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - process.PushChild({transformer.GetRule(PEGRuleId::CTEBody), list_pr.GetChild(5)}, 4); - auto &materialized_opt = list_pr.GetChild(4).Cast(); - if (materialized_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Materialized), materialized_opt.GetResult()}, 3); - } - auto &using_key_opt = list_pr.GetChild(2).Cast(); - if (using_key_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::UsingKey), using_key_opt.GetResult()}, 2); - } - auto &column_aliases_opt = list_pr.GetChild(1).Cast(); - if (column_aliases_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ColumnAliases), column_aliases_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWithStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23140,34 +17697,6 @@ PEGTransformerFactory::FinalizeWithStatementTrampoline(PEGTransformer &transform return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeCTEBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeCTEBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeCTESelectBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCTESelectBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23176,13 +17705,6 @@ PEGTransformerFactory::FinalizeCTESelectBodyTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCTEDMLBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Statement), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto statement = process.TakeResult>(0); @@ -23190,13 +17712,6 @@ PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUsingKeyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), ExtractResultFromParens(list_pr.GetChild(2))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUsingKeyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto target_list = process.TakeResult>>(0); @@ -23204,11 +17719,6 @@ arena_ptr PEGTransformerFactory::FinalizeUsingKeyTrampolin return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeMaterializedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeMaterializedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -23219,20 +17729,6 @@ PEGTransformerFactory::FinalizeMaterializedTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSelectClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &target_list_opt = list_pr.GetChild(2).Cast(); - if (target_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), target_list_opt.GetResult()}, 1); - } - auto &distinct_clause_opt = list_pr.GetChild(1).Cast(); - if (distinct_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DistinctClause), distinct_clause_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSelectClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional distinct_clause {}; @@ -23247,19 +17743,6 @@ PEGTransformerFactory::FinalizeSelectClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTargetListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::AliasedExpression), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -23269,60 +17752,22 @@ PEGTransformerFactory::FinalizeTargetListTrampoline(PEGTransformer &transformer, for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { aliased_expression.push_back(process.TakeResult>(i)); } - auto result = TransformTargetList(transformer, std::move(aliased_expression)); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeColumnAliasesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 0 + child_idx); - } -} - -arena_ptr -PEGTransformerFactory::FinalizeColumnAliasesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto dynamic_child_count = CountParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - vector col_id_or_string; - col_id_or_string.reserve(dynamic_child_count); - for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { - col_id_or_string.push_back(process.TakeResult(i)); - } - auto result = TransformColumnAliases(transformer, col_id_or_string); - return transformer.MakeResult>(result); -} - -void PEGTransformerFactory::InitializeDistinctClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); + auto result = TransformTargetList(transformer, std::move(aliased_expression)); + return transformer.MakeResult>>(std::move(result)); } arena_ptr -PEGTransformerFactory::FinalizeDistinctClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeDistinctAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); +PEGTransformerFactory::FinalizeColumnAliasesTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + auto dynamic_child_count = CountParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); + vector col_id_or_string; + col_id_or_string.reserve(dynamic_child_count); + for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { + col_id_or_string.push_back(process.TakeResult(i)); + } + auto result = TransformColumnAliases(transformer, col_id_or_string); + return transformer.MakeResult>(result); } arena_ptr @@ -23331,16 +17776,6 @@ PEGTransformerFactory::FinalizeDistinctAllTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDistinctOnTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &distinct_on_targets_opt = list_pr.GetChild(1).Cast(); - if (distinct_on_targets_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DistinctOnTargets), distinct_on_targets_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeDistinctOnTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional>> distinct_on_targets {}; @@ -23351,18 +17786,6 @@ PEGTransformerFactory::FinalizeDistinctOnTrampoline(PEGTransformer &transformer, return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDistinctOnTargetsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(1))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23377,50 +17800,6 @@ PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline(PEGTransformer &trans return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeInnerTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeInnerTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeTableSubqueryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &sample_clause_opt = list_pr.GetChild(4).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 4); - } - auto &table_alias_opt = list_pr.GetChild(3).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::SubqueryReference), list_pr.GetChild(2)}, 2); - auto &lateral_opt = list_pr.GetChild(1).Cast(); - if (lateral_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Lateral), lateral_opt.GetResult()}, 1); - } - auto &table_alias_colon_opt = list_pr.GetChild(0).Cast(); - if (table_alias_colon_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAliasColon), table_alias_colon_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeTableSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23446,29 +17825,6 @@ PEGTransformerFactory::FinalizeTableSubqueryTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBaseTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &sample_clause_opt = list_pr.GetChild(4).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 4); - } - auto &at_clause_opt = list_pr.GetChild(3).Cast(); - if (at_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AtClause), at_clause_opt.GetResult()}, 3); - } - auto &table_alias_opt = list_pr.GetChild(2).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(1)}, 1); - auto &table_alias_colon_opt = list_pr.GetChild(0).Cast(); - if (table_alias_colon_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAliasColon), table_alias_colon_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeBaseTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional table_alias_colon {}; @@ -23493,13 +17849,6 @@ PEGTransformerFactory::FinalizeBaseTableRefTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableAliasColonTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableAliasColonTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23508,25 +17857,6 @@ PEGTransformerFactory::FinalizeTableAliasColonTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeValuesRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &sample_clause_opt = list_pr.GetChild(3).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 3); - } - auto &table_alias_opt = list_pr.GetChild(2).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::ValuesClause), list_pr.GetChild(1)}, 1); - auto &table_alias_colon_opt = list_pr.GetChild(0).Cast(); - if (table_alias_colon_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAliasColon), table_alias_colon_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeValuesRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional table_alias_colon {}; @@ -23547,25 +17877,6 @@ arena_ptr PEGTransformerFactory::FinalizeValuesRefTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeParensTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &sample_clause_opt = list_pr.GetChild(3).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 3); - } - auto &table_alias_opt = list_pr.GetChild(2).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), ExtractResultFromParens(list_pr.GetChild(1))}, 1); - auto &table_alias_colon_opt = list_pr.GetChild(0).Cast(); - if (table_alias_colon_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAliasColon), table_alias_colon_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23587,38 +17898,6 @@ PEGTransformerFactory::FinalizeParensTableRefTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeJoinOrPivotTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeJoinOrPivotTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeTablePivotClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &table_alias_opt = list_pr.GetChild(2).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 1); - } - process.PushChild( - {transformer.GetRule(PEGRuleId::TablePivotClauseBody), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTablePivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23631,26 +17910,6 @@ PEGTransformerFactory::FinalizeTablePivotClauseTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTablePivotClauseBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(2).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(3 + dynamic_child_count - 1); - auto &pivot_group_by_list_opt = list_pr.GetChild(3).Cast(); - if (pivot_group_by_list_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::PivotGroupByList), pivot_group_by_list_opt.GetResult()}, - 2 + dynamic_child_count - 1); - } - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::PivotValueList), repeat_children[child_idx].get()}, - 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23673,13 +17932,6 @@ PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePivotGroupByListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OptionalParensNameList), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotGroupByListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23688,23 +17940,6 @@ PEGTransformerFactory::FinalizePivotGroupByListTrampoline(PEGTransformer &transf return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeTableUnpivotClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &table_alias_opt = list_pr.GetChild(3).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 2); - } - process.PushChild( - {transformer.GetRule(PEGRuleId::TableUnpivotClauseBody), ExtractResultFromParens(list_pr.GetChild(2))}, 1); - auto &include_or_exclude_nulls_opt = list_pr.GetChild(1).Cast(); - if (include_or_exclude_nulls_opt.HasResult()) { - process.PushChild( - {transformer.GetRule(PEGRuleId::IncludeOrExcludeNulls), include_or_exclude_nulls_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23722,21 +17957,6 @@ PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableUnpivotClauseBodyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(2).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::UnpivotValueList), repeat_children[child_idx].get()}, - 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::UnpivotHeader), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23754,13 +17974,6 @@ PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePivotHeaderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::BaseExpression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotHeaderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto base_expression = process.TakeResult>(0); @@ -23768,14 +17981,6 @@ PEGTransformerFactory::FinalizePivotHeaderTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializePivotValueListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::PivotValueTarget), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::PivotHeader), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotValueListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23785,32 +17990,6 @@ PEGTransformerFactory::FinalizePivotValueListTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePivotValueTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizePivotValueTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializePivotEnumTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePivotEnumTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23820,13 +17999,6 @@ PEGTransformerFactory::FinalizePivotEnumTargetTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePivotListTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::PivotTargetList), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotListTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23835,14 +18007,6 @@ PEGTransformerFactory::FinalizePivotListTargetTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeUnpivotValueListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::UnpivotTargetList), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::UnpivotHeader), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUnpivotValueListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23852,13 +18016,6 @@ PEGTransformerFactory::FinalizeUnpivotValueListTrampoline(PEGTransformer &transf return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePivotTargetListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePivotTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23867,13 +18024,6 @@ PEGTransformerFactory::FinalizePivotTargetListTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUnpivotTargetListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::TargetList), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23882,43 +18032,12 @@ PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLateralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLateralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformLateral(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeUnqualifiedBaseTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeUnqualifiedBaseTableNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23928,34 +18047,6 @@ PEGTransformerFactory::FinalizeUnqualifiedBaseTableNameTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeQualifiedTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeQualifiedTableNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSchemaReservedTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaReservedTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -23966,22 +18057,6 @@ PEGTransformerFactory::FinalizeSchemaReservedTableTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCatalogReservedSchemaTableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_pr = list_pr.GetChild(1).Cast(); - auto repeat_children = repeat_pr.GetChildren(); - auto dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild( - {transformer.GetRule(PEGRuleId::ReservedSchemaQualification), repeat_children[child_idx].get()}, - 1 + child_idx); - } - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaTableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24001,51 +18076,6 @@ PEGTransformerFactory::FinalizeCatalogReservedSchemaTableTrampoline(PEGTransform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeTableFunctionLateralOptTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(6); - auto &sample_clause_opt = list_pr.GetChild(5).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 5); - } - auto &table_alias_opt = list_pr.GetChild(4).Cast(); - if (table_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::TableAlias), table_alias_opt.GetResult()}, 4); - } - auto &with_ordinality_opt = list_pr.GetChild(3).Cast(); - if (with_ordinality_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithOrdinality), with_ordinality_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableFunctionArguments), list_pr.GetChild(2)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTableFunction), list_pr.GetChild(1)}, 1); - auto &lateral_opt = list_pr.GetChild(0).Cast(); - if (lateral_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Lateral), lateral_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24073,23 +18103,6 @@ PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeTableFunctionAliasColonTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - auto &sample_clause_opt = list_pr.GetChild(4).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 4); - } - auto &with_ordinality_opt = list_pr.GetChild(3).Cast(); - if (with_ordinality_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithOrdinality), with_ordinality_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableFunctionArguments), list_pr.GetChild(2)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTableFunction), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::TableAliasColon), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24107,12 +18120,7 @@ PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline(PEGTransformer auto result = TransformTableFunctionAliasColon(transformer, table_alias_colon, qualified_table_function, std::move(table_function_arguments), with_ordinality, std::move(sample_clause)); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeWithOrdinalityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); + return transformer.MakeResult>(std::move(result)); } arena_ptr @@ -24122,31 +18130,6 @@ PEGTransformerFactory::FinalizeWithOrdinalityTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeQualifiedTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SchemaQualification), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - auto &catalog_qualification_opt = list_pr.GetChild(0).Cast(); - if (catalog_qualification_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::CatalogQualification), catalog_qualification_opt.GetResult()}, - 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24177,25 +18160,6 @@ PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTableFunctionArgumentsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = ExtractResultFromParens(list_pr.GetChild(0)).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::FunctionArgument), list_items[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24219,35 +18183,6 @@ PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeNamedFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::TypeFuncName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24257,13 +18192,6 @@ PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializePositionalFunctionArgumentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24272,18 +18200,6 @@ PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline(PEGTransform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeNamedParameterTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(3)}, 2); - auto &type_opt = list_pr.GetChild(1).Cast(); - if (type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Type), type_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TypeFuncName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNamedParameterTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24297,37 +18213,6 @@ PEGTransformerFactory::FinalizeNamedParameterTrampoline(PEGTransformer &transfor return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeTableAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeTableAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeTableAliasAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &column_aliases_opt = list_pr.GetChild(2).Cast(); - if (column_aliases_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ColumnAliases), column_aliases_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::IdentifierOrStringLiteral), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeTableAliasAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto identifier_or_string_literal = process.TakeResult(0); @@ -24339,16 +18224,6 @@ PEGTransformerFactory::FinalizeTableAliasAsTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTableAliasWithoutAsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &column_aliases_opt = list_pr.GetChild(1).Cast(); - if (column_aliases_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ColumnAliases), column_aliases_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24362,13 +18237,6 @@ PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAtClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AtSpecifier), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAtClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto at_specifier = process.TakeResult>(0); @@ -24376,14 +18244,6 @@ arena_ptr PEGTransformerFactory::FinalizeAtClauseTrampolin return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAtSpecifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::AtUnit), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAtSpecifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto at_unit = process.TakeResult(0); @@ -24392,24 +18252,6 @@ PEGTransformerFactory::FinalizeAtSpecifierTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAtUnitTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -24433,11 +18275,6 @@ arena_ptr PEGTransformerFactory::FinalizeAtUnitTrampoline( return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVersionAtUnitTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeVersionAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24445,11 +18282,6 @@ PEGTransformerFactory::FinalizeVersionAtUnitTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeTimestampAtUnitTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeTimestampAtUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24457,64 +18289,6 @@ PEGTransformerFactory::FinalizeTimestampAtUnitTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeJoinClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeJoinClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeNearestJoinClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeNearestJoinClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeNearestJoinAliasedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(8)}, 4); - process.PushChild({transformer.GetRule(PEGRuleId::DistanceOrSimilarity), list_pr.GetChild(7)}, 3); - auto &approx_or_exact_opt = list_pr.GetChild(3).Cast(); - if (approx_or_exact_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ApproxOrExact), approx_or_exact_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), list_pr.GetChild(2)}, 1); - auto &join_type_opt = list_pr.GetChild(0).Cast(); - if (join_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::JoinType), join_type_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24540,23 +18314,6 @@ PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNearestJoinBareTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(5); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(8)}, 4); - process.PushChild({transformer.GetRule(PEGRuleId::DistanceOrSimilarity), list_pr.GetChild(7)}, 3); - auto &approx_or_exact_opt = list_pr.GetChild(3).Cast(); - if (approx_or_exact_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ApproxOrExact), approx_or_exact_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::NearestBareTableRef), list_pr.GetChild(2)}, 1); - auto &join_type_opt = list_pr.GetChild(0).Cast(); - if (join_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::JoinType), join_type_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNearestJoinBareTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24582,34 +18339,6 @@ PEGTransformerFactory::FinalizeNearestJoinBareTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNearestBareTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeNearestBareTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeNearestValuesRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ValuesClause), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestValuesRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24618,22 +18347,6 @@ PEGTransformerFactory::FinalizeNearestValuesRefTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNearestTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &with_ordinality_opt = list_pr.GetChild(3).Cast(); - if (with_ordinality_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithOrdinality), with_ordinality_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableFunctionArguments), list_pr.GetChild(2)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::QualifiedTableFunction), list_pr.GetChild(1)}, 1); - auto &lateral_opt = list_pr.GetChild(0).Cast(); - if (lateral_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Lateral), lateral_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24652,17 +18365,6 @@ PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNearestTableSubqueryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SubqueryReference), list_pr.GetChild(1)}, 1); - auto &lateral_opt = list_pr.GetChild(0).Cast(); - if (lateral_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Lateral), lateral_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24675,21 +18377,6 @@ PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNearestBaseTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &sample_clause_opt = list_pr.GetChild(2).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 2); - } - auto &at_clause_opt = list_pr.GetChild(1).Cast(); - if (at_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AtClause), at_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24707,17 +18394,6 @@ PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeNearestParensTableRefTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &sample_clause_opt = list_pr.GetChild(1).Cast(); - if (sample_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleClause), sample_clause_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24730,32 +18406,6 @@ PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeApproxOrExactTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeApproxOrExactTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeNearestApproxTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestApproxTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24763,43 +18413,12 @@ PEGTransformerFactory::FinalizeNearestApproxTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNearestExactTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestExactTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNearestExact(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDistanceOrSimilarityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeDistanceOrSimilarityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeNearestDistanceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestDistanceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24807,11 +18426,6 @@ PEGTransformerFactory::FinalizeNearestDistanceTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNearestSimilarityTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNearestSimilarityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24819,22 +18433,6 @@ PEGTransformerFactory::FinalizeNearestSimilarityTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRegularJoinClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - process.PushChild({transformer.GetRule(PEGRuleId::JoinQualifier), list_pr.GetChild(4)}, 3); - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), list_pr.GetChild(3)}, 2); - auto &join_type_opt = list_pr.GetChild(1).Cast(); - if (join_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::JoinType), join_type_opt.GetResult()}, 1); - } - auto &asof_opt = list_pr.GetChild(0).Cast(); - if (asof_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Asof), asof_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -24853,17 +18451,6 @@ PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeJoinByClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - process.PushChild({transformer.GetRule(PEGRuleId::JoinQualifier), list_pr.GetChild(4)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), list_pr.GetChild(3)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabel), - ExtractResultFromParens(list_pr.GetChild(2)).Cast().GetChild(1)}, - 0); -} - arena_ptr PEGTransformerFactory::FinalizeJoinByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto col_label = process.TakeResult(0); @@ -24873,22 +18460,10 @@ PEGTransformerFactory::FinalizeJoinByClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeAsofTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAsofTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = TransformAsof(transformer); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeJoinWithoutOnClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::InnerTableRef), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::JoinPrefix), list_pr.GetChild(0)}, 0); + auto result = TransformAsof(transformer); + return transformer.MakeResult(result); } arena_ptr @@ -24900,34 +18475,6 @@ PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeJoinQualifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeJoinQualifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeOnClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOnClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -24935,19 +18482,6 @@ arena_ptr PEGTransformerFactory::FinalizeOnClauseTrampolin return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeUsingClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(1))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::UsingColumnName), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeUsingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -24961,24 +18495,6 @@ PEGTransformerFactory::FinalizeUsingClauseTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeUsingColumnNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.Name().empty() || choice_result.type == ParseResultType::IDENTIFIER || - choice_result.type == ParseResultType::KEYWORD || choice_result.type == ParseResultType::STRING) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUsingColumnNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25001,51 +18517,6 @@ PEGTransformerFactory::FinalizeUsingColumnNameTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeJoinTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeJoinTypeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeJoinPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeCrossJoinPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25053,16 +18524,6 @@ PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNaturalJoinPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &join_type_opt = list_pr.GetChild(1).Cast(); - if (join_type_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::JoinType), join_type_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25074,11 +18535,6 @@ PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline(PEGTransformer &trans return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializePositionalJoinPrefixTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25086,11 +18542,6 @@ PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline(PEGTransformer &tr return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFullJoinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFullJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25101,11 +18552,6 @@ arena_ptr PEGTransformerFactory::FinalizeFullJoinTrampolin return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeLeftJoinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLeftJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25116,11 +18562,6 @@ arena_ptr PEGTransformerFactory::FinalizeLeftJoinTrampolin return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRightJoinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRightJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25131,51 +18572,24 @@ arena_ptr PEGTransformerFactory::FinalizeRightJoinTrampoli return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSemiJoinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSemiJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSemiJoin(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAntiJoinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAntiJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformAntiJoin(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeInnerJoinTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeInnerJoinTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformInnerJoin(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeFromClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::TableRef), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeFromClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25189,13 +18603,6 @@ PEGTransformerFactory::FinalizeFromClauseTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWhereClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeWhereClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -25203,13 +18610,6 @@ PEGTransformerFactory::FinalizeWhereClauseTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeGroupByClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::GroupByExpressions), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25218,13 +18618,6 @@ PEGTransformerFactory::FinalizeGroupByClauseTrampoline(PEGTransformer &transform return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeHavingClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeHavingClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto expression = process.TakeResult>(0); @@ -25232,13 +18625,6 @@ PEGTransformerFactory::FinalizeHavingClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeQualifyClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeQualifyClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25247,13 +18633,6 @@ PEGTransformerFactory::FinalizeQualifyClauseTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSampleClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SampleEntry), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSampleClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto sample_entry = process.TakeResult>(0); @@ -25261,13 +18640,6 @@ PEGTransformerFactory::FinalizeSampleClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSelectSampleClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SampleEntry), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25276,19 +18648,6 @@ PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeWindowClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::WindowDefinition), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeWindowClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25302,39 +18661,6 @@ PEGTransformerFactory::FinalizeWindowClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSampleEntryTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSampleEntryTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSampleEntryCountTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &sample_properties_opt = list_pr.GetChild(1).Cast(); - if (sample_properties_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleProperties), - ExtractResultFromParens(sample_properties_opt.GetResult())}, - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SampleCount), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSampleEntryCountTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25347,21 +18673,6 @@ PEGTransformerFactory::FinalizeSampleEntryCountTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSampleEntryFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &repeatable_sample_opt = list_pr.GetChild(2).Cast(); - if (repeatable_sample_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::RepeatableSample), repeatable_sample_opt.GetResult()}, 2); - } - process.PushChild({transformer.GetRule(PEGRuleId::SampleCount), ExtractResultFromParens(list_pr.GetChild(1))}, 1); - auto &sample_function_opt = list_pr.GetChild(0).Cast(); - if (sample_function_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleFunction), sample_function_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25379,13 +18690,6 @@ PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSampleFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSampleFunctionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25394,19 +18698,6 @@ PEGTransformerFactory::FinalizeSampleFunctionTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSamplePropertiesTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &sample_seed_opt = list_pr.GetChild(1).Cast(); - if (sample_seed_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleSeed), - sample_seed_opt.GetResult().Cast().GetChild(1)}, - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSamplePropertiesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25419,13 +18710,6 @@ PEGTransformerFactory::FinalizeSamplePropertiesTrampoline(PEGTransformer &transf return transformer.MakeResult>(result); } -void PEGTransformerFactory::InitializeRepeatableSampleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SampleSeed), ExtractResultFromParens(list_pr.GetChild(1))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeRepeatableSampleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25434,11 +18718,6 @@ PEGTransformerFactory::FinalizeRepeatableSampleTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSampleSeedTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSampleSeedTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25447,17 +18726,6 @@ PEGTransformerFactory::FinalizeSampleSeedTrampoline(PEGTransformer &transformer, return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSampleCountTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &sample_unit_opt = list_pr.GetChild(1).Cast(); - if (sample_unit_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SampleUnit), sample_unit_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::SampleValue), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSampleCountTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto sample_value = process.TakeResult>(0); @@ -25469,51 +18737,6 @@ PEGTransformerFactory::FinalizeSampleCountTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSampleValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSampleValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSampleUnitTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSampleUnitTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSamplePercentageTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSamplePercentageTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25521,62 +18744,18 @@ PEGTransformerFactory::FinalizeSamplePercentageTrampoline(PEGTransformer &transf return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSampleRowsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSampleRowsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSampleRows(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGroupByExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeGroupByExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeGroupByAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupByAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformGroupByAll(transformer); return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeGroupByListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::GroupByExpression), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeGroupByListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -25590,34 +18769,6 @@ PEGTransformerFactory::FinalizeGroupByListTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeGroupByExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeGroupByExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeGroupByBaseExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeGroupByBaseExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25626,11 +18777,6 @@ PEGTransformerFactory::FinalizeGroupByBaseExpressionTrampoline(PEGTransformer &t return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeEmptyGroupingItemTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25638,25 +18784,6 @@ PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline(PEGTransformer &trans return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCubeOrRollupClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &list_opt = ExtractResultFromParens(list_pr.GetChild(1)).Cast(); - idx_t dynamic_child_count = 0; - if (list_opt.HasResult()) { - auto list_items = ExtractParseResultsFromList(list_opt.GetResult()); - dynamic_child_count = list_items.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::CubeOrRollup), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25681,24 +18808,6 @@ PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline(PEGTransformer &tran return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeCubeOrRollupTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCubeOrRollupTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -25722,22 +18831,12 @@ PEGTransformerFactory::FinalizeCubeOrRollupTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCubeKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCubeKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformCubeKeyword(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeRollupKeywordTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRollupKeywordTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25745,19 +18844,6 @@ PEGTransformerFactory::FinalizeRollupKeywordTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGroupingSetsClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(2))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::GroupByExpression), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25772,14 +18858,6 @@ PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline(PEGTransformer &tran return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeSubqueryReferenceTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild( - {transformer.GetRule(PEGRuleId::SelectStatementInternal), ExtractResultFromParens(list_pr.GetChild(0))}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25788,21 +18866,6 @@ PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOrderByExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(3); - auto &nulls_first_or_last_opt = list_pr.GetChild(2).Cast(); - if (nulls_first_or_last_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::NullsFirstOrLast), nulls_first_or_last_opt.GetResult()}, 2); - } - auto &desc_or_asc_opt = list_pr.GetChild(1).Cast(); - if (desc_or_asc_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DescOrAsc), desc_or_asc_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOrderByExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25819,31 +18882,6 @@ PEGTransformerFactory::FinalizeOrderByExpressionTrampoline(PEGTransformer &trans return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeDescOrAscTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeDescOrAscTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeDescendingOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDescendingOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25851,11 +18889,6 @@ PEGTransformerFactory::FinalizeDescendingOrderTrampoline(PEGTransformer &transfo return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeAscendingOrderTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeAscendingOrderTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25863,56 +18896,18 @@ PEGTransformerFactory::FinalizeAscendingOrderTrampoline(PEGTransformer &transfor return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNullsFirstOrLastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeNullsFirstOrLastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeNullsFirstTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNullsFirstTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNullsFirst(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNullsLastTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeNullsLastTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformNullsLast(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOrderByClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OrderByExpressions), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOrderByClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25921,40 +18916,6 @@ PEGTransformerFactory::FinalizeOrderByClauseTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOrderByExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeOrderByExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeOrderByExpressionListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::OrderByExpression), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -25969,20 +18930,6 @@ PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline(PEGTransformer &t return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeOrderByAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &nulls_first_or_last_opt = list_pr.GetChild(2).Cast(); - if (nulls_first_or_last_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::NullsFirstOrLast), nulls_first_or_last_opt.GetResult()}, 1); - } - auto &desc_or_asc_opt = list_pr.GetChild(1).Cast(); - if (desc_or_asc_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::DescOrAsc), desc_or_asc_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeOrderByAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional desc_or_asc {}; @@ -25997,13 +18944,6 @@ PEGTransformerFactory::FinalizeOrderByAllTrampoline(PEGTransformer &transformer, return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLimitClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LimitValue), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLimitClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto limit_value = process.TakeResult(0); @@ -26011,13 +18951,6 @@ PEGTransformerFactory::FinalizeLimitClauseTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOffsetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::OffsetValue), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOffsetClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto offset_value = process.TakeResult(0); @@ -26025,13 +18958,6 @@ PEGTransformerFactory::FinalizeOffsetClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeOffsetValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOffsetValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -26043,42 +18969,12 @@ PEGTransformerFactory::FinalizeOffsetValueTrampoline(PEGTransformer &transformer return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeLimitValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeLimitValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeLimitAllTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLimitAllTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformLimitAll(transformer); return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeLimitLiteralPercentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLimitLiteralPercentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26088,13 +18984,6 @@ PEGTransformerFactory::FinalizeLimitLiteralPercentTrampoline(PEGTransformer &tra return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeLimitExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeLimitExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26107,93 +18996,18 @@ PEGTransformerFactory::FinalizeLimitExpressionTrampoline(PEGTransformer &transfo return transformer.MakeResult(std::move(result)); } -void PEGTransformerFactory::InitializeFetchClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFetchClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeFetchClauseWithoutValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformFetchClauseWithoutValue(transformer); return transformer.MakeResult(std::move(result)); } - -void PEGTransformerFactory::InitializeFetchClauseWithValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::FetchValue), list_pr.GetChild(2)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFetchClauseWithValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeFetchValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeFetchValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto expression = process.TakeResult>(0); - auto result = TransformFetchValue(transformer, std::move(expression)); - return transformer.MakeResult(std::move(result)); -} - -void PEGTransformerFactory::InitializeAliasedExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeAliasedExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeColIdExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(0)}, 0); + +arena_ptr +PEGTransformerFactory::FinalizeFetchValueTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { + auto expression = process.TakeResult>(0); + auto result = TransformFetchValue(transformer, std::move(expression)); + return transformer.MakeResult(std::move(result)); } arena_ptr @@ -26205,14 +19019,6 @@ PEGTransformerFactory::FinalizeColIdExpressionTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExpressionAsCollabelTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ColLabelOrString), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26222,13 +19028,6 @@ PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline(PEGTransformer &tr return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeExpressionOptIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26243,19 +19042,6 @@ PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeValuesClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(1)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ValuesExpressions), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeValuesClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -26269,18 +19055,6 @@ PEGTransformerFactory::FinalizeValuesClauseTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeValuesExpressionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeValuesExpressionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26295,33 +19069,6 @@ PEGTransformerFactory::FinalizeValuesExpressionsTrampoline(PEGTransformer &trans return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeSetStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSetStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeSetKeywordStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SetAssignmentOrTimeZone), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26330,13 +19077,6 @@ PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeVariableAssignmentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(3)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeVariableAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26347,34 +19087,6 @@ PEGTransformerFactory::FinalizeVariableAssignmentTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetAssignmentOrTimeZoneTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSetAssignmentOrTimeZoneTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeResetStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ResetTarget), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeResetStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26383,36 +19095,6 @@ PEGTransformerFactory::FinalizeResetStatementTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeResetTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeResetTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeResetTimeZoneTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &setting_scope_opt = list_pr.GetChild(0).Cast(); - if (setting_scope_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SettingScope), setting_scope_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeResetTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26424,13 +19106,6 @@ PEGTransformerFactory::FinalizeResetTimeZoneTrampoline(PEGTransformer &transform return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeResetVariableOrSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::SetVariableOrSetting), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26439,16 +19114,6 @@ PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline(PEGTransformer & return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetSchemaTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &setting_scope_opt = list_pr.GetChild(0).Cast(); - if (setting_scope_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SettingScope), setting_scope_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSetSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -26461,14 +19126,6 @@ arena_ptr PEGTransformerFactory::FinalizeSetSchemaTrampoli return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeStandardAssignmentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::SetAssignment), list_pr.GetChild(1)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::SetVariableOrSetting), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeStandardAssignmentTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26478,38 +19135,6 @@ PEGTransformerFactory::FinalizeStandardAssignmentTrampoline(PEGTransformer &tran return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetVariableOrSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSetVariableOrSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSetTimeZoneTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::ZoneValue), list_pr.GetChild(3)}, 1); - auto &setting_scope_opt = list_pr.GetChild(0).Cast(); - if (setting_scope_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SettingScope), setting_scope_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSetTimeZoneTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { optional setting_scope {}; @@ -26521,53 +19146,18 @@ PEGTransformerFactory::FinalizeSetTimeZoneTrampoline(PEGTransformer &transformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeZoneValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeZoneValueTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeZoneLocalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeZoneLocalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformZoneLocal(transformer); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeZoneDefaultTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeZoneDefaultTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformZoneDefault(transformer); return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeZoneStringLiteralTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeZoneStringLiteralTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26577,11 +19167,6 @@ PEGTransformerFactory::FinalizeZoneStringLiteralTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeZoneIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeZoneIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26591,16 +19176,6 @@ PEGTransformerFactory::FinalizeZoneIdentifierTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeZoneIntervalWithIntervalTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &interval_opt = list_pr.GetChild(2).Cast(); - if (interval_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::Interval), interval_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26614,11 +19189,6 @@ PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline(PEGTransformer return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeZoneIntervalWithPrecisionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26629,16 +19199,6 @@ PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline(PEGTransforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeSetSettingTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &setting_scope_opt = list_pr.GetChild(0).Cast(); - if (setting_scope_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::SettingScope), setting_scope_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeSetSettingTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -26651,13 +19211,6 @@ PEGTransformerFactory::FinalizeSetSettingTrampoline(PEGTransformer &transformer, return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSetVariableTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::VariableScope), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSetVariableTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -26667,11 +19220,6 @@ PEGTransformerFactory::FinalizeSetVariableTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVariableScopeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeVariableScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26679,128 +19227,43 @@ PEGTransformerFactory::FinalizeVariableScopeTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSettingScopeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSettingScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeLocalScopeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeLocalScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformLocalScope(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeSessionScopeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeSessionScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformSessionScope(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeGlobalScopeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeGlobalScopeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformGlobalScope(transformer); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSetAssignmentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::VariableList), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSetAssignmentTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto variable_list = process.TakeResult>>(0); - auto result = TransformSetAssignment(transformer, std::move(variable_list)); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeVariableListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_items[child_idx].get()}, 0 + child_idx); - } -} - -arena_ptr -PEGTransformerFactory::FinalizeVariableListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto dynamic_child_count = CountParseResultsFromList(list_pr.GetChild(0)); - vector> expression; - expression.reserve(dynamic_child_count); - for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { - expression.push_back(process.TakeResult>(i)); - } - auto result = TransformVariableList(transformer, std::move(expression)); - return transformer.MakeResult>>(std::move(result)); -} - -void PEGTransformerFactory::InitializeTransactionStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); + return transformer.MakeResult(result); } arena_ptr -PEGTransformerFactory::FinalizeTransactionStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); +PEGTransformerFactory::FinalizeSetAssignmentTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto variable_list = process.TakeResult>>(0); + auto result = TransformSetAssignment(transformer, std::move(variable_list)); + return transformer.MakeResult>>(std::move(result)); } -void PEGTransformerFactory::InitializeBeginTransactionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +arena_ptr +PEGTransformerFactory::FinalizeVariableListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - auto &read_or_write_opt = list_pr.GetChild(2).Cast(); - if (read_or_write_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReadOrWrite), read_or_write_opt.GetResult()}, 0); + auto dynamic_child_count = CountParseResultsFromList(list_pr.GetChild(0)); + vector> expression; + expression.reserve(dynamic_child_count); + for (idx_t i = 0; i < 0 + dynamic_child_count; i++) { + expression.push_back(process.TakeResult>(i)); } + auto result = TransformVariableList(transformer, std::move(expression)); + return transformer.MakeResult>>(std::move(result)); } arena_ptr @@ -26818,11 +19281,6 @@ PEGTransformerFactory::FinalizeBeginTransactionTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeRollbackTransactionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeRollbackTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26834,11 +19292,6 @@ PEGTransformerFactory::FinalizeRollbackTransactionTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeCommitTransactionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeCommitTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26850,13 +19303,6 @@ PEGTransformerFactory::FinalizeCommitTransactionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeReadOrWriteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ReadOnlyOrReadWrite), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeReadOrWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto read_only_or_read_write = process.TakeResult(0); @@ -26864,73 +19310,18 @@ PEGTransformerFactory::FinalizeReadOrWriteTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReadOnlyOrReadWriteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeReadOnlyOrReadWriteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeReadOnlyTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeReadOnlyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformReadOnly(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeReadWriteTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeReadWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformReadWrite(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUpdateStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(6); - auto &returning_clause_opt = list_pr.GetChild(6).Cast(); - if (returning_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::ReturningClause), returning_clause_opt.GetResult()}, 5); - } - auto &where_clause_opt = list_pr.GetChild(5).Cast(); - if (where_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WhereClause), where_clause_opt.GetResult()}, 4); - } - auto &from_clause_opt = list_pr.GetChild(4).Cast(); - if (from_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::FromClause), from_clause_opt.GetResult()}, 3); - } - process.PushChild({transformer.GetRule(PEGRuleId::UpdateSetClauseList), list_pr.GetChild(3)}, 2); - process.PushChild({transformer.GetRule(PEGRuleId::UpdateTarget), list_pr.GetChild(2)}, 1); - auto &with_clause_opt = list_pr.GetChild(0).Cast(); - if (with_clause_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::WithClause), with_clause_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeUpdateStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -26958,33 +19349,6 @@ PEGTransformerFactory::FinalizeUpdateStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeUpdateTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeBaseTableSetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBaseTableSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto base_table_name = process.TakeResult>(0); @@ -26992,17 +19356,6 @@ PEGTransformerFactory::FinalizeBaseTableSetTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeBaseTableAliasSetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &update_alias_opt = list_pr.GetChild(1).Cast(); - if (update_alias_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::UpdateAlias), update_alias_opt.GetResult()}, 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::BaseTableName), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27015,13 +19368,6 @@ PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateAliasTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::ColId), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateAliasTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -27033,19 +19379,6 @@ PEGTransformerFactory::FinalizeUpdateAliasTrampoline(PEGTransformer &transformer return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUpdateSetClauseListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(list_pr.GetChild(0)); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::UpdateSetClause), list_items[child_idx].get()}, - 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27060,34 +19393,6 @@ PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline(PEGTransformer &tra return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeUpdateSetClauseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult>(0); - return transformer.MakeResult>(std::move(result)); -} - -void PEGTransformerFactory::InitializeUpdateSetTupleTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27103,14 +19408,6 @@ PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline(PEGTransformer &transfor return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateSetElementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - process.PushChild({transformer.GetRule(PEGRuleId::Expression), list_pr.GetChild(2)}, 1); - process.PushChild({transformer.GetRule(PEGRuleId::UpdateSetColumnTarget), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUpdateSetElementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27120,26 +19417,6 @@ PEGTransformerFactory::FinalizeUpdateSetElementTrampoline(PEGTransformer &transf return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUpdateSetColumnTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::DotIdentifier), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27165,13 +19442,6 @@ PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUseStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::UseTarget), list_pr.GetChild(1)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeUseStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto use_target = process.TakeResult(0); @@ -27179,46 +19449,6 @@ PEGTransformerFactory::FinalizeUseStatementTrampoline(PEGTransformer &transforme return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr PEGTransformerFactory::FinalizeUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeSchemaNameAsUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && - (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR || - choice_result.type == ParseResultType::CHOICE || choice_result.type == ParseResultType::LIST)) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeSchemaNameAsUseTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27244,26 +19474,6 @@ PEGTransformerFactory::FinalizeSchemaNameAsUseTargetTrampoline(PEGTransformer &t return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeCatalogNameAsUseTargetTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process && - (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR || - choice_result.type == ParseResultType::CHOICE || choice_result.type == ParseResultType::LIST)) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27289,26 +19499,6 @@ PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeUseTargetCatalogSchemaTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(3).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::DotIdentifier), repeat_children[child_idx].get()}, - 0 + child_idx); - } - } else { - process.ReserveChildSlots(1 - 1); - } -} - arena_ptr PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27335,11 +19525,6 @@ PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline(PEGTransformer & return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeDotIdentifierTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeDotIdentifierTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27349,20 +19534,6 @@ PEGTransformerFactory::FinalizeDotIdentifierTrampoline(PEGTransformer &transform return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVacuumStatementTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(2); - auto &analyze_target_opt = list_pr.GetChild(2).Cast(); - if (analyze_target_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::AnalyzeTarget), analyze_target_opt.GetResult()}, 1); - } - auto &vacuum_options_opt = list_pr.GetChild(1).Cast(); - if (vacuum_options_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::VacuumOptions), vacuum_options_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeVacuumStatementTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27378,39 +19549,6 @@ PEGTransformerFactory::FinalizeVacuumStatementTrampoline(PEGTransformer &transfo return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeVacuumOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeVacuumOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto result = process.TakeResult(0); - return transformer.MakeResult(result); -} - -void PEGTransformerFactory::InitializeVacuumParensOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::VacuumOption), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27425,28 +19563,6 @@ PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVacuumLegacyOptionsTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(4); - auto &opt_analyze_opt = list_pr.GetChild(3).Cast(); - if (opt_analyze_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OptAnalyze), opt_analyze_opt.GetResult()}, 3); - } - auto &opt_verbose_opt = list_pr.GetChild(2).Cast(); - if (opt_verbose_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OptVerbose), opt_verbose_opt.GetResult()}, 2); - } - auto &opt_freeze_opt = list_pr.GetChild(1).Cast(); - if (opt_freeze_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OptFreeze), opt_freeze_opt.GetResult()}, 1); - } - auto &opt_full_opt = list_pr.GetChild(0).Cast(); - if (opt_full_opt.HasResult()) { - process.PushChild({transformer.GetRule(PEGRuleId::OptFull), opt_full_opt.GetResult()}, 0); - } -} - arena_ptr PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -27470,24 +19586,6 @@ PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline(PEGTransformer &tra return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeVacuumOptionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &choice_pr = list_pr.Child(0); - auto &choice_result = choice_pr.GetResult(); - process.ReserveChildSlots(1); - auto child_rule = choice_result.GetRule(); - auto has_transform_process = child_rule && child_rule->transform_process; - if (choice_result.type == ParseResultType::IDENTIFIER || choice_result.type == ParseResultType::KEYWORD || - choice_result.type == ParseResultType::STRING || choice_result.type == ParseResultType::OPERATOR) { - return; - } - if (!has_transform_process) { - throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); - } - process.PushChild({*child_rule, choice_result}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeVacuumOptionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { string result; @@ -27511,13 +19609,6 @@ PEGTransformerFactory::FinalizeVacuumOptionTrampoline(PEGTransformer &transforme return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOptAnalyzeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::AnalyzeKeyword), list_pr.GetChild(0)}, 0); -} - arena_ptr PEGTransformerFactory::FinalizeOptAnalyzeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto analyze_keyword = process.TakeResult(0); @@ -27525,51 +19616,24 @@ PEGTransformerFactory::FinalizeOptAnalyzeTrampoline(PEGTransformer &transformer, return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOptFullTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOptFullTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformOptFull(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOptFreezeTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOptFreezeTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformOptFreeze(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeOptVerboseTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - process.ReserveChildSlots(0); -} - arena_ptr PEGTransformerFactory::FinalizeOptVerboseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto result = TransformOptVerbose(transformer); return transformer.MakeResult(result); } -void PEGTransformerFactory::InitializeNameListTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto list_items = ExtractParseResultsFromList(ExtractResultFromParens(list_pr.GetChild(0))); - auto dynamic_child_count = list_items.size(); - process.ReserveChildSlots(1 + dynamic_child_count - 1); - for (idx_t i = list_items.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::ColIdOrString), list_items[child_idx].get()}, 0 + child_idx); - } -} - arena_ptr PEGTransformerFactory::FinalizeNameListTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); diff --git a/src/duckdb/src/parser/peg/transformer/transform_generic_copy_option.cpp b/src/duckdb/src/parser/peg/transformer/transform_generic_copy_option.cpp index e26ec37cb..7c61c824a 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generic_copy_option.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generic_copy_option.cpp @@ -44,9 +44,6 @@ static void SetGenericCopyOptionExpression(GenericCopyOption ©_option, uniqu ExpressionClassToString(child->GetExpressionClass())); } } - } else if (expression->GetExpressionType() == ExpressionType::FUNCTION || - expression->GetExpressionType() == ExpressionType::VALUE_PARAMETER) { - copy_option.expression = std::move(expression); } else if (expression->GetExpressionType() == ExpressionType::STAR) { copy_option.children.push_back(Value("*")); } else if (expression->GetExpressionType() == ExpressionType::OPERATOR_CAST) { @@ -64,8 +61,7 @@ static void SetGenericCopyOptionExpression(GenericCopyOption ©_option, uniqu copy_option.expression = std::move(expression); } } else { - throw NotImplementedException("Unrecognized expression type %s", - ExpressionTypeToString(expression->GetExpressionType())); + copy_option.expression = std::move(expression); } } diff --git a/src/duckdb/src/parser/peg/transformer/transform_select.cpp b/src/duckdb/src/parser/peg/transformer/transform_select.cpp index 4c25d295a..0fba4e745 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_select.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_select.cpp @@ -1049,37 +1049,49 @@ void PEGTransformerFactory::InitializeWithClauseTrampoline(PEGTransformer &trans GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); auto with_statement_list = ExtractParseResultsFromList(list_pr.Child(2)); - process.ReserveChildSlots(with_statement_list.size()); - for (idx_t i = with_statement_list.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({with_statement_list[child_idx].get()}, child_idx); - } + auto entry_count = with_statement_list.size(); + // the last slot holds the CTE map that is built up while the CTEs are transformed + process.ReserveChildSlots(entry_count + 1); + process.SetChildResult(entry_count, transformer.MakeResult(CommonTableExpressionMap())); + // earlier CTEs are visible while transforming later ones (e.g. for PIVOT enum extraction) + transformer.stored_cte_map.push_back(process.GetResult(entry_count)); + process.manual_state = 0; + process.PushChild({with_statement_list[0].get()}, 0); } arena_ptr PEGTransformerFactory::FinalizeWithClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); bool is_recursive = list_pr.Child(1).HasResult(); - CommonTableExpressionMap result; - for (idx_t entry_idx = 0; entry_idx < process.child_results.size(); entry_idx++) { - auto with_entry = process.TakeResult>>(entry_idx); - if (is_recursive) { - auto &query_node = with_entry.second->query_node; - if (!query_node) { - throw ParserException("Recursive CTEs with DML statements are not supported"); - } - ValidateRecursiveCTEQueryNode(*query_node); - query_node = ToRecursiveCTE(std::move(query_node), with_entry.first, with_entry.second->aliases, - with_entry.second->key_targets); + auto entry_count = process.child_results.size() - 1; + auto &result = process.GetResult(entry_count); + + auto entry_idx = process.manual_state; + auto with_entry = process.TakeResult>>(entry_idx); + if (is_recursive) { + auto &query_node = with_entry.second->query_node; + if (!query_node) { + throw ParserException("Recursive CTEs with DML statements are not supported"); } - auto &cte_name = with_entry.first; - auto it = result.map.find(cte_name); - if (it != result.map.end()) { - throw ParserException("Duplicate CTE name %s", cte_name); - } - result.map.insert(with_entry.first, std::move(with_entry.second)); + ValidateRecursiveCTEQueryNode(*query_node); + query_node = ToRecursiveCTE(std::move(query_node), with_entry.first, with_entry.second->aliases, + with_entry.second->key_targets); + } + auto &cte_name = with_entry.first; + auto it = result.map.find(cte_name); + if (it != result.map.end()) { + throw ParserException("Duplicate CTE name %s", cte_name); + } + result.map.insert(with_entry.first, std::move(with_entry.second)); + + if (entry_idx + 1 < entry_count) { + process.manual_state = entry_idx + 1; + auto with_statement_list = ExtractParseResultsFromList(list_pr.Child(2)); + process.PushChild({with_statement_list[entry_idx + 1].get()}, entry_idx + 1); + return nullptr; } - return transformer.MakeResult(std::move(result)); + transformer.stored_cte_map.pop_back(); + return transformer.MakeResult(process.TakeResult(entry_count)); } pair> diff --git a/src/duckdb/src/parser/query_node/insert_query_node.cpp b/src/duckdb/src/parser/query_node/insert_query_node.cpp index 05dfe39d0..72a5b3c64 100644 --- a/src/duckdb/src/parser/query_node/insert_query_node.cpp +++ b/src/duckdb/src/parser/query_node/insert_query_node.cpp @@ -58,18 +58,18 @@ string InsertQueryNode::ToString() const { } if (!or_replace_shorthand_set && on_conflict_info) { auto &conflict_info = *on_conflict_info; - result += " ON CONFLICT "; + result += " ON CONFLICT"; // (optional) conflict target if (!conflict_info.indexed_columns.empty()) { - result += "("; + result += " ("; auto &cols = conflict_info.indexed_columns; for (auto it = cols.begin(); it != cols.end();) { - result += StringUtil::Lower(it->GetIdentifierName()); + result += SQLIdentifier(*it); if (++it != cols.end()) { result += ", "; } } - result += " )"; + result += ")"; } // (optional) where clause @@ -79,18 +79,8 @@ string InsertQueryNode::ToString() const { result += " " + OnConflictInfo::ActionToString(conflict_info.action_type); if (conflict_info.set_info) { D_ASSERT(conflict_info.action_type == OnConflictAction::UPDATE); - result += " SET "; auto &set_info = *conflict_info.set_info; - D_ASSERT(set_info.columns.size() == set_info.expressions.size()); - // SET = - for (idx_t i = 0; i < set_info.columns.size(); i++) { - auto &column = set_info.columns[i]; - auto &expr = set_info.expressions[i]; - if (i) { - result += ", "; - } - result += StringUtil::Lower(column.GetIdentifierName()) + " = " + expr->ToString(); - } + result += " " + set_info.ToString(); // (optional) where clause if (set_info.condition) { result += " WHERE " + set_info.condition->ToString(); diff --git a/src/duckdb/src/parser/query_node/merge_query_node.cpp b/src/duckdb/src/parser/query_node/merge_query_node.cpp index 5dd8f466f..c33e90faf 100644 --- a/src/duckdb/src/parser/query_node/merge_query_node.cpp +++ b/src/duckdb/src/parser/query_node/merge_query_node.cpp @@ -37,7 +37,7 @@ string MergeQueryNode::ToString() const { if (c > 0) { result += ", "; } - result += using_columns[c].GetIdentifierName(); + result += SQLIdentifier(using_columns[c]); } result += ")"; } diff --git a/src/duckdb/src/parser/statement/external_resource_statement.cpp b/src/duckdb/src/parser/statement/external_resource_statement.cpp index c0f90e494..c170bc9e6 100644 --- a/src/duckdb/src/parser/statement/external_resource_statement.cpp +++ b/src/duckdb/src/parser/statement/external_resource_statement.cpp @@ -11,7 +11,7 @@ ExternalResourceStatement::ExternalResourceStatement(ExternalResourceOperation o } ExternalResourceStatement::ExternalResourceStatement(const ExternalResourceStatement &other) - : SQLStatement(other), operation(other.operation), type(other.type), name(other.name), all(other.all) { + : SQLStatement(other), operation(other.operation), type(other.type), name(other.name) { if (other.handle) { handle = other.handle->Copy(); } @@ -51,9 +51,6 @@ string ExternalResourceStatement::ToString() const { case ExternalResourceOperation::DESTROY: result = "DESTROY EXTERNAL RESOURCE " + SQLIdentifier(name); break; - case ExternalResourceOperation::SHOW: - result = all ? "SHOW ALL EXTERNAL RESOURCES" : "SHOW EXTERNAL RESOURCES"; - break; } return result; } diff --git a/src/duckdb/src/parser/tableref/delimgetref.cpp b/src/duckdb/src/parser/tableref/delimgetref.cpp index 71910ff3b..ec6952122 100644 --- a/src/duckdb/src/parser/tableref/delimgetref.cpp +++ b/src/duckdb/src/parser/tableref/delimgetref.cpp @@ -13,7 +13,9 @@ bool DelimGetRef::Equals(const TableRef &other) const { } unique_ptr DelimGetRef::Copy() { - return make_uniq(types); + auto copy = make_uniq(types); + CopyProperties(*copy); + return std::move(copy); } void DelimGetRef::Serialize(Serializer &serializer) const { diff --git a/src/duckdb/src/parser/tableref/emptytableref.cpp b/src/duckdb/src/parser/tableref/emptytableref.cpp index 0107aac9c..09eab0370 100644 --- a/src/duckdb/src/parser/tableref/emptytableref.cpp +++ b/src/duckdb/src/parser/tableref/emptytableref.cpp @@ -11,7 +11,9 @@ bool EmptyTableRef::Equals(const TableRef &other) const { } unique_ptr EmptyTableRef::Copy() { - return make_uniq(); + auto copy = make_uniq(); + CopyProperties(*copy); + return std::move(copy); } } // namespace duckdb diff --git a/src/duckdb/src/parser/tableref/joinref.cpp b/src/duckdb/src/parser/tableref/joinref.cpp index b4621cbb0..5f51e1b13 100644 --- a/src/duckdb/src/parser/tableref/joinref.cpp +++ b/src/duckdb/src/parser/tableref/joinref.cpp @@ -119,7 +119,6 @@ unique_ptr JoinRef::Copy() { } copy->type = type; copy->ref_type = ref_type; - copy->alias = alias; copy->using_columns = using_columns; copy->delim_flipped = delim_flipped; for (auto &col : duplicate_eliminated_columns) { @@ -132,6 +131,7 @@ unique_ptr JoinRef::Copy() { copy->nearest_count = nearest_count; copy->nearest_order_type = nearest_order_type; copy->nearest_approx = nearest_approx; + CopyProperties(*copy); return std::move(copy); } diff --git a/src/duckdb/src/parser/tableref/pivotref.cpp b/src/duckdb/src/parser/tableref/pivotref.cpp index f8197ba98..018ffc730 100644 --- a/src/duckdb/src/parser/tableref/pivotref.cpp +++ b/src/duckdb/src/parser/tableref/pivotref.cpp @@ -340,7 +340,7 @@ unique_ptr PivotRef::Copy() { copy->groups = groups; copy->column_name_alias = column_name_alias; copy->include_nulls = include_nulls; - copy->alias = alias; + CopyProperties(*copy); return std::move(copy); } diff --git a/src/duckdb/src/planner/binder.cpp b/src/duckdb/src/planner/binder.cpp index 5161fe0fe..580ac0109 100644 --- a/src/duckdb/src/planner/binder.cpp +++ b/src/duckdb/src/planner/binder.cpp @@ -278,6 +278,14 @@ void Binder::SetParameters(BoundParameterMap ¶meters) { global_binder_state->parameters = parameters; } +void Binder::SetStatementParameters(const identifier_map_t &statement_parameters) { + global_binder_state->statement_parameters = statement_parameters; +} + +bool Binder::StatementHasParameter(const Identifier &identifier) const { + return global_binder_state->statement_parameters.count(identifier) > 0; +} + void Binder::SetInsideSubquery() { inside_subquery = true; } @@ -286,6 +294,14 @@ bool Binder::IsInsideSubquery() const { return inside_subquery; } +void Binder::SetBindingIndexKey(bool binding_index_key_p) { + binding_index_key = binding_index_key_p; +} + +bool Binder::IsBindingIndexKey() const { + return binding_index_key; +} + void Binder::SetBindingTrySubquery() { binding_try_subquery = true; } 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 43b92deb8..3f0ff3b0f 100644 --- a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp @@ -99,7 +99,8 @@ static void NegatePercentileFractions(ClientContext &context, unique_ptr values; for (const auto &element_val : ListValue::GetChildren(value)) { values.push_back(NegatePercentileValue(element_val, desc)); @@ -292,6 +293,15 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu } } + // EXPORT_STATE exports the state of the underlying (non-distinct) aggregate: it does not carry the set of values + // seen so far, so combining exported states of a DISTINCT aggregate would count repeated values again + if (aggr.Distinct() && aggr.ExportState()) { + throw BinderException(aggr, + "EXPORT_STATE is not supported for DISTINCT aggregates: the exported state does not " + "retain the set of distinct values, so combining states would produce incorrect " + "results"); + } + // Bind the function FunctionBinder function_binder(binder); auto aggregate = diff --git a/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp index 9a6732d95..72d3a6d5a 100644 --- a/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp @@ -88,19 +88,19 @@ bool BoundComparisonExpression::TryBindComparison(ClientContext &context, const case LogicalTypeId::DECIMAL: { // result is a decimal: we need the maximum width and the maximum scale over width vector argument_types = {left_type, right_type}; - uint8_t max_width = 0, max_scale = 0, max_width_over_scale = 0; + uint32_t max_width = 0, max_scale = 0, max_width_over_scale = 0; for (idx_t i = 0; i < argument_types.size(); i++) { - uint8_t width, scale; + uint32_t width, scale; auto can_convert = argument_types[i].GetDecimalProperties(width, scale); if (!can_convert) { result_type = res; return true; } - max_width = MaxValue(width, max_width); - max_scale = MaxValue(scale, max_scale); - max_width_over_scale = MaxValue(width - scale, max_width_over_scale); + max_width = MaxValue(width, max_width); + max_scale = MaxValue(scale, max_scale); + max_width_over_scale = MaxValue(width - scale, max_width_over_scale); } - max_width = MaxValue(max_scale + max_width_over_scale, max_width); + max_width = MaxValue(max_scale + max_width_over_scale, max_width); if (max_width > Decimal::MAX_WIDTH_DECIMAL) { // target width does not fit in decimal: truncate the scale (if possible) to try and make it fit max_width = Decimal::MAX_WIDTH_DECIMAL; 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 a3764be05..7ff9f8868 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 @@ -216,8 +216,9 @@ BoundStatement Binder::FinishCTE(BoundCTEData &bound_cte, BoundStatement child) auto cte_query = std::move(bind_state.query.plan); auto cte_child = std::move(child.plan); - auto root = make_uniq(bound_cte.ctename, bound_cte.setop_index, result.types.size(), - std::move(cte_query), std::move(cte_child), bound_cte.materialized); + auto root = + make_uniq(bound_cte.ctename, bound_cte.setop_index, bind_state.query.types.size(), + std::move(cte_query), std::move(cte_child), bound_cte.materialized); result.plan = std::move(root); return result; diff --git a/src/duckdb/src/planner/binder/query_node/bind_recursive_cte_node.cpp b/src/duckdb/src/planner/binder/query_node/bind_recursive_cte_node.cpp index 3509d41c7..87e014dcb 100644 --- a/src/duckdb/src/planner/binder/query_node/bind_recursive_cte_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/bind_recursive_cte_node.cpp @@ -122,7 +122,19 @@ BoundStatement Binder::BindNode(RecursiveCTENode &statement) { // Bind the children of the aggregate function for (auto &child : func_expr.GetArgumentsMutable()) { - bound_children.push_back(expression_binder.Bind(child.GetExpressionMutable())); + // the aggregates are evaluated on the rows of the CTE, where nothing plans a subquery, so it is + // rejected before binding, and once more after it for one that a macro expands to + auto child_location = child.GetExpression().GetQueryLocation(); + if (child.GetExpression().HasSubquery()) { + throw BinderException(child_location, + "Subqueries are not yet supported for aggregates in USING KEY"); + } + auto bound_child = expression_binder.Bind(child.GetExpressionMutable()); + if (bound_child->HasSubquery()) { + throw BinderException(child_location, + "Subqueries are not yet supported for aggregates in USING KEY"); + } + bound_children.push_back(std::move(bound_child)); } ProjectionIndex aggregate_idx; 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 e6f4bf384..00921259f 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 @@ -73,9 +73,12 @@ BoundLimitNode Binder::BindLimitValue(OrderBinder &order_binder, unique_ptrIsFoldable()) { + + Value constant; + // if evaluation throws, evaluate at runtime instead, so it only fails if the LIMIT operator receives rows + if (expr->IsFoldable() && ExpressionExecutor::TryEvaluateScalar(context, *expr, constant)) { //! this is a constant - auto val = ExpressionExecutor::EvaluateScalar(context, *expr).CastAs(context, target_type); + auto val = constant.CastAs(context, target_type); if (is_percentage) { D_ASSERT(!is_offset); double percentage_val; @@ -345,8 +348,20 @@ void Binder::BindModifiers(BoundQueryNode &result, TableIndex table_index, const switch (bound_mod->type) { case ResultModifierType::DISTINCT_MODIFIER: { auto &distinct = bound_mod->Cast(); + if (distinct.distinct_type == DistinctType::DISTINCT) { + // DISTINCT covers every result column: the targets were prepared before the select list was bound, + // and an UNNEST of a struct expands an entry into several columns + distinct.target_distincts.clear(); + for (idx_t i = 0; i < result.types.size(); i++) { + distinct.target_distincts.push_back(make_uniq( + names[i], sql_types[i], ColumnBinding(table_index, ProjectionIndex(i)))); + } + } // set types of distinct targets for (auto &expr : distinct.target_distincts) { + if (expr->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { + continue; + } expr = FinalizeBindOrderExpression(std::move(expr), table_index, names, sql_types, bind_state); if (!expr) { throw InternalException("DISTINCT ON ORDER BY ALL not supported"); diff --git a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp index f7456f026..0bc3c7833 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp @@ -46,6 +46,10 @@ bool Binder::DebugAggregateStateExportVerify(BoundSelectNode &statement, unique_ // already an aggregate state export - skip verification return false; } + if (aggr->Cast().IsDistinct()) { + // the exported state of a DISTINCT aggregate cannot be re-bound: EXPORT_STATE rejects DISTINCT + return false; + } } // we transform a query like "SELECT grp, SUM(col) FROM tbl GROUP BY grp" into diff --git a/src/duckdb/src/planner/binder/query_node/plan_setop.cpp b/src/duckdb/src/planner/binder/query_node/plan_setop.cpp index a2877a682..deba4feb2 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_setop.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_setop.cpp @@ -1,10 +1,17 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_window_expression.hpp" +#include "duckdb/planner/expression_binder.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" +#include "duckdb/planner/operator/logical_window.hpp" #include "duckdb/planner/query_node/bound_set_operation_node.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/function/table/read_csv.hpp" +#include "duckdb/function/window/rows_functions.hpp" +#include "duckdb/function/window_function.hpp" #include "duckdb/planner/operator/logical_get.hpp" namespace duckdb { @@ -70,25 +77,66 @@ unique_ptr Binder::CastLogicalOperatorToTypes(const vector Binder::CreatePlan(BoundSetOperationNode &node) { - // create actual logical ops for setops - LogicalOperatorType logical_type = LogicalOperatorType::LOGICAL_INVALID; - switch (node.setop_type) { - case SetOperationType::UNION: - case SetOperationType::UNION_BY_NAME: - logical_type = LogicalOperatorType::LOGICAL_UNION; - break; - case SetOperationType::EXCEPT: - logical_type = LogicalOperatorType::LOGICAL_EXCEPT; - break; - case SetOperationType::INTERSECT: - logical_type = LogicalOperatorType::LOGICAL_INTERSECT; - break; - default: - throw InternalException("Unsupported logical operator type for set-operation"); +//! Numbers the rows that are equal in all columns, so that EXCEPT ALL and INTERSECT ALL match the n-th copies of a row +static unique_ptr AddRowNumber(Binder &binder, const vector &types, + unique_ptr child) { + auto &context = binder.context; + auto bindings = child->GetColumnBindings(); + auto row_number = GetBuiltinWindowFunction(context, RowNumberFun::Name, {})->Bind(context); + row_number->WindowStartMutable() = WindowBoundary::UNBOUNDED_PRECEDING; + row_number->WindowEndMutable() = WindowBoundary::UNBOUNDED_FOLLOWING; + for (idx_t i = 0; i < types.size(); i++) { + unique_ptr partition = make_uniq(types[i], bindings[i]); + ExpressionBinder::PushCollation(context, partition, types[i]); + row_number->PartitionsMutable().push_back(std::move(partition)); } - // Generate the logical plan for the children of the set operation + auto window = make_uniq(binder.GenerateTableIndex()); + window->expressions.push_back(std::move(row_number)); + window->AddChild(std::move(child)); + return std::move(window); +} + +//! Plans EXCEPT as an ANTI join and INTERSECT as a SEMI join on all columns, which compares them with the collations +//! of both children and treats NULLs as equal +static unique_ptr CreateSetOperationJoin(Binder &binder, BoundSetOperationNode &node, + unique_ptr left, + unique_ptr right) { + auto &types = node.types; + auto compared_types = types; + if (node.setop_all) { + left = AddRowNumber(binder, types, std::move(left)); + right = AddRowNumber(binder, types, std::move(right)); + compared_types.push_back(LogicalType::BIGINT); + } + auto left_bindings = left->GetColumnBindings(); + auto right_bindings = right->GetColumnBindings(); + D_ASSERT(left_bindings.size() == compared_types.size() && right_bindings.size() == compared_types.size()); + + auto join_type = node.setop_type == SetOperationType::EXCEPT ? JoinType::ANTI : JoinType::SEMI; + auto join = make_uniq(join_type); + for (idx_t i = 0; i < compared_types.size(); i++) { + auto &type = compared_types[i]; + JoinCondition condition(make_uniq(type, left_bindings[i]), + make_uniq(type, right_bindings[i]), + ExpressionType::COMPARE_NOT_DISTINCT_FROM); + ExpressionBinder::PushCollation(binder.context, condition.LeftReference(), type); + ExpressionBinder::PushCollation(binder.context, condition.RightReference(), type); + join->conditions.push_back(std::move(condition)); + } + join->AddChild(std::move(left)); + join->AddChild(std::move(right)); + + vector> select_list; + for (idx_t i = 0; i < types.size(); i++) { + select_list.push_back(make_uniq(types[i], left_bindings[i])); + } + auto projection = make_uniq(node.setop_index, std::move(select_list)); + projection->AddChild(std::move(join)); + return std::move(projection); +} +unique_ptr Binder::CreatePlan(BoundSetOperationNode &node) { + // Generate the logical plan for the children of the set operation D_ASSERT(node.bound_children.size() >= 2); vector> children; for (auto &child : node.bound_children) { @@ -98,8 +146,21 @@ unique_ptr Binder::CreatePlan(BoundSetOperationNode &node) { child_node = CastLogicalOperatorToTypes(child.types, node.types, std::move(child_node)); children.push_back(std::move(child_node)); } - auto root = make_uniq(node.setop_index, node.types.size(), std::move(children), logical_type, - node.setop_all); + unique_ptr root; + switch (node.setop_type) { + case SetOperationType::UNION: + case SetOperationType::UNION_BY_NAME: + root = make_uniq(node.setop_index, node.types.size(), std::move(children), + LogicalOperatorType::LOGICAL_UNION, node.setop_all); + break; + case SetOperationType::EXCEPT: + case SetOperationType::INTERSECT: + D_ASSERT(children.size() == 2); + root = CreateSetOperationJoin(*this, node, std::move(children[0]), std::move(children[1])); + break; + default: + throw InternalException("Unsupported logical operator type for set-operation"); + } return VisitQueryNode(node, std::move(root)); } 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 cd8aae41c..adc1ec9d4 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp @@ -448,9 +448,46 @@ static bool PerformDelimOnType(const LogicalType &type) { return true; } +//! Like IsVolatile, but ignores error() +//! Error is deterministic, so it can be evaluated once per distinct correlated value +//! FIXME: remove once `error` no longer has to be volatile (fixing blockers is WIP) +static bool IsVolatileIgnoringError(const Expression &expr) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_FUNCTION: { + auto &function = expr.Cast().Function(); + if (function.HasBindLambdaCallback() || + (function.GetName() != ErrorFun::Name && function.GetStability() == FunctionStability::VOLATILE)) { + return expr.IsVolatile(); + } + break; + } + case ExpressionClass::BOUND_CASE: + case ExpressionClass::BOUND_CONJUNCTION: + case ExpressionClass::BOUND_OPERATOR: + break; + default: + return expr.IsVolatile(); + } + bool is_volatile = false; + ExpressionIterator::EnumerateChildren( + expr, [&](const Expression &child) { is_volatile = is_volatile || IsVolatileIgnoringError(child); }); + return is_volatile; +} + +static bool HasVolatileExpressionsIgnoringError(const LogicalOperator &op) { + bool is_volatile = false; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { + is_volatile = is_volatile || IsVolatileIgnoringError(**expression); + }); + for (auto &child : op.children) { + is_volatile = is_volatile || (child && HasVolatileExpressionsIgnoringError(*child)); + } + return is_volatile; +} + static bool PerformDuplicateElimination(Binder &binder, CorrelatedColumns &correlated_columns, optional_ptr dependent_plan = nullptr) { - bool perform_delim = !dependent_plan || !dependent_plan->HasVolatileExpressions(); + bool perform_delim = !dependent_plan || !HasVolatileExpressionsIgnoringError(*dependent_plan); if (perform_delim && !Settings::Get(binder.context)) { // if optimizations are disabled we always do a delim join return true; @@ -482,7 +519,7 @@ static unique_ptr PlanCorrelatedSubquery(Binder &binder, BoundSubque // Preserve the existing duplicate-elimination path for deterministic ANY queries. Volatile ANY queries require // row identity for the same reason as other correlated subqueries: sharing one result between equal outer values // changes their evaluation cardinality. - bool perform_delim = expr.GetSubqueryType() == SubqueryType::ANY && !plan->HasVolatileExpressions() + bool perform_delim = expr.GetSubqueryType() == SubqueryType::ANY && !HasVolatileExpressionsIgnoringError(*plan) ? true : PerformDuplicateElimination(binder, correlated_columns, plan); D_ASSERT(expr.IsCorrelated()); diff --git a/src/duckdb/src/planner/binder/statement/bind_copy.cpp b/src/duckdb/src/planner/binder/statement/bind_copy.cpp index ecbf79184..3516d5925 100644 --- a/src/duckdb/src/planner/binder/statement/bind_copy.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_copy.cpp @@ -106,33 +106,6 @@ identifier_map_t Binder::GetFullCopyOptionsList(const CopyFunction & return copy_options; } -static idx_t ParseBytesArg(const Identifier &name, Value &arg) { - if (arg.IsNull()) { - throw BinderException("NULL is not supported as a valid option for COPY option \"%s\"", - StringUtil::Upper(name.GetIdentifierName())); - } - optional_idx result; - if (arg.type().id() == LogicalTypeId::VARCHAR) { - result = DBConfig::ParseMemoryLimit(arg.ToString()); - } else { - auto cast_arg = arg.DefaultTryCastAs(LogicalType::UBIGINT); - if (!cast_arg) { - throw BinderException("Unable to parse bytes from \"%s\" for copy option \"%s\" ", arg.ToString(), - StringUtil::Upper(name.GetIdentifierName())); - } - auto bytes = cast_arg->GetValue(); - if (bytes != DConstants::INVALID_INDEX) { - result = bytes; - } - } - if (!result.IsValid()) { - // e.g. '-1' or 'none', which ParseMemoryLimit parses as unlimited - throw BinderException("Copy option \"%s\" must be a valid size, not \"%s\"", - StringUtil::Upper(name.GetIdentifierName()), arg.ToString()); - } - return result.GetIndex(); -} - struct CopyToParsedOptions { optional use_tmp_file; optional overwrite_mode; diff --git a/src/duckdb/src/planner/binder/statement/bind_execute.cpp b/src/duckdb/src/planner/binder/statement/bind_execute.cpp index b3859c644..b73daaace 100644 --- a/src/duckdb/src/planner/binder/statement/bind_execute.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_execute.cpp @@ -73,7 +73,7 @@ BoundStatement Binder::Bind(ExecuteStatement &stmt) { if (prepared->RequireRebind(context, bind_values)) { rebind = RebindQueryInfo::ATTEMPT_TO_REBIND; } - for (auto &state : context.registered_state->States()) { + for (auto &state : context.GetContext().GetRegisteredState().States()) { BindPreparedStatementCallbackInfo info {*prepared, bind_values}; auto new_rebind = state->OnRebindPreparedStatement(context, info, rebind); if (new_rebind == RebindQueryInfo::ATTEMPT_TO_REBIND) { 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 0bbee6fd6..13660130c 100644 --- a/src/duckdb/src/planner/binder/statement/bind_external_resource.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_external_resource.cpp @@ -1,11 +1,6 @@ #include "duckdb/execution/expression_executor.hpp" #include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/parser/expression/function_expression.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/parser/statement/external_resource_statement.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/tableref/table_function_ref.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression_binder/table_function_binder.hpp" #include "duckdb/planner/operator/logical_external_resource.hpp" @@ -26,26 +21,6 @@ void Binder::BindExternalResourceParams(case_insensitive_map_t)`. - vector> children; - if (stmt.all) { - auto all_expr = ConstantExpression::Boolean(true); - all_expr->SetAlias("discover"); - children.push_back(std::move(all_expr)); - } - auto table_function = make_uniq(); - table_function->function = make_uniq("duckdb_external_resources", std::move(children)); - - auto select_node = make_uniq(); - select_node->select_list.push_back(make_uniq()); - select_node->from_table = std::move(table_function); - SelectStatement select_statement; - select_statement.node = std::move(select_node); - - return Bind(select_statement); - } - BoundStatement result; result.types = {LogicalType::BOOLEAN}; result.names = {"Success"}; diff --git a/src/duckdb/src/planner/binder/statement/bind_summarize.cpp b/src/duckdb/src/planner/binder/statement/bind_summarize.cpp index cb806020e..40bef9c22 100644 --- a/src/duckdb/src/planner/binder/statement/bind_summarize.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_summarize.cpp @@ -118,7 +118,9 @@ BoundStatement Binder::BindSummarize(ShowRef &ref) { max_children.push_back(SummarizeCreateAggregate("max", plan.names[i])); unique_children.push_back(make_uniq( LogicalType::BIGINT, SummarizeCreateAggregate("approx_count_distinct", plan.names[i]))); - if (plan.types[i].IsNumeric() || plan.types[i].IsTemporal()) { + const auto &column_type = plan.types[i]; + const auto supports_average = column_type.IsNumeric() || column_type.IsTemporal(); + if (supports_average) { avg_children.push_back(SummarizeCreateAggregate("avg", plan.names[i])); } else { avg_children.push_back(ConstantExpression::Null()); @@ -128,7 +130,7 @@ BoundStatement Binder::BindSummarize(ShowRef &ref) { } else { std_children.push_back(ConstantExpression::Null()); } - if (plan.types[i].IsNumeric() || plan.types[i].IsTemporal()) { + if (supports_average) { q25_children.push_back(SummarizeCreateAggregate("approx_quantile", plan.names[i], Value::FLOAT(0.25))); q50_children.push_back(SummarizeCreateAggregate("approx_quantile", plan.names[i], Value::FLOAT(0.50))); q75_children.push_back(SummarizeCreateAggregate("approx_quantile", plan.names[i], Value::FLOAT(0.75))); diff --git a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp index 3c2696983..de3d0d9af 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp @@ -46,14 +46,14 @@ static bool TryLoadExtensionForReplacementScan(ClientContext &context, const str } BoundStatement Binder::BindWithReplacementScan(ClientContext &context, BaseTableRef &ref) { - if (!context.config.use_replacement_scans) { + if (!ClientConfig::GetConfig(context).use_replacement_scans) { return BoundStatement(); } ReplacementScanInput input(ref.GetQualifiedName()); unique_ptr replacement_function; // Connection-scoped replacement scans are consulted first - for (const auto &scan : context.config.replacement_scans) { + for (const auto &scan : ClientConfig::GetConfig(context).replacement_scans) { if (auto result = scan->function(context, input, scan->data.get())) { replacement_function = std::move(result); break; @@ -226,8 +226,8 @@ BoundStatement Binder::Bind(BaseTableRef &ref) { } } auto &config = DBConfig::GetConfig(context); - if (context.config.use_replacement_scans && Settings::Get(config) && - ExtensionHelper::IsFullPath(full_path)) { + if (ClientConfig::GetConfig(context).use_replacement_scans && + Settings::Get(config) && ExtensionHelper::IsFullPath(full_path)) { auto &fs = FileSystem::GetFileSystem(context); if (!fs.IsDisabledForPath(full_path) && fs.FileExists(full_path)) { throw BinderException( diff --git a/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp b/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp index aa3a68b5b..92c66b71d 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp @@ -24,13 +24,40 @@ namespace duckdb { enum class TableFunctionBindType { STANDARD_TABLE_FUNCTION, TABLE_IN_OUT_FUNCTION, TABLE_PARAMETER_FUNCTION }; +//! Recognize named arguments before deciding whether a call has a table input. +static bool NamedArgumentShaped(const FunctionArgument &argument) { + if (argument.HasName()) { + return true; + } + auto &expression = argument.GetExpression(); + if (expression.GetExpressionType() == ExpressionType::SUBQUERY) { + return false; + } + if (expression.GetExpressionType() == ExpressionType::COMPARE_EQUAL) { + auto &comparison = expression.Cast(); + return comparison.Left().GetExpressionType() == ExpressionType::COLUMN_REF && + !comparison.Left().Cast().IsQualified(); + } + return !expression.GetAlias().empty(); +} + +//! True when a real table input remains once the named arguments are set aside. +static bool HasTableInputBesidesNamedArguments(const vector &arguments) { + for (auto &argument : arguments) { + if (!NamedArgumentShaped(argument) && !argument.GetExpression().IsScalar()) { + return true; + } + } + return false; +} + static TableFunctionBindType GetTableFunctionBindType(TableFunctionCatalogEntry &table_function, - vector> &expressions) { + const vector &arguments) { // first check if all expressions are scalar // if they are we always bind as a standard table function bool all_scalar = true; - for (auto &expr : expressions) { - if (!expr->IsScalar()) { + for (auto &argument : arguments) { + if (!argument.GetExpression().IsScalar()) { all_scalar = false; break; } @@ -94,24 +121,23 @@ void Binder::BindTableInTableOutFunction(vector> &e MoveCorrelatedExpressions(*binder); } -bool Binder::BindTableFunctionParameters(TableFunctionCatalogEntry &table_function, - vector> &expressions, +bool Binder::BindTableFunctionParameters(TableFunctionCatalogEntry &table_function, vector &arguments, vector> &positional_arguments, vector>> &named_arguments, BoundStatement &subquery, bool &table_in_out, ErrorData &error) { - auto bind_type = GetTableFunctionBindType(table_function, expressions); - if (bind_type == TableFunctionBindType::TABLE_IN_OUT_FUNCTION) { - // bind table in-out function - its arguments are the columns of the subquery, so there is nothing to fold - BindTableInTableOutFunction(expressions, subquery); - table_in_out = true; - return true; + auto bind_type = GetTableFunctionBindType(table_function, arguments); + // Named arguments alone do not make an otherwise scalar call table-in-out. + if (bind_type == TableFunctionBindType::TABLE_IN_OUT_FUNCTION && !HasTableInputBesidesNamedArguments(arguments)) { + bind_type = TableFunctionBindType::STANDARD_TABLE_FUNCTION; } + vector> input_expressions; bool seen_subquery = false; - for (auto &child : expressions) { - Identifier parameter_name; + for (auto &argument : arguments) { + auto &child = argument.GetExpressionMutable(); + Identifier parameter_name = argument.GetName(); - // hack to make named parameters work - if (child->GetExpressionType() == ExpressionType::COMPARE_EQUAL) { + // Explicit argument names take precedence over the legacy name = expression form. + if (parameter_name.empty() && child->GetExpressionType() == ExpressionType::COMPARE_EQUAL) { // comparison, check if the LHS is a columnref auto &comp = child->Cast(); if (comp.Left().GetExpressionType() == ExpressionType::COLUMN_REF) { @@ -121,11 +147,21 @@ bool Binder::BindTableFunctionParameters(TableFunctionCatalogEntry &table_functi child = std::move(comp.RightMutable()); } } - } else if (!child->GetAlias().empty()) { + } else if (parameter_name.empty() && !child->GetAlias().empty() && + !(bind_type == TableFunctionBindType::TABLE_IN_OUT_FUNCTION && + child->GetExpressionType() == ExpressionType::SUBQUERY)) { // => will set the alias of to parameter_name = child->GetAlias(); } - if (bind_type == TableFunctionBindType::TABLE_PARAMETER_FUNCTION && + if (bind_type == TableFunctionBindType::TABLE_IN_OUT_FUNCTION && parameter_name.empty()) { + if (!named_arguments.empty()) { + error = ErrorData("Unnamed parameters cannot come after named parameters"); + return false; + } + input_expressions.push_back(std::move(child)); + continue; + } + if (bind_type == TableFunctionBindType::TABLE_PARAMETER_FUNCTION && parameter_name.empty() && child->GetExpressionType() == ExpressionType::SUBQUERY) { D_ASSERT(table_function.functions.Size() == 1); const auto &fun = *table_function.functions.GetFunctionByOffset(0); @@ -149,7 +185,11 @@ bool Binder::BindTableFunctionParameters(TableFunctionCatalogEntry &table_functi } TableFunctionBinder binder(*this, context, table_function.name.GetIdentifierName()); + // a NULL argument keeps the NULL type, so that it can still match any overload + auto prev_can_contain_nulls = CanContainNulls(); + SetCanContainNulls(true); auto expr = binder.Bind(child); + SetCanContainNulls(prev_can_contain_nulls); if (expr->HasParameter()) { throw ParameterNotResolvedException(); } @@ -171,6 +211,12 @@ bool Binder::BindTableFunctionParameters(TableFunctionCatalogEntry &table_functi named_arguments.emplace_back(parameter_name, std::move(expr)); } } + if (bind_type == TableFunctionBindType::TABLE_IN_OUT_FUNCTION) { + // Positional arguments vary with each input row. Named options remain scalar + // bind-time arguments and must not become extra columns in that input table. + BindTableInTableOutFunction(input_expressions, subquery); + table_in_out = true; + } return true; } @@ -239,7 +285,7 @@ BoundStatement Binder::BindTableFunctionInternal(BoundTableFunction &table_funct auto constexpr ordinality_name = "ordinality"; string ordinality_column_name = ordinality_name; optional_idx ordinality_column_id; - // the function binder has placed them already, but not for a table in-out call or a direct bind + // the function binder has placed them already, but a direct bind may not have done so table_function.GetSignature().FillNamedDefaults(context, named_parameters); table_function.SetCallArguments(parameters, named_parameters); if (table_function.bind || table_function.bind_replace || table_function.bind_operator) { @@ -467,32 +513,18 @@ BoundStatement Binder::Bind(TableFunctionRef &ref) { bool table_in_out = false; ErrorData error; - vector> children; - for (auto &child : fexpr.GetArgumentsMutable()) { - children.push_back(std::move(child.GetExpressionMutable())); - } - - if (!BindTableFunctionParameters(function, children, positional_arguments, named_arguments, subquery, table_in_out, - error)) { + if (!BindTableFunctionParameters(function, fexpr.GetArgumentsMutable(), positional_arguments, named_arguments, + subquery, table_in_out, error)) { error.AddQueryLocation(ref); error.Throw(); } // selection, named-argument checking, folding and casting all happen in the function binder - unique_ptr resolved; - if (table_in_out) { - // the arguments are the columns of the subquery - auto selection = FunctionBinder::SelectFunction(context, function.functions, subquery.types); - if (selection.IsSuccess()) { - auto definition = selection.GetBinding().GetFunction(); - resolved = make_uniq(BoundTableFunction(definition)); - } else { - error = selection.GetError(); - } - } else { - FunctionBinder function_binder(*this); - resolved = function_binder.BindTableFunction(function.functions, positional_arguments, named_arguments, error); - } + FunctionBinder function_binder(*this); + auto resolved = + table_in_out + ? function_binder.BindTableInOutFunction(function.functions, subquery.types, named_arguments, error) + : function_binder.BindTableFunction(function.functions, positional_arguments, named_arguments, error); if (!resolved) { error.AddQueryLocation(ref); error.Throw(); diff --git a/src/duckdb/src/planner/expression/bound_cast_expression.cpp b/src/duckdb/src/planner/expression/bound_cast_expression.cpp index 41876b3a5..e49a82cbf 100644 --- a/src/duckdb/src/planner/expression/bound_cast_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_cast_expression.cpp @@ -173,8 +173,8 @@ bool BoundCastExpression::CastIsInvertible(const LogicalType &source_type, const return false; } if (source_type.id() == LogicalTypeId::DECIMAL || target_type.id() == LogicalTypeId::DECIMAL) { - uint8_t source_width, target_width; - uint8_t source_scale, target_scale; + uint32_t source_width, target_width; + uint32_t source_scale, target_scale; // cast to or from decimal // cast is only invertible if the cast is strictly widening if (!source_type.GetDecimalProperties(source_width, source_scale)) { @@ -308,8 +308,11 @@ static bool NestedCastCanThrow(const LogicalType &source_type, const LogicalType } return BoundCastExpression::CastCanThrow(ListOrArrayChildType(source_type), ListOrArrayChildType(target_type), false); + // TUPLE is an unnamed STRUCT - same physical layout, positional child matching, and the same shared struct + // cast operators, so it can throw exactly when a STRUCT of the same children can. + case LogicalTypeId::TUPLE: case LogicalTypeId::STRUCT: { - if (target_type.id() != LogicalTypeId::STRUCT) { + if (target_type.id() != LogicalTypeId::STRUCT && target_type.id() != LogicalTypeId::TUPLE) { return true; } // Pair the fields as the cast executes them: positionally for unnamed structs, by name otherwise. @@ -350,6 +353,46 @@ static bool NestedCastCanThrow(const LogicalType &source_type, const LogicalType } } +//! The decimal digits that every value of an integer type fits in, e.g. 5 for SMALLINT: no five-digit DECIMAL +//! overflows for 32767 or -32768. 0 for other types, and for HUGEINT and UHUGEINT, whose 39-digit values no DECIMAL +//! holds +static uint8_t IntegerTypeDecimalDigits(const LogicalType &type) { + switch (type.id()) { + case LogicalTypeId::TINYINT: + case LogicalTypeId::UTINYINT: + return 3; + case LogicalTypeId::SMALLINT: + case LogicalTypeId::USMALLINT: + return 5; + case LogicalTypeId::INTEGER: + case LogicalTypeId::UINTEGER: + return 10; + case LogicalTypeId::BIGINT: + return 19; + case LogicalTypeId::UBIGINT: + return 20; + default: + return 0; + } +} + +//! Whether a DECIMAL target holds every value of the source type, so that the cast cannot overflow +static bool DecimalHoldsEveryValue(const LogicalType &source_type, const LogicalType &target_type) { + D_ASSERT(target_type.id() == LogicalTypeId::DECIMAL); + const auto target_integral_digits = DecimalType::GetWidth(target_type) - DecimalType::GetScale(target_type); + if (source_type.id() == LogicalTypeId::DECIMAL) { + // The target needs the digits of the source on both sides of the decimal point: scaling up multiplies by a + // power of ten and keeps every digit, but scaling down rounds, which can carry into one more integral digit + // (9.99 -> DECIMAL(2,1) rounds to 10.0) + const auto source_integral_digits = DecimalType::GetWidth(source_type) - DecimalType::GetScale(source_type); + return DecimalType::GetScale(target_type) >= DecimalType::GetScale(source_type) && + target_integral_digits >= source_integral_digits; + } + // An integer fits when its digits fit before the decimal point: the cast checks the value against 10^(width-scale) + const auto source_digits = IntegerTypeDecimalDigits(source_type); + return source_digits > 0 && target_integral_digits >= source_digits; +} + bool BoundCastExpression::CastCanThrow(const LogicalType &source_type, const LogicalType &target_type, bool try_cast) { if (source_type == target_type) { return false; @@ -397,9 +440,12 @@ bool BoundCastExpression::CastCanThrow(const LogicalType &source_type, const Log if (source_type.IsNested() || target_type.IsNested()) { return NestedCastCanThrow(source_type, target_type); } - // Casting to DECIMAL overflows whenever the value does not fit in the width and scale, e.g. 100 -> DECIMAL(38,37) + // Casting to DECIMAL overflows whenever the value does not fit in the width and scale, e.g. 100 -> DECIMAL(38,37), + // unless the target holds every value of the source type: a DECIMAL that keeps the source's integral and fractional + // digits, or an integer type whose digits fit before the decimal point. The max-type check below cannot decide + // this, since the maximum DECIMAL of two types is capped at the maximum width, e.g. HUGEINT -> DECIMAL(38,0) if (target_type.id() == LogicalTypeId::DECIMAL) { - return true; + return !DecimalHoldsEveryValue(source_type, target_type); } // Casting to a TIMESTAMP overflows for values outside of the timestamp range, even when widening the type, // e.g. a DATE far in the future does not fit in a TIMESTAMP diff --git a/src/duckdb/src/planner/expression/bound_constant_expression.cpp b/src/duckdb/src/planner/expression/bound_constant_expression.cpp index 41f8a477a..5e558567c 100644 --- a/src/duckdb/src/planner/expression/bound_constant_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_constant_expression.cpp @@ -32,8 +32,17 @@ string BoundConstantExpression::ToString() const { //! Two constants are the same expression if their values have the same representation. VARIANT values compare by //! meaning - 1::TINYINT and 1::INTEGER are equal - but as constants they are different: variant_typeof tells them -//! apart, and they hash differently. Vectors compare a VARIANT as the STRUCT it is stored as. +//! apart, and they hash differently. Vectors compare a VARIANT as the STRUCT it is stored as. INTERVALs that are +//! only not distinct after normalization (e.g. INTERVAL 1 MONTH vs INTERVAL 30 DAY) can have different effects in +//! expressions - DATE '2008-05-17' + INTERVAL 1 MONTH is 2008-06-17, but + INTERVAL 30 DAY is 2008-06-16 - so +//! they compare by their raw (months, days, micros) fields, not by normalized equality. static bool SameRepresentation(const Value &left, const Value &right) { + if (left.type().id() == LogicalTypeId::INTERVAL) { + if (left.IsNull() || right.IsNull()) { + return left.IsNull() == right.IsNull(); + } + return left.GetValueUnsafe().SameFields(right.GetValueUnsafe()); + } if (!TypeVisitor::Contains(left.type(), LogicalTypeId::VARIANT)) { return !ValueOperations::DistinctFrom(left, right); } @@ -47,11 +56,21 @@ bool BoundConstantExpression::Equals(const BaseExpression &other_p) const { return false; } auto &other = other_p.Cast(); - return value.type() == other.value.type() && SameRepresentation(value, other.value); + if (value.type() != other.value.type()) { + return false; + } + return SameRepresentation(value, other.value); } hash_t BoundConstantExpression::Hash() const { hash_t result = Expression::Hash(); + if (value.type().id() == LogicalTypeId::INTERVAL && !value.IsNull()) { + // Hash by the raw (months, days, micros) fields: Value::Hash normalizes first, which would put intervals + // that are only equal after normalization in the same bucket and make Equals the deciding factor + auto interval = value.GetValueUnsafe(); + return CombineHash(duckdb::Hash(interval.months) ^ duckdb::Hash(interval.days) ^ duckdb::Hash(interval.micros), + result); + } return CombineHash(value.Hash(), result); } diff --git a/src/duckdb/src/planner/expression_binder/index_binder.cpp b/src/duckdb/src/planner/expression_binder/index_binder.cpp index ef3ca830d..abb3a9d7f 100644 --- a/src/duckdb/src/planner/expression_binder/index_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/index_binder.cpp @@ -15,6 +15,8 @@ #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/function/table/table_scan.hpp" #include "duckdb/planner/operator/logical_create_index.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" namespace duckdb { @@ -75,6 +77,23 @@ 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, @@ -111,6 +130,12 @@ unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, 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()); + } } properties.always_require_rebind = statement_requires_rebind; @@ -132,9 +157,21 @@ BindResult IndexBinder::BindExpression(unique_ptr &expr_ptr, i return BindResult(BinderException::Unsupported(expr, "window functions are not allowed in index expressions")); case ExpressionClass::SUBQUERY: return BindResult(BinderException::Unsupported(expr, "cannot use subquery in index expressions")); - default: + default: { + // restores the previous state on exit, binding is recursive + struct IndexKeyScope { + explicit IndexKeyScope(Binder &binder_p) : binder(binder_p), previous(binder_p.IsBindingIndexKey()) { + binder.SetBindingIndexKey(true); + } + ~IndexKeyScope() { + binder.SetBindingIndexKey(previous); + } + Binder &binder; + bool previous; + } scope(binder); return ExpressionBinder::BindExpression(expr_ptr, depth); } + } } string IndexBinder::UnsupportedAggregateMessage() { diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 7146dced9..6f6c1ac06 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -283,6 +283,11 @@ static optional_ptr TryGetExpressionStats(optional_ptr child_stats; child_stats.reserve(func.GetChildren().size()); for (auto &child_expr : func.GetChildren()) { + if (child_expr->GetExpressionClass() == ExpressionClass::BOUND_LAMBDA) { + // a lambda has no value, the callback of its function derives what it produces + child_stats.push_back(BaseStatistics::CreateUnknown(child_expr->GetReturnType())); + continue; + } auto child_stat = TryGetExpressionStats(context_p, *child_expr, input_stats, owned_stats); if (!child_stat) { return nullptr; diff --git a/src/duckdb/src/planner/logical_operator_repeatability.cpp b/src/duckdb/src/planner/logical_operator_repeatability.cpp index 90b83907f..0990ace8e 100644 --- a/src/duckdb/src/planner/logical_operator_repeatability.cpp +++ b/src/duckdb/src/planner/logical_operator_repeatability.cpp @@ -65,10 +65,8 @@ static LogicalOperatorRepeatability ClassifyOperatorType(LogicalOperator &op) { if (get.GetTable()) { return LogicalOperatorRepeatability::REPEATABLE; } - if (!get.function.is_repeatable || !get.function.is_repeatable(get.bind_data.get())) { - return LogicalOperatorRepeatability::UNKNOWN; - } - return LogicalOperatorRepeatability::REPEATABLE; + return get.function.stability == FunctionStability::VOLATILE ? LogicalOperatorRepeatability::NON_REPEATABLE + : LogicalOperatorRepeatability::REPEATABLE; } case LogicalOperatorType::LOGICAL_SAMPLE: { auto &sample = op.Cast(); diff --git a/src/duckdb/src/planner/operator/logical_external_resource.cpp b/src/duckdb/src/planner/operator/logical_external_resource.cpp index 8c60d2f33..aa835a055 100644 --- a/src/duckdb/src/planner/operator/logical_external_resource.cpp +++ b/src/duckdb/src/planner/operator/logical_external_resource.cpp @@ -11,10 +11,6 @@ idx_t LogicalExternalResource::EstimateCardinality(ClientContext &context) { } void LogicalExternalResource::ResolveTypes() { - if (data.operation == ExternalResourceOperation::SHOW) { - // SHOW is handled as a table-function scan, not this operator. - throw InternalException("LogicalExternalResource does not handle SHOW"); - } types = {LogicalType::BOOLEAN}; } diff --git a/src/duckdb/src/planner/planner.cpp b/src/duckdb/src/planner/planner.cpp index a43040510..8ef4878ea 100644 --- a/src/duckdb/src/planner/planner.cpp +++ b/src/duckdb/src/planner/planner.cpp @@ -208,6 +208,7 @@ void Planner::CreatePlan(SQLStatement &statement) { try { auto binding_timer = profiler.StartTimer(); binder->SetParameters(bound_parameters); + binder->SetStatementParameters(statement.named_param_map); RunPreBindExtensions(context, *binder, statement); auto bound_statement = binder->Bind(statement); binding_timer.EndTimer(); diff --git a/src/duckdb/src/planner/sql_export/sql_export_dml.cpp b/src/duckdb/src/planner/sql_export/sql_export_dml.cpp index 26b10f44c..4898e5805 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_dml.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_dml.cpp @@ -29,35 +29,6 @@ static LogicalPlanVerificationIssue UnsupportedDML(const LogicalPlanVerification return LogicalPlanSQLExportHelpers::PlanUnsupportedFeature(path, std::move(feature), std::move(message)); } -SQLExportDMLHelpers::SelectedRowId SQLExportDMLHelpers::SelectRowIdColumn(const vector &row_id_columns, - const virtual_column_map_t &virtual_columns) { - // A single row-id column is the key by itself. Among several, only the logical row identifier - // can key the generated statement: the remaining columns are physical coordinates, not identity. - SelectedRowId result; - result.count = row_id_columns.size(); - optional selected; - if (row_id_columns.size() == 1) { - selected = row_id_columns[0]; - } else { - for (idx_t i = 0; i < row_id_columns.size(); i++) { - if (row_id_columns[i] == COLUMN_IDENTIFIER_ROW_ID) { - selected = row_id_columns[i]; - result.ordinal = i; - break; - } - } - } - if (!selected) { - return result; - } - auto entry = virtual_columns.find(*selected); - if (entry == virtual_columns.end()) { - return result; - } - result.column = &entry->second; - return result; -} - struct ExportedRowId { Identifier name; //! Index of the key column within the row-id columns the binder appends to the source @@ -66,19 +37,40 @@ struct ExportedRowId { idx_t count; }; -//! The row-id column SQL can reference on the modified table; row-id sets without a logical row id have -//! no SQL key, and a physical column with the row-id name would capture the generated references. +//! The row-id column SQL can reference on the modified table. A single row-id column is the key by +//! itself. Among several, only the logical row identifier can key the generated statement: the +//! remaining columns are physical coordinates, not identity. Row-id sets without such a key have no +//! SQL form, and a physical column with the row-id name would capture the generated references. static LogicalPlanVerificationResult ExportedRowIdName(const TableCatalogEntry &table, const LogicalPlanVerificationPath &path) { auto row_id_columns = table.GetRowIdColumns(); auto virtual_columns = table.GetVirtualColumns(); - auto selected = SQLExportDMLHelpers::SelectRowIdColumn(row_id_columns, virtual_columns); - if (!selected.column || table.ColumnExists(selected.column->name)) { + optional selected; + idx_t ordinal = 0; + if (row_id_columns.size() == 1) { + selected = row_id_columns[0]; + } else { + for (idx_t i = 0; i < row_id_columns.size(); i++) { + if (row_id_columns[i] == COLUMN_IDENTIFIER_ROW_ID) { + selected = row_id_columns[i]; + ordinal = i; + break; + } + } + } + optional_ptr column; + if (selected) { + auto entry = virtual_columns.find(*selected); + if (entry != virtual_columns.end()) { + column = &entry->second; + } + } + if (!column || table.ColumnExists(column->name)) { return LogicalPlanVerificationResult::Failure( {UnsupportedDML(path, "dml_row_id", "The modified table does not expose an exportable row-id column")}); } return LogicalPlanVerificationResult::Success( - {Identifier(selected.column->name), selected.ordinal, selected.count}); + {Identifier(column->name), ordinal, row_id_columns.size()}); } static unique_ptr ModifiedTableRef(const TableCatalogEntry &table) { @@ -322,6 +314,11 @@ static LogicalPlanSQLExportResult ExportMergeNode(LogicalMergeInto &op, LogicalP set_info->columns.push_back(op.table.GetColumns().GetColumn(bound_action->columns[i]).Name()); set_info->expressions.push_back(std::move(value.GetValue())); } + if (set_info->columns.empty()) { + // an update without assignments is expressed as DO NOTHING + action->action_type = MergeActionType::MERGE_DO_NOTHING; + break; + } action->update_info = std::move(set_info); break; } diff --git a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp index e7b0eb79e..05a66cabf 100644 --- a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp +++ b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp @@ -369,6 +369,13 @@ FlattenDependentJoins::DecorrelateSubtreeInternal(unique_ptr &p if (!child_flatten.RequiresDomain(*cte_ref.children[0])) { detached_cte = std::move(plan->children[1]); plan->children[1] = std::move(detached_cte->children[1]); + // the definition is outside this join's domain, but may contain dependent joins of its own + auto old_definition_bindings = detached_cte->children[0]->GetColumnBindings(); + auto definition_state = DecorrelateIndependentSubtree(detached_cte->children[0]); + ColumnBindingRewrite::ApplyToChild(detached_cte, 0, std::move(old_definition_bindings), + 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); @@ -637,11 +644,44 @@ FlattenDependentJoins::AttachDelimToIndependentJoinLeft(unique_ptrGetColumnBindings(); + auto projection_index = binder.GenerateTableIndex(); + op.children[0] = LogicalProjection::CreateIdentity(projection_index, std::move(op.children[0])); + + BindingReplacementGraph replacements; + for (idx_t i = 0; i < old_left_bindings.size(); i++) { + replacements.Add(old_left_bindings[i], ColumnBinding(projection_index, ProjectionIndex(i))); + } + // The projection preserves the left layout, so positional projection maps remain valid. Only the join's own + // bindings move: the projection input keeps the original bindings so the deferred rewrite still finds them. + ColumnBindingRewrite::ApplyToOperatorBindings(op, replacements); + for (auto &binding : outer_state.bindings) { + binding = replacements.Resolve(binding); + } + outer_state.replacement_graph.Merge(replacements); +} + FlattenDependentJoins::UnnestingState FlattenDependentJoins::FinalizeDependentJoin(unique_ptr &plan, UnnestingState outer_state, const UnnestingState &right_state, DependentJoinOutput output) { auto &op = plan->Cast(); + MaterializeCorrelatedAggregateRewrites(op, outer_state); RewriteCorrelatedBindings(op, outer_state.bindings); vector> duplicate_eliminated_columns; @@ -1158,8 +1198,13 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownJoin(unique bool left_requires_domain = RequiresDomain(*plan->children[0]); bool right_requires_domain = RequiresDomain(*plan->children[1]); + // An ASOF join selects at most one match per left row from its entire right input. If the right input + // varies per domain, the left input must carry the domain too, so the selection partitions per domain. + bool selects_over_right = plan->type == LogicalOperatorType::LOGICAL_ASOF_JOIN; + bool can_push_left_only = !right_requires_domain && (join_type == JoinType::INNER || join_type == JoinType::LEFT); - bool can_push_right_only = !left_requires_domain && (join_type == JoinType::INNER || join_type == JoinType::RIGHT); + bool can_push_right_only = + !left_requires_domain && !selects_over_right && (join_type == JoinType::INNER || join_type == JoinType::RIGHT); if (can_push_left_only) { return PushDownSingleCorrelatedChild(plan, propagate_null_values, std::move(state), true); @@ -1217,6 +1262,9 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownJoin(unique auto left_state = PushDownChild(plan, propagate_null_values, right_state.bindings, false, 0); auto &comparison_join = plan->Cast(); + AppendStateToProjectionMap(comparison_join.left_projection_map, + ColumnBindingLayout(plan->children[0]->GetColumnBindings()), + left_state.bindings); auto conditions = std::move(comparison_join.conditions); comparison_join.conditions.clear(); AddCorrelatedJoinConditions(comparison_join, left_state.bindings, right_state.bindings); @@ -1232,6 +1280,8 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownJoin(unique } auto left_state = PushDownChild(plan, propagate_null_values, state, false); + AppendStateToProjectionMap(plan->Cast().left_projection_map, + ColumnBindingLayout(plan->children[0]->GetColumnBindings()), left_state.bindings); auto old_right_bindings = plan->children[1]->GetColumnBindings(); auto independent_state = DecorrelateIndependentSubtree(plan->children[1]); ColumnBindingRewrite::ApplyToChild(plan, 1, std::move(old_right_bindings), independent_state.replacement_graph); diff --git a/src/duckdb/src/planner/table_filter_set.cpp b/src/duckdb/src/planner/table_filter_set.cpp index 7068fb7fc..2e746b486 100644 --- a/src/duckdb/src/planner/table_filter_set.cpp +++ b/src/duckdb/src/planner/table_filter_set.cpp @@ -449,6 +449,45 @@ const vector> &TableFilterSet::GetMultiColumnFilters() c return multi_column_filters; } +vector> DynamicTableFilterSet::AddDisjunction(ProjectionIndex column, + idx_t alternative_count) { + D_ASSERT(alternative_count > 1); + FilterDisjunction disjunction {column, {}}; + for (idx_t i = 0; i < alternative_count; i++) { + disjunction.alternatives.push_back(make_shared_ptr()); + } + disjunctions.push_back(std::move(disjunction)); + return disjunctions.back().alternatives; +} + +vector> DynamicTableFilterSet::GetDisjunctionFilters() const { + vector> result; + for (auto &disjunction : disjunctions) { + for (auto &alternative : disjunction.alternatives) { + result.push_back(*alternative); + } + } + return result; +} + +unique_ptr DynamicTableFilterSet::CopyColumnFilter(ProjectionIndex column) const { + lock_guard l(lock); + auto conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); + for (auto &entry : filters) { + auto filter = entry.second->TryGetFilterByColumnIndex(column); + if (filter) { + conjunction->GetChildrenMutable().push_back(filter->Cast().expr->Copy()); + } + } + if (conjunction->GetChildren().empty()) { + return nullptr; + } + if (conjunction->GetChildren().size() == 1) { + return std::move(conjunction->GetChildrenMutable()[0]); + } + return std::move(conjunction); +} + void DynamicTableFilterSet::ClearFilters(const PhysicalOperator &op) { lock_guard l(lock); filters.erase(op); @@ -471,14 +510,25 @@ void DynamicTableFilterSet::PushFilter(const PhysicalOperator &op, ProjectionInd bool DynamicTableFilterSet::HasFilters() const { lock_guard l(lock); - return !filters.empty(); + if (!filters.empty()) { + return true; + } + for (auto &disjunction : disjunctions) { + bool complete = true; + for (auto &alternative : disjunction.alternatives) { + complete &= alternative->HasFilters(); + } + if (complete) { + return true; + } + } + return false; } unique_ptr DynamicTableFilterSet::GetFinalTableFilters(const PhysicalTableScan &scan, optional_ptr existing_filters) const { lock_guard l(lock); - D_ASSERT(!filters.empty()); auto result = make_uniq(); if (existing_filters) { for (auto &filter_entry : *existing_filters) { @@ -494,6 +544,21 @@ DynamicTableFilterSet::GetFinalTableFilters(const PhysicalTableScan &scan, result->PushFilter(filter_entry.GetIndex(), filter_entry.Filter().Cast().Copy()); } } + for (auto &group : disjunctions) { + auto disjunction = make_uniq(ExpressionType::CONJUNCTION_OR); + bool complete = true; + for (auto &alternative : group.alternatives) { + auto expression = alternative->CopyColumnFilter(group.column); + if (!expression) { + complete = false; + break; + } + disjunction->GetChildrenMutable().push_back(std::move(expression)); + } + if (complete) { + result->PushFilter(group.column, make_uniq(std::move(disjunction))); + } + } if (!result->HasFilters() && !result->HasMultiColumnFilters()) { return nullptr; } diff --git a/src/duckdb/src/planner/table_filter_state.cpp b/src/duckdb/src/planner/table_filter_state.cpp index 3c62323b8..cbb0ff4a2 100644 --- a/src/duckdb/src/planner/table_filter_state.cpp +++ b/src/duckdb/src/planner/table_filter_state.cpp @@ -59,6 +59,75 @@ class OptionalFilterExecutor final : public ExpressionFilterExecutor { } }; +class ConjunctionOrFilterExecutor final : public ExpressionFilterExecutor { +public: + explicit ConjunctionOrFilterExecutor(vector> children_p) + : children(std::move(children_p)), input_sel(STANDARD_VECTOR_SIZE), child_input(STANDARD_VECTOR_SIZE), + result_sel(STANDARD_VECTOR_SIZE), merge_sel(STANDARD_VECTOR_SIZE) { + } + + idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, + idx_t &approved_tuple_count) override { + if (approved_tuple_count == 0) { + return 0; + } + if (approved_tuple_count > input_sel.Capacity()) { + input_sel.Initialize(approved_tuple_count); + child_input.Initialize(approved_tuple_count); + result_sel.Initialize(approved_tuple_count); + merge_sel.Initialize(approved_tuple_count); + } + const auto has_selection = sel.IsSet(); + if (has_selection) { + for (idx_t i = 0; i < approved_tuple_count; i++) { + input_sel.set_index(i, sel.get_index(i)); + } + } + idx_t result_count = 0; + for (auto &child : children) { + SelectionVector child_sel; + if (has_selection) { + for (idx_t i = 0; i < approved_tuple_count; i++) { + child_input.set_index(i, input_sel.get_index(i)); + } + child_sel.Initialize(child_input); + } + auto child_count = approved_tuple_count; + child->FilterSelection(child_sel, vector, scan_count, child_count); + if (child_count == approved_tuple_count) { + if (has_selection) { + sel.Initialize(input_sel); + } + return approved_tuple_count; + } + // Scan filters preserve ordered selections; merge without repeating overlapping matches. + idx_t left = 0; + idx_t right = 0; + idx_t merged_count = 0; + while (left < result_count || right < child_count) { + auto left_index = left < result_count ? result_sel.get_index(left) : scan_count; + auto right_index = right < child_count ? child_sel.get_index(right) : scan_count; + auto index = MinValue(left_index, right_index); + merge_sel.set_index(merged_count++, index); + left += left_index == index; + right += right_index == index; + } + std::swap(result_sel, merge_sel); + result_count = merged_count; + } + sel.Initialize(result_sel); + approved_tuple_count = result_count; + return result_count; + } + +private: + vector> children; + SelectionVector input_sel; + SelectionVector child_input; + SelectionVector result_sel; + SelectionVector merge_sel; +}; + class ComparisonFilterExecutor final : public ExpressionFilterExecutor { public: ComparisonFilterExecutor(ExpressionType comparison_type_p, Value constant_p) @@ -597,7 +666,8 @@ static unique_ptr TryCreateFastExecutor(const Expressi case ExpressionClass::BOUND_FUNCTION: return TryCreateFunctionExecutor(expression.Cast(), inside_selectivity_optional); case ExpressionClass::BOUND_CONJUNCTION: { - if (expression.GetExpressionType() != ExpressionType::CONJUNCTION_AND) { + if (expression.GetExpressionType() != ExpressionType::CONJUNCTION_AND && + expression.GetExpressionType() != ExpressionType::CONJUNCTION_OR) { return nullptr; } auto &conjunction = expression.Cast(); @@ -609,7 +679,10 @@ static unique_ptr TryCreateFastExecutor(const Expressi } children.push_back(std::move(child_executor)); } - return make_uniq(std::move(children)); + if (expression.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + return make_uniq(std::move(children)); + } + return make_uniq(std::move(children)); } default: return nullptr; diff --git a/src/duckdb/src/storage/buffer/block_manager.cpp b/src/duckdb/src/storage/buffer/block_manager.cpp index 1d1263151..25b49a69f 100644 --- a/src/duckdb/src/storage/buffer/block_manager.cpp +++ b/src/duckdb/src/storage/buffer/block_manager.cpp @@ -61,7 +61,8 @@ shared_ptr BlockManager::ConvertToPersistent(QueryContext context, shared_ptr old_block, BufferHandle old_handle, ConvertToPersistentMode mode, optional tag) { auto default_tag = old_block->GetMemory().GetMemoryTag(); - if (default_tag == MemoryTag::IN_MEMORY_TABLE) { + // Persistent table and index payloads can share a block, so they use the same memory tag. + if (default_tag == MemoryTag::IN_MEMORY_TABLE || default_tag == MemoryTag::ART_INDEX) { default_tag = MemoryTag::BASE_TABLE; } // register a block with the new block id diff --git a/src/duckdb/src/storage/buffer_manager.cpp b/src/duckdb/src/storage/buffer_manager.cpp index 077b31859..181cb0f68 100644 --- a/src/duckdb/src/storage/buffer_manager.cpp +++ b/src/duckdb/src/storage/buffer_manager.cpp @@ -23,13 +23,11 @@ const BufferManager &BufferManager::GetBufferManager(const DatabaseInstance &db) } BufferManager &BufferManager::GetBufferManager(ClientContext &context) { - auto &client_data = ClientData::Get(context); - return *client_data.client_buffer_manager; + return context.GetContext().GetBufferManager(); } const BufferManager &BufferManager::GetBufferManager(const ClientContext &context) { - auto &client_data = ClientData::Get(context); - return *client_data.client_buffer_manager; + return context.GetContext().GetBufferManager(); } BufferManager &BufferManager::GetBufferManager(AttachedDatabase &db) { diff --git a/src/duckdb/src/storage/checkpoint/table_data_writer.cpp b/src/duckdb/src/storage/checkpoint/table_data_writer.cpp index 824c3cf48..cbfbbf7fa 100644 --- a/src/duckdb/src/storage/checkpoint/table_data_writer.cpp +++ b/src/duckdb/src/storage/checkpoint/table_data_writer.cpp @@ -1,5 +1,7 @@ #include "duckdb/storage/checkpoint/table_data_writer.hpp" #include "duckdb/common/shared_ptr_ipp.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/storage/checkpoint/pending_publication.hpp" #include "duckdb/storage/checkpoint/table_index_writer.hpp" #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" @@ -21,8 +23,8 @@ namespace duckdb { -TableDataWriter::TableDataWriter(TableCatalogEntry &table_p, QueryContext context) - : table(table_p.Cast()), context(context.GetClientContext()) { +TableDataWriter::TableDataWriter(TableCatalogEntry &table_p, Context &context_p) + : table(table_p.Cast()), context(context_p) { D_ASSERT(table_p.IsDuckTable()); auto storage_compatibility = StorageCompatibility::FromDatabase(table_p.ParentCatalog().GetAttached()); @@ -41,6 +43,10 @@ void TableDataWriter::WriteTableData(Serializer &metadata_serializer) { table.GetStorage().Checkpoint(*this, metadata_serializer); } +void TableDataWriter::AddPendingPublication(unique_ptr publication) { + throw InternalException("This table writer does not support deferred publication"); +} + void TableDataWriter::AddRowGroup(RowGroupPointer &&row_group_pointer, unique_ptr writer) { row_group_pointers.push_back(std::move(row_group_pointer)); } @@ -54,23 +60,20 @@ DatabaseInstance &TableDataWriter::GetDatabase() { } unique_ptr TableDataWriter::CreateTaskExecutor() { - if (context) { - return make_uniq(*context); - } - return make_uniq(TaskScheduler::GetScheduler(GetDatabase())); + return make_uniq(context); } -optional_ptr TableDataWriter::TryGetClientContext() const { +Context &TableDataWriter::GetContext() const { return context; } SingleFileTableDataWriter::SingleFileTableDataWriter(SingleFileCheckpointWriter &checkpoint_manager, TableCatalogEntry &table, MetadataWriter &table_data_writer) - : TableDataWriter(table, checkpoint_manager.GetClientContext()), checkpoint_manager(checkpoint_manager), + : TableDataWriter(table, checkpoint_manager.GetContext()), checkpoint_manager(checkpoint_manager), table_data_writer(table_data_writer) { } -unique_ptr SingleFileTableDataWriter::GetRowGroupWriter(RowGroup &row_group) { +unique_ptr SingleFileTableDataWriter::GetRowGroupWriter() { return make_uniq(table, checkpoint_manager.partial_block_manager, *this, table_data_writer); } @@ -96,6 +99,15 @@ unique_ptr SingleFileTableDataWriter::GetTableIndexWriter(Stor return make_uniq(checkpoint_manager, version); } +bool SingleFileTableDataWriter::CanDeferPublication() const { + return !GetRebuildIndexes(); +} + +void SingleFileTableDataWriter::AddPendingPublication(unique_ptr publication) { + D_ASSERT(CanDeferPublication()); + checkpoint_manager.AddPendingPublication(std::move(publication)); +} + void SingleFileTableDataWriter::FlushPartialBlocks() { checkpoint_manager.partial_block_manager.FlushPartialBlocks(); } diff --git a/src/duckdb/src/storage/checkpoint/table_index_writer.cpp b/src/duckdb/src/storage/checkpoint/table_index_writer.cpp index 89aba0f93..1644b98fd 100644 --- a/src/duckdb/src/storage/checkpoint/table_index_writer.cpp +++ b/src/duckdb/src/storage/checkpoint/table_index_writer.cpp @@ -1,4 +1,5 @@ #include "duckdb/storage/checkpoint/table_index_writer.hpp" +#include "duckdb/storage/checkpoint/pending_publication.hpp" #include "duckdb/storage/partial_block_manager.hpp" #include "duckdb/storage/checkpoint_manager.hpp" @@ -17,16 +18,15 @@ StorageVersion TableIndexWriter::GetStorageVersion() const { SingleFileTableIndexWriter::SingleFileTableIndexWriter(SingleFileCheckpointWriter &checkpoint_manager, const StorageVersion version) - : TableIndexWriter(checkpoint_manager.index_partial_block_manager, version), - checkpoint_manager(checkpoint_manager) { + : TableIndexWriter(checkpoint_manager.partial_block_manager, version), checkpoint_manager(checkpoint_manager) { } PartialBlockManager SingleFileTableIndexWriter::CreatePerIndexPartialBlockManager() { return checkpoint_manager.CreatePerIndexPartialBlockManager(); } -void SingleFileTableIndexWriter::Flush() { - partial_block_manager.FlushPartialBlocks(); +void SingleFileTableIndexWriter::AddPendingPublication(unique_ptr publication) { + checkpoint_manager.AddPendingPublication(std::move(publication)); } } // namespace duckdb 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 ffaf0d9bb..068386f23 100644 --- a/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp +++ b/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp @@ -129,7 +129,7 @@ void WriteOverflowStringsToDisk::Flush() { } // write to disk auto &block_manager = partial_block_manager.GetBlockManager(); - block_manager.Write(partial_block_manager.GetClientContext(), handle.GetFileBuffer(), block_id); + block_manager.Write(partial_block_manager.GetQueryContext(), handle.GetFileBuffer(), block_id); } block_id = INVALID_BLOCK; offset = 0; diff --git a/src/duckdb/src/storage/checkpoint_manager.cpp b/src/duckdb/src/storage/checkpoint_manager.cpp index 7acb7cd93..bb58e20ae 100644 --- a/src/duckdb/src/storage/checkpoint_manager.cpp +++ b/src/duckdb/src/storage/checkpoint_manager.cpp @@ -32,6 +32,7 @@ #include "duckdb/storage/block_manager.hpp" #include "duckdb/storage/checkpoint/table_data_reader.hpp" #include "duckdb/storage/checkpoint/table_data_writer.hpp" +#include "duckdb/storage/checkpoint/pending_publication.hpp" #include "duckdb/storage/metadata/metadata_reader.hpp" #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/table/index_entry.hpp" @@ -41,13 +42,14 @@ #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(optional_ptr context, AttachedDatabase &db_p, +ActiveCheckpointWrapper::ActiveCheckpointWrapper(Context &context, AttachedDatabase &db_p, DuckTransactionManager &transaction_manager_p) : db(db_p), transaction_manager(transaction_manager_p) { - if (!context) { + if (!context.IsClient()) { return; } checkpoint_connection = make_uniq(Connection::CreateInternal(db.GetDatabase())); @@ -101,13 +103,32 @@ optional_ptr ActiveCheckpointWrapper::GetCheckpointContext() cons 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) { +} + +CheckpointWriter::~CheckpointWriter() { +} + void ReorderTableEntries(catalog_entry_vector_t &tables); SingleFileCheckpointWriter::SingleFileCheckpointWriter(QueryContext context, AttachedDatabase &db, - BlockManager &block_manager, CheckpointOptions options_p) - : CheckpointWriter(db), context(context.GetClientContext()), - partial_block_manager(context, block_manager, PartialBlockType::FULL_CHECKPOINT), - index_partial_block_manager(context, block_manager, PartialBlockType::FULL_CHECKPOINT), options(options_p) { + BlockManager &block_manager, CheckpointOptions options_p, + optional_ptr client_context) + : CheckpointWriter(db, context, client_context), + partial_block_manager(GetContext(), block_manager, PartialBlockType::FULL_CHECKPOINT), options(options_p) { +} + +SingleFileCheckpointWriter::~SingleFileCheckpointWriter() { + // Discard pending packable references before destroying their publication owners. + partial_block_manager.ClearBlocks(); +} + +void SingleFileCheckpointWriter::AddPendingPublication(unique_ptr publication) { + D_ASSERT(publication); + pending_publications.push_back(std::move(publication)); } BlockManager &SingleFileCheckpointWriter::GetBlockManager() { @@ -116,7 +137,7 @@ BlockManager &SingleFileCheckpointWriter::GetBlockManager() { } PartialBlockManager SingleFileCheckpointWriter::CreatePerIndexPartialBlockManager() { - return PartialBlockManager(QueryContext(context), GetBlockManager(), PartialBlockType::FULL_CHECKPOINT); + return PartialBlockManager(GetContext(), GetBlockManager(), PartialBlockType::FULL_CHECKPOINT); } MetadataWriter &SingleFileCheckpointWriter::GetMetadataWriter() { @@ -242,7 +263,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { return; } // A context-free checkpoint cannot persist buffered operations on an unbound index. Keep the WAL instead. - if (!context && HasBufferedIndexReplays(db)) { + if (!GetContext().IsClient() && HasBufferedIndexReplays(db)) { return; } // assert that the checkpoint manager hasn't been used before @@ -271,7 +292,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { // 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(context, db, transaction_manager); + ActiveCheckpointWrapper active_checkpoint(GetContext(), db, transaction_manager); auto has_wal = storage_manager.WALStartCheckpoint(meta_block, options, active_checkpoint); checkpoint_context = active_checkpoint.GetCheckpointContext(); @@ -321,6 +342,12 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { }); serializer.End(); + partial_block_manager.FlushPartialBlocks(); + for (auto &pending : pending_publications) { + pending->Publish(); + } + pending_publications.clear(); + metadata_writer->Flush(); table_metadata_writer->Flush(); @@ -337,7 +364,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { header.meta_block = meta_block.block_pointer; header.block_alloc_size = block_manager.GetBlockAllocSize(); header.vector_size = STANDARD_VECTOR_SIZE; - block_manager.WriteHeader(context, header); + block_manager.WriteHeader(QueryContext(GetContext()), header); auto debug_verify_blocks = Settings::Get(db.GetDatabase()); if (debug_verify_blocks) { @@ -353,7 +380,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { } auto &table = entry.Cast(); auto &storage = table.GetStorage(); - auto segment_info = storage.GetColumnSegmentInfo(context); + auto segment_info = storage.GetColumnSegmentInfo(QueryContext(GetContext())); for (auto &segment : segment_info) { verify_block_usage_count[segment.block_id]++; if (StringUtil::Contains(segment.segment_info, "Overflow String Block Ids: ")) { @@ -743,8 +770,8 @@ void SingleFileCheckpointWriter::WriteTable(TableCatalogEntry &table, Serializer serializer.WriteProperty(100, "table", &table); // Explicit checkpoints bind indexes before serialization, so that buffered index operations are replayed - // and not lost on a restart. During a commit-time checkpoint the caller has no active transaction. - if (context && context->transaction.HasActiveTransaction() && checkpoint_context) { + // 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. @@ -791,7 +818,10 @@ void CheckpointReader::ReadTableData(CatalogTransaction transaction, Deserialize // Read next_row_id as total_rows for backwards compatibility. Older storage versions do not allow for gaps in // row_id numbering, in which case next_row_id = total_rows. auto next_row_id = deserializer.ReadPropertyWithExplicitDefault(105, "next_row_id", total_rows); - D_ASSERT(next_row_id >= total_rows); + if (next_row_id < total_rows) { + throw DataCorruptionException("corrupt database file - next row id %llu is lower than the total row count %llu", + next_row_id, total_rows); + } if (!index_storage_infos.empty()) { bound_info.indexes = std::move(index_storage_infos); diff --git a/src/duckdb/src/storage/compression/bitpacking.cpp b/src/duckdb/src/storage/compression/bitpacking.cpp index 4734b26a3..4bae820d8 100644 --- a/src/duckdb/src/storage/compression/bitpacking.cpp +++ b/src/duckdb/src/storage/compression/bitpacking.cpp @@ -1139,6 +1139,117 @@ void BitpackingScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_c BitpackingScanPartial(segment, state, scan_count, result, 0); } +//===--------------------------------------------------------------------===// +// Select +//===--------------------------------------------------------------------===// +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) { + auto &scan_state = state.scan_state->Cast>(); + result.SetVectorType(VectorType::FLAT_VECTOR); + T *result_data = FlatVector::GetDataMutable(result) + result_offset; + + idx_t previous_index = 0; + auto next_index = [&](idx_t sel_idx) { + const idx_t index = sel.get_index(sel_idx); + if (index < previous_index) { + InternalException::Throw("Error in BitpackingSelect - selection vector indices are not ordered"); + } + previous_index = index; + return index; + }; + + idx_t pos = 0; + idx_t i = 0; + 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; + if (!scan_state.HasCurrentGroup()) { + ThrowBitpackingReadPastEnd(); + } + if (scan_state.GetCurrentGroup().AtEnd()) { + if (scan_state.GetCurrentGroup().index + 1 >= scan_state.group_count) { + ThrowBitpackingReadPastEnd(); + } + scan_state.LoadGroup(scan_state.GetCurrentGroup().index + 1); + } + auto &group = scan_state.GetCurrentGroup(); + // rows [pos, run_end) are served by the same (partial) decode + idx_t run_end = pos + group.Remaining(); + switch (group.metadata.mode) { + case BitpackingMode::CONSTANT: + for (; i < sel_count && next_index(i) < run_end; i++) { + result_data[i] = group.constant; + } + break; + case BitpackingMode::CONSTANT_DELTA: + for (; i < sel_count && next_index(i) < run_end; i++) { + idx_t multiplier = group.offset + (sel.get_index(i) - pos); + // Operands read from disk can contain any T value, so use defined wrapping. + result_data[i] = static_cast((static_cast(group.constant) * multiplier) + + static_cast(group.frame_of_reference)); + } + break; + case BitpackingMode::FOR: { + const idx_t offset_in_algorithm_group = + group.offset % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; + run_end = MinValue(run_end, pos + BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE - + offset_in_algorithm_group); + group.UnpackAlgorithmGroups(unsafe_array_ptr(scan_state.decompression_buffer, + BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE)); + for (; i < sel_count && next_index(i) < run_end; i++) { + T_U value = static_cast( + scan_state.decompression_buffer[offset_in_algorithm_group + (sel.get_index(i) - pos)]); + result_data[i] = static_cast(value + static_cast(group.frame_of_reference)); + } + break; + } + default: { + D_ASSERT(group.metadata.mode == BitpackingMode::DELTA_FOR); + const idx_t offset_in_algorithm_group = + group.offset % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; + run_end = MinValue(run_end, pos + BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE - + offset_in_algorithm_group); + group.UnpackAlgorithmGroups(unsafe_array_ptr(scan_state.decompression_buffer, + BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE)); + auto deltas = reinterpret_cast(scan_state.decompression_buffer) + offset_in_algorithm_group; + const T_U frame = static_cast(group.frame_of_reference); + T_U carry = static_cast(group.delta_offset); + const idx_t first = i; + // prefix-sum the deltas up to each selected row, emitting the running value + idx_t cur = pos; + for (; i < sel_count && next_index(i) < run_end; i++) { + const idx_t selected = sel.get_index(i); + for (; cur <= selected; cur++) { + carry += deltas[cur - pos] + frame; + } + result_data[i] = static_cast(carry); + } + if (scan_state.is_bool) { + VerifyBooleanValues(result_data + first, i - first); + } + group.delta_offset = static_cast(carry); + group.Advance(cur - pos); + pos = cur; + if (group.AtEnd() && group.index + 1 == scan_state.group_count) { + scan_state.Finish(); + } + continue; + } + } + // move the group offset to the last selected row so that it matches 'pos' + const idx_t last_row = sel.get_index(i - 1); + group.Advance(last_row - pos); + pos = last_row; + } + // leave the scan state positioned at the end of the vector + if (vector_count > pos) { + scan_state.Skip(vector_count - pos); + } +} + //===--------------------------------------------------------------------===// // Skip //===--------------------------------------------------------------------===// @@ -1185,6 +1296,7 @@ CompressionFunction GetBitpackingFunction(PhysicalType data_type) { BitpackingFinalAnalyze, BitpackingInitCompression, BitpackingCompress, BitpackingFinalizeCompress, BitpackingInitScan, BitpackingScan, BitpackingScanPartial, BitpackingSkip); + bitpacking.select = BitpackingSelect; bitpacking.get_segment_info = BitpackingGetSegmentInfo; return bitpacking; } diff --git a/src/duckdb/src/storage/compression/dict_fsst/analyze.cpp b/src/duckdb/src/storage/compression/dict_fsst/analyze.cpp index 10701ba86..f68369658 100644 --- a/src/duckdb/src/storage/compression/dict_fsst/analyze.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst/analyze.cpp @@ -1,7 +1,10 @@ #include "duckdb/storage/compression/dict_fsst/analyze.hpp" #include "duckdb/common/bitpacking.hpp" +#include "duckdb/common/types/hash.hpp" #include "duckdb/common/types/vector.hpp" +#include "duckdb/storage/block_manager.hpp" +#include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/compression/dict_fsst/common.hpp" namespace duckdb { @@ -53,20 +56,311 @@ DictFSSTAnalyzeState::DictFSSTAnalyzeState(BlockManager &block_manager) : Analyz string_size_limit = GetStringSizeLimit(block_size, false); fsst_string_size_limit = GetStringSizeLimit(block_size, true); + + // a block cannot hold more distinct strings than half its size in bytes, matching the compression state + max_set_size = block_size / 2; + // most blocks hold few distinct values, so start small and grow the set only when it runs out of room + current_set_size = MinValue(INITIAL_SET_SIZE, max_set_size); + current_set = MakeSet(current_set_size); + current_required_space = BlockRequiredSpace(0, 0, 0, 0); +} + +unique_ptr> DictFSSTAnalyzeState::MakeSet(idx_t size) const { + auto &allocator = info.GetBlockManager().buffer_manager.GetBufferAllocator(); + return make_uniq>(allocator, size, 1); +} + +void DictFSSTAnalyzeState::GrowSet() { + D_ASSERT(current_set_size < max_set_size); + current_set_size = MinValue(current_set_size * SET_GROWTH_FACTOR, max_set_size); + auto grown = MakeSet(current_set_size); + // the strings live in 'heap', so the entries carry over as they are + current_set->IterateValues([&](const string_t &value, const string_t &) { grown->Insert(value); }); + current_set = std::move(grown); +} + +idx_t DictFSSTAnalyzeState::RequiredSpace(idx_t tuple_count, idx_t unique_count, idx_t dict_size, + idx_t max_string_length) { + return RequiredSpace(DictionaryAppendState::NOT_ENCODED, tuple_count, unique_count, dict_size, max_string_length, + 0); +} + +idx_t DictFSSTAnalyzeState::RequiredSpace(DictionaryAppendState mode, idx_t tuple_count, idx_t unique_count, + idx_t dict_size, idx_t max_string_length, idx_t symbol_table_size) { + // index 0 of the dictionary is reserved for NULL + const idx_t dict_count = unique_count + 1; + + const auto string_lengths_width = BitpackingPrimitives::MinimumBitWidth(max_string_length); + const auto string_lengths_space = BitpackingPrimitives::GetRequiredSize(dict_count, string_lengths_width); + + idx_t required_space = AlignValue(sizeof(dict_fsst_compression_header_t)); + required_space += dict_size; + required_space = AlignValue(required_space); + if (IsEncoded(mode)) { + required_space += symbol_table_size; + required_space = AlignValue(required_space); + } + required_space += string_lengths_space; + required_space = AlignValue(required_space); + if (mode != DictionaryAppendState::ENCODED_ALL_UNIQUE) { + // when every value is stored there is no selection buffer + const auto dictionary_indices_width = BitpackingPrimitives::MinimumBitWidth(dict_count - 1); + required_space += BitpackingPrimitives::GetRequiredSize(tuple_count, dictionary_indices_width); + } + return required_space; +} + +idx_t DictFSSTAnalyzeState::BlockRequiredSpace(idx_t tuple_count, idx_t unique_count, idx_t dict_size, + idx_t max_string_length) const { + return RequiredSpace(current_mode, tuple_count, unique_count, dict_size, max_string_length, + current_symbol_table_size); +} + +idx_t DictFSSTAnalyzeState::AvailableSpace() const { + if (current_mode == DictionaryAppendState::REGULAR) { + return info.GetBlockSize() - DictFSSTCompression::FSST_SYMBOL_TABLE_SIZE; + } + return info.GetBlockSize(); +} + +idx_t DictFSSTAnalyzeState::EncodedLength(idx_t length) const { + if (!length) { + return 0; + } + return MaxValue((length * fsst_ratio + FSST_RATIO_SCALE - 1) / FSST_RATIO_SCALE, 1); +} + +idx_t DictFSSTAnalyzeState::StoredLength(idx_t length) const { + return IsEncoded(current_mode) ? EncodedLength(length) : length; +} + +idx_t DictFSSTAnalyzeState::SegmentCharge(idx_t required_space) const { + // a segment above the limit is written to a block of its own whose remainder is lost, a smaller one is packed + // with other segments, see PartialBlockManager::RetainOrFlush + if (required_space > info.GetCompactionFlushLimit()) { + return info.GetBlockSize(); + } + return AlignValue(required_space); +} + +void DictFSSTAnalyzeState::MeasureFSST() { + // The writer trains the symbol table on the dictionary of the block. FSST only looks at a sample of what it is + // given, so the first values of the block are enough to tell how well the dictionary compresses. + vector dictionary; + vector lengths; + dictionary.reserve(measure_sample_size); + lengths.reserve(measure_sample.size()); + for (auto &value : measure_sample) { + const auto data = const_data_ptr_cast(value.GetData()); + dictionary.insert(dictionary.end(), data, data + value.GetSize()); + lengths.push_back(value.GetSize()); + } + if (dictionary.empty()) { + return; + } + vector pointers; + pointers.reserve(lengths.size()); + idx_t offset = 0; + for (auto length : lengths) { + pointers.push_back(dictionary.data() + offset); + offset += length; + } + + auto encoder = duckdb_fsst_create(lengths.size(), lengths.data(), pointers.data(), 0); + // as specified in fsst.h, the output buffer has to hold the worst case + vector output(7 + 2 * dictionary.size()); + vector encoded_lengths(lengths.size()); + vector encoded_pointers(lengths.size()); + const auto encoded_count = + duckdb_fsst_compress(encoder, lengths.size(), lengths.data(), pointers.data(), output.size(), output.data(), + encoded_lengths.data(), encoded_pointers.data()); + vector symbol_table(sizeof(duckdb_fsst_decoder_t)); + const idx_t symbol_table_size = duckdb_fsst_export(encoder, symbol_table.data()); + duckdb_fsst_destroy(encoder); + + idx_t encoded_size = 0; + for (auto length : encoded_lengths) { + encoded_size += length; + } + if (encoded_count != lengths.size()) { + // cannot happen with a worst case sized output, but it must not make encoding look attractive + encoded_size = dictionary.size(); + } + // round up, so the estimate is not too optimistic + fsst_ratio = MinValue((encoded_size * FSST_RATIO_SCALE + dictionary.size() - 1) / dictionary.size(), + 2 * FSST_RATIO_SCALE); + fsst_symbol_table_size = symbol_table_size; +} + +DictionaryAppendState DictFSSTAnalyzeState::ChooseEncoding() { + if (disable_fsst || current_dict_size < DictFSSTCompression::DICTIONARY_ENCODE_THRESHOLD) { + return DictionaryAppendState::NOT_ENCODED; + } + // the writer trains a symbol table for every block that gets here, which is too expensive to do while + // analyzing. The ratio is measured on the first block and again after every few more. + encode_decisions++; + if (encode_decisions == next_measurement) { + MeasureFSST(); + next_measurement *= FSST_MEASURE_INTERVAL; + } + + const idx_t encoded_dict_size = EncodedLength(current_dict_size); + if (encoded_dict_size + DictFSSTCompression::DICTIONARY_ENCODE_THRESHOLD > current_dict_size) { + // the dictionary does not compress well enough to be worth it + return DictionaryAppendState::NOT_ENCODED; + } + // The writer encodes into a buffer as big as the dictionary, and FSST only encodes a value while the space left + // holds twice its length and 7 more bytes. A dictionary of a few large values can therefore not be encoded. + // The longest value is assumed to come last, which is the hardest position. + const idx_t space_before_longest = current_dict_size - EncodedLength(current_dict_size - current_max_string_length); + if (space_before_longest < 2 * current_max_string_length + FSST_OUTPUT_SLACK) { + return DictionaryAppendState::NOT_ENCODED; + } + // without NULLs and duplicates every value can be stored as is, which saves the selection buffer + const bool all_unique = !contains_nulls && current_unique_count == current_tuple_count; + const auto mode = all_unique ? DictionaryAppendState::ENCODED_ALL_UNIQUE : DictionaryAppendState::ENCODED; + const idx_t required_space = RequiredSpace(mode, current_tuple_count, current_unique_count, encoded_dict_size, + EncodedLength(current_max_string_length), fsst_symbol_table_size); + if (required_space > info.GetBlockSize()) { + return DictionaryAppendState::NOT_ENCODED; + } + return mode; +} + +void DictFSSTAnalyzeState::SwitchFromRegular() { + D_ASSERT(current_mode == DictionaryAppendState::REGULAR); + current_mode = ChooseEncoding(); + if (!IsEncoded(current_mode)) { + // the layout is the same, the block only stops reserving space for a symbol table + return; + } + current_symbol_table_size = fsst_symbol_table_size; + current_dict_size = EncodedLength(current_dict_size); + current_max_string_length = EncodedLength(current_max_string_length); + current_required_space = + BlockRequiredSpace(current_tuple_count, current_unique_count, current_dict_size, current_max_string_length); + D_ASSERT(current_required_space <= info.GetBlockSize()); +} + +bool DictFSSTAnalyzeState::TryAddIndexOnlyTuple() { + while (true) { + // the dictionary does not change, so only the index buffer can grow, and only when a new packing group starts + idx_t growth = 0; + if (current_mode != DictionaryAppendState::ENCODED_ALL_UNIQUE && + current_tuple_count % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE == 0) { + growth = BitpackingPrimitives::GetRequiredSize(BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE, + current_indices_width); + } + if (current_required_space + growth <= AvailableSpace()) { + current_tuple_count++; + current_required_space += growth; + D_ASSERT(current_required_space == BlockRequiredSpace(current_tuple_count, current_unique_count, + current_dict_size, current_max_string_length)); + return true; + } + if (current_mode != DictionaryAppendState::REGULAR) { + return false; + } + SwitchFromRegular(); + if (current_mode == DictionaryAppendState::ENCODED_ALL_UNIQUE) { + // no lookups are performed in this mode, the value is stored again + return false; + } + } +} + +void DictFSSTAnalyzeState::AddNewString(const string_t &str, optional_idx hash) { + const idx_t str_len = str.GetSize(); + idx_t stored_length; + idx_t required_space; + while (true) { + stored_length = StoredLength(str_len); + // a new value changes the dictionary size and with it the alignment of the sections after it: recompute + required_space = + BlockRequiredSpace(current_tuple_count + 1, current_unique_count + 1, current_dict_size + stored_length, + MaxValue(current_max_string_length, stored_length)); + idx_t admission_space = required_space; + if (current_mode == DictionaryAppendState::ENCODED) { + // The writer encodes the values it adds later, and reserves twice their length until then. It only + // accepts a value when that fits next to everything stored before it. + admission_space = BlockRequiredSpace(current_tuple_count + 1, current_unique_count + 1, + current_dict_size + 2 * str_len + FSST_OUTPUT_SLACK, + MaxValue(current_max_string_length, 2 * str_len)); + } + // the set that finds repeated values holds a limited number of them + const bool set_is_full = + current_mode != DictionaryAppendState::ENCODED_ALL_UNIQUE && current_unique_count >= max_set_size; + if (admission_space <= AvailableSpace() && !set_is_full) { + break; + } + if (current_mode == DictionaryAppendState::REGULAR) { + SwitchFromRegular(); + continue; + } + if (!current_tuple_count) { + throw InternalException("A string does not fit in an empty block while analyzing DICT_FSST"); + } + FlushSimulatedBlock(); + } + + current_tuple_count++; + current_unique_count++; + current_dict_size += stored_length; + current_max_string_length = MaxValue(current_max_string_length, stored_length); + current_indices_width = BitpackingPrimitives::MinimumBitWidth(current_unique_count); + current_required_space = required_space; + + if (current_mode == DictionaryAppendState::ENCODED_ALL_UNIQUE) { + // nothing is looked up in this mode, so the value does not have to be remembered + return; + } + if (current_set->GetSize() == current_set_size) { + GrowSet(); + } + // the block may have been flushed into one that looks values up, while the value was added without a hash + const auto stored = heap.AddBlob(str); + current_set->Insert(stored, hash.IsValid() ? hash.GetIndex() : Hash(str)); + D_ASSERT(!current_set->IsFull()); + if (current_mode == DictionaryAppendState::REGULAR && measure_sample_size < FSST_MEASURE_SIZE) { + measure_sample.push_back(stored); + measure_sample_size += str_len; + } +} + +void DictFSSTAnalyzeState::FlushSimulatedBlock() { + simulated_space += SegmentCharge(current_required_space); + current_mode = disable_fsst ? DictionaryAppendState::NOT_ENCODED : DictionaryAppendState::REGULAR; + current_tuple_count = 0; + current_unique_count = 0; + current_dict_size = 0; + current_max_string_length = 0; + current_symbol_table_size = 0; + current_indices_width = 0; + current_required_space = BlockRequiredSpace(0, 0, 0, 0); + current_set->Clear(); + measure_sample.clear(); + measure_sample_size = 0; + // the strings are only referenced by 'current_set' and 'measure_sample', which we just cleared; keep the current + // chunk for the next block + heap.GetAllocator().Reset(); } bool DictFSSTAnalyzeState::Analyze(const Vector &input) { for (auto entry : input.Values()) { if (!entry.IsValid()) { contains_nulls = true; + // NULL is dictionary index 0, it does not occupy a dictionary entry of its own + if (!TryAddIndexOnlyTuple()) { + FlushSimulatedBlock(); + // an empty block always has room for one more index + const bool added = TryAddIndexOnlyTuple(); + D_ASSERT(added); + (void)added; + } continue; } auto &str = entry.GetValue(); auto str_len = str.GetSize(); - total_string_length += str_len; - if (str_len > max_string_length) { - max_string_length = str_len; - } if (str_len >= string_size_limit) { // A segment cannot be spread out over multiple blocks, so if a string cannot fit in an empty segment // the encoding will fail @@ -76,13 +370,46 @@ bool DictFSSTAnalyzeState::Analyze(const Vector &input) { // FSST strings may be up to two times larger than their plain equivalent disable_fsst = true; } + + if (current_mode == DictionaryAppendState::ENCODED_ALL_UNIQUE) { + // the writer does not look values up in this mode, every one is stored + AddNewString(str, optional_idx()); + continue; + } + const auto hash = Hash(str); + if (!current_set->Lookup(str, hash).IsEmpty()) { + if (TryAddIndexOnlyTuple()) { + continue; + } + if (current_mode != DictionaryAppendState::ENCODED_ALL_UNIQUE) { + // the next block starts with an empty dictionary, so this value has to be stored again + FlushSimulatedBlock(); + } + } + AddNewString(str, hash); } total_count += input.size(); return true; } idx_t DictFSSTAnalyzeState::FinalAnalyze() { - return LossyNumericCast((double)total_string_length / 2.0); + // the simulation is complete, free its set before the compression state allocates a dictionary of its own + current_set.reset(); + measure_sample.clear(); + heap.Destroy(); + + if (!total_count) { + return 0; + } + + // Every block carries its own dictionary, so a value repeated across blocks is stored once per block. + // Charging the simulated segments the way they are stored also charges for the space wasted in blocks that a + // large dictionary left mostly empty - which a ratio of the raw size cannot express. + idx_t estimate = simulated_space; + if (current_tuple_count) { + estimate += SegmentCharge(current_required_space); + } + return estimate; } } // namespace dict_fsst diff --git a/src/duckdb/src/storage/compression/dict_fsst/compression.cpp b/src/duckdb/src/storage/compression/dict_fsst/compression.cpp index 252d3a1e8..7293199fa 100644 --- a/src/duckdb/src/storage/compression/dict_fsst/compression.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst/compression.cpp @@ -32,12 +32,6 @@ DictFSSTCompressionState::~DictFSSTCompressionState() { } } -static constexpr idx_t DICTIONARY_ENCODE_THRESHOLD = 4096; - -static inline bool IsEncoded(DictionaryAppendState state) { - return state == DictionaryAppendState::ENCODED || state == DictionaryAppendState::ENCODED_ALL_UNIQUE; -} - static DictFSSTMode ConvertToMode(DictionaryAppendState &state) { switch (state) { case DictionaryAppendState::ENCODED: @@ -135,23 +129,6 @@ idx_t DictFSSTCompressionState::Finalize() { return required_space; } -idx_t DictFSSTCompressionState::CalculateRequiredSpace() const { - idx_t required_space = 0; - required_space += sizeof(dict_fsst_compression_header_t); - required_space = AlignValue(required_space); - required_space += dictionary_offset + to_encode_string_sum; - required_space = AlignValue(required_space); - if (IsEncoded(append_state)) { - required_space += symbol_table_size; - required_space = AlignValue(required_space); - } - required_space += string_lengths_space; - required_space = AlignValue(required_space); - required_space += dictionary_indices_space; - - return required_space; -} - void DictFSSTCompressionState::FlushEncodingBuffer() { if (dictionary_encoding_buffer.empty()) { D_ASSERT(to_encode_string_sum == 0); @@ -666,7 +643,7 @@ bool DictFSSTCompressionState::AllUnique() const { DictionaryAppendState DictFSSTCompressionState::TryEncode() { //! We were appending normally, the segment is full - if (dictionary_offset < DICTIONARY_ENCODE_THRESHOLD) { + if (dictionary_offset < DictFSSTCompression::DICTIONARY_ENCODE_THRESHOLD) { return DictionaryAppendState::NOT_ENCODED; } @@ -729,7 +706,7 @@ DictionaryAppendState DictFSSTCompressionState::TryEncode() { max_length = str_len; } } - if (new_size + DICTIONARY_ENCODE_THRESHOLD > dictionary_offset) { + if (new_size + DictFSSTCompression::DICTIONARY_ENCODE_THRESHOLD > dictionary_offset) { can_use_encoding = false; break; } @@ -886,9 +863,5 @@ void DictFSSTCompressionState::Compress(const Vector &scan_vector) { } } -void DictFSSTCompressionState::FinalizeCompress() { - Flush(true); -} - } // namespace dict_fsst } // namespace duckdb diff --git a/src/duckdb/src/storage/compression/validity_uncompressed.cpp b/src/duckdb/src/storage/compression/validity_uncompressed.cpp index 66f8b809c..1f72f11b0 100644 --- a/src/duckdb/src/storage/compression/validity_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/validity_uncompressed.cpp @@ -578,7 +578,8 @@ idx_t ValidityAppend(CompressionAppendState &append_state, ColumnSegment &segmen return append_count; } - ValidityMask mask(reinterpret_cast(append_state.handle.GetDataMutable()), max_tuples); + ValidityMask mask(reinterpret_cast(append_state.handle.GetDataMutable() + segment.GetBlockOffset()), + max_tuples); for (idx_t i = 0; i < append_count; i++) { auto idx = data.sel->get_index(offset + i); if (!data.validity.RowIsValidUnsafe(idx)) { diff --git a/src/duckdb/src/storage/compression/zstd.cpp b/src/duckdb/src/storage/compression/zstd.cpp index de32407e8..2f08c8f33 100644 --- a/src/duckdb/src/storage/compression/zstd.cpp +++ b/src/duckdb/src/storage/compression/zstd.cpp @@ -302,7 +302,7 @@ class ZSTDCompressionState : public CompressionState { buffer_collection.SetCurrentBuffer(buffer.slot); auto &buffer_handle = buffer_collection.BufferHandleMutable(); if (!buffer_handle.IsValid()) { - buffer_handle = buffer_manager.Allocate(partial_block_manager.GetClientContext(), + buffer_handle = buffer_manager.Allocate(partial_block_manager.GetQueryContext(), MemoryTag::OVERFLOW_STRINGS, &block_manager); } return; @@ -474,7 +474,7 @@ class ZSTDCompressionState : public CompressionState { // Write the current page to disk auto &block_manager = partial_block_manager.GetBlockManager(); - block_manager.Write(partial_block_manager.GetClientContext(), buffer.GetFileBuffer(), block_id); + block_manager.Write(partial_block_manager.GetQueryContext(), buffer.GetFileBuffer(), block_id); } void FlushVector() { @@ -545,7 +545,7 @@ class ZSTDCompressionState : public CompressionState { auto &buffer_manager = BufferManager::GetBufferManager(checkpoint_data.GetDatabase()); buffer_collection.segment_handle = - buffer_manager.Pin(partial_block_manager.GetClientContext(), buffer_collection.segment->GetBlockHandle()); + buffer_manager.Pin(partial_block_manager.GetQueryContext(), buffer_collection.segment->GetBlockHandle()); } void FlushSegment() { @@ -959,7 +959,6 @@ struct ZSTDScanState : public SegmentScanState { remaining -= to_scan; } scan_state.scanned_count += count; - scanned_count += count; } void ScanInternal(ZSTDVectorScanState &scan_state, idx_t count, Vector &result, idx_t result_offset) { @@ -983,7 +982,6 @@ struct ZSTDScanState : public SegmentScanState { offset += string_lengths[i]; } scan_state.scanned_count += count; - scanned_count += count; } void ScanPartial(idx_t start_idx, Vector &result, idx_t offset, idx_t count) { @@ -1019,8 +1017,6 @@ struct ZSTDScanState : public SegmentScanState { //! The amount of tuples stored in the segment idx_t segment_count; - //! The amount of tuples consumed - idx_t scanned_count = 0; ColumnSegment &segment; //! Buffer for skipping data diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index 3de24794a..6cd9d6276 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -27,6 +27,7 @@ #include "duckdb/planner/expression_binder/check_binder.hpp" #include "duckdb/planner/expression_binder/constant_binder.hpp" #include "duckdb/planner/table_filter.hpp" +#include "duckdb/storage/checkpoint/pending_publication.hpp" #include "duckdb/storage/checkpoint/table_data_writer.hpp" #include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table/append_state.hpp" @@ -109,7 +110,7 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, ColumnDefinition this->row_groups = parent.row_groups->AddColumn(context, new_column, default_executor); // also add this column to client local storage - local_storage.AddColumn(parent, *this, new_column, default_executor); + local_storage.AddColumn(context, parent, *this, new_column, default_executor); // this table replaces the previous table, hence the parent is no longer the root DataTable parent.version = DataTableVersion::ALTERED; @@ -227,7 +228,7 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, idx_t changed_id rewrite_visibility); // scan the original table, and fill the new column with the transformed value - local_storage.ChangeType(parent, *this, changed_idx, target_type, bound_columns, cast_expr); + local_storage.ChangeType(context, parent, *this, changed_idx, target_type, bound_columns, cast_expr); // re-verify any column constraint that the rewrite could have violated (e.g. NOT NULL) if (constraint_to_verify) { @@ -277,7 +278,7 @@ void DataTable::InitializeScan(ClientContext &context, DuckTransaction &transact auto &local_storage = LocalStorage::Get(transaction); state.Initialize(column_ids, context, table_filters); row_groups->InitializeScan(context, state.table_state, column_ids, table_filters); - local_storage.InitializeScan(*this, state.local_state, table_filters); + local_storage.InitializeScan(context, *this, state.local_state, table_filters); } void DataTable::InitializeScanWithOffset(DuckTransaction &transaction, TableScanState &state, @@ -525,7 +526,7 @@ void DataTable::Fetch(DuckTransaction &transaction, DataChunk &result, const vec D_ASSERT(result.size() == committed_count); // Fetch local rows into a separate chunk. - auto &allocator = Allocator::Get(local_storage.GetClientContext()); + auto &allocator = Allocator::Get(local_storage.GetContext().GetDatabase()); DataChunk local_chunk; local_chunk.Initialize(allocator, result.GetTypes()); Vector local_row_ids(row_identifiers, local_sel, local_count); @@ -714,7 +715,7 @@ void DataTable::VerifyForeignKeyConstraint(optional_ptr stora // Local constraint verification. if (local_verification) { - auto &local_indexes = local_storage.GetIndexes(context, data_table); + auto &local_indexes = local_storage.GetIndexes(data_table); local_indexes.VerifyForeignKey(sibling_delete_indexes, dst_keys_ptr, dst_chunk, local_conflict_manager); local_error = IsForeignKeyConstraintError(local_conflict_manager, is_append, count); } @@ -740,7 +741,7 @@ void DataTable::VerifyForeignKeyConstraint(optional_ptr stora throw ConstraintException(message); } - auto &transact_index = local_storage.GetIndexes(context, data_table); + auto &transact_index = local_storage.GetIndexes(data_table); transaction_index_entry = transact_index.FindForeignKeyIndex(dst_keys_ptr, fk_type); if (local_error && global_error && is_append) { @@ -806,7 +807,7 @@ void DataTable::VerifyNewConstraint(LocalStorage &local_storage, DataTable &pare throw NotImplementedException("FIXME: ALTER COLUMN with such constraint is not supported yet"); } - parent.row_groups->VerifyNewConstraint(local_storage.GetClientContext(), local_storage.GetTransaction(), parent, + parent.row_groups->VerifyNewConstraint(local_storage.GetContext(), local_storage.GetTransaction(), parent, constraint); local_storage.VerifyNewConstraint(parent, constraint); } @@ -1587,6 +1588,39 @@ unique_ptr DataTable::GetSample() { //===--------------------------------------------------------------------===// // Checkpoint //===--------------------------------------------------------------------===// +namespace { + +class PendingRowGroupCollectionPublication final : public PendingPublication { +public: + PendingRowGroupCollectionPublication(shared_ptr table_p, CollectionCheckpointResult result_p, + TableStatistics checkpoint_stats_p) + : table(std::move(table_p)), result(std::move(result_p)), checkpoint_stats(std::move(checkpoint_stats_p)) { + D_ASSERT(table); + } + + const TableStatistics &GetStatistics() const { + return checkpoint_stats; + } + + void Publish() override { + table->PublishCheckpoint(std::move(result), checkpoint_stats); + } + +private: + //! Keep the collection's owner alive until the prepared state is released. + shared_ptr table; + CollectionCheckpointResult result; + TableStatistics checkpoint_stats; +}; + +} // namespace + +void DataTable::PublishCheckpoint(CollectionCheckpointResult result, TableStatistics &checkpoint_stats) { + lock_guard lock(append_lock); + row_groups->InstallCheckpoint(std::move(result), checkpoint_stats); + row_groups->SetRowGroupAppendMode(RowGroupAppendMode::SUGGEST_NEW); +} + void DataTable::Checkpoint(TableDataWriter &writer, Serializer &serializer) { TableStatistics global_stats; CollectionCheckpointSnapshot snapshot; @@ -1594,21 +1628,29 @@ void DataTable::Checkpoint(TableDataWriter &writer, Serializer &serializer) { lock_guard lock(append_lock); snapshot = row_groups->SnapshotForCheckpoint(writer); } + // checkpoint each individual row group auto result = row_groups->Checkpoint(writer, global_stats, snapshot); - { - lock_guard lock(append_lock); - row_groups->InstallCheckpoint(std::move(result), global_stats); - row_groups->SetRowGroupAppendMode(RowGroupAppendMode::SUGGEST_NEW); - } - if (writer.GetRebuildIndexes()) { - MetricsTimer timer; - auto context = writer.TryGetClientContext(); - if (context) { - timer = QueryProfiler::Get(*context).StartTimer(); + auto publication = + make_uniq(shared_from_this(), std::move(result), std::move(global_stats)); + const auto &checkpoint_stats = publication->GetStatistics(); + if (writer.CanDeferPublication()) { + D_ASSERT(!writer.RowIdsChanged() || + writer.GetCheckpointOptions().type != CheckpointType::CONCURRENT_CHECKPOINT); + D_ASSERT(!writer.GetRebuildIndexes()); + writer.AddPendingPublication(std::move(publication)); + } else { + // we cannot defer the publish of the collection when rebuilding needs it immediately + publication->Publish(); + if (writer.GetRebuildIndexes()) { + MetricsTimer timer; + auto profiler = writer.GetContext().TryGetQueryProfiler(); + if (profiler) { + timer = profiler->StartTimer(); + } + RebuildIndexes(); + timer.EndTimer(); } - RebuildIndexes(); - timer.EndTimer(); } const auto storage_version = serializer.GetOptions().storage_compatibility.storage_version; @@ -1619,7 +1661,7 @@ void DataTable::Checkpoint(TableDataWriter &writer, Serializer &serializer) { index_infos = info->GetIndexes().Checkpoint(*index_writer); } - writer.FinalizeTable(global_stats, *info, *row_groups, index_infos, serializer); + writer.FinalizeTable(checkpoint_stats, *info, *row_groups, index_infos, serializer); } void DataTable::CommitDropColumn(const idx_t column_index, CommitDropState &drop_state) { diff --git a/src/duckdb/src/storage/database_handle.cpp b/src/duckdb/src/storage/database_handle.cpp index 36f4ac369..dc5127b4d 100644 --- a/src/duckdb/src/storage/database_handle.cpp +++ b/src/duckdb/src/storage/database_handle.cpp @@ -16,9 +16,8 @@ DatabaseHandle::DatabaseHandle(unique_ptr mmap_handle_p) : mma //! file uses the settings of the session that attached it (http_proxy, ca_cert_file, ...) and reports its requests to //! that session's logger. Without a client, the database-wide file system only sees global settings. static FileSystem &GetDatabaseFileSystem(QueryContext context, AttachedDatabase &db) { - auto client_context = context.GetClientContext(); - if (client_context) { - return FileSystem::GetFileSystem(*client_context); + if (context.Valid()) { + return context.GetContext()->GetFileSystem(); } return FileSystem::Get(db); } diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index ee9e59d52..597dd4e0c 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -309,8 +309,8 @@ CachingFileHandle::CachingFileHandle(QueryContext context, CachingFileSystem &ca optional_ptr opener_p) : context(context), file_system(caching_file_system_p.file_system), db(caching_file_system_p.db), external_file_cache(caching_file_system_p.external_file_cache), path(path_p), flags(std::move(flags_p)), - opener(opener_p), validate(ExternalFileCacheUtil::GetCacheValidationMode(path_p, context.GetClientContext(), - caching_file_system_p.db)), + opener(opener_p), + validate(ExternalFileCacheUtil::GetCacheValidationMode(path_p, context.GetContext(), caching_file_system_p.db)), cached_file(nullptr), position(0) { cached_file = external_file_cache.GetOrCreateCachedFile(path_p.path); if (!external_file_cache.IsEnabled() || Validate()) { diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp index c54fb20a8..b5df812f0 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp @@ -393,6 +393,10 @@ void CachingFileSystemWrapper::SetDisabledFileSystems(const vector &name underlying_file_system.SetDisabledFileSystems(names); } +vector CachingFileSystemWrapper::GetDisabledFileSystems() { + return underlying_file_system.GetDisabledFileSystems(); +} + bool CachingFileSystemWrapper::SubSystemIsDisabled(const string &name) { return underlying_file_system.SubSystemIsDisabled(name); } diff --git a/src/duckdb/src/storage/external_file_cache/external_file_cache_util.cpp b/src/duckdb/src/storage/external_file_cache/external_file_cache_util.cpp index a1b36afd0..25ef46eb9 100644 --- a/src/duckdb/src/storage/external_file_cache/external_file_cache_util.cpp +++ b/src/duckdb/src/storage/external_file_cache/external_file_cache_util.cpp @@ -11,13 +11,13 @@ #include "duckdb/common/enums/cache_validation_mode.hpp" #include "duckdb/common/open_file_info.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/settings.hpp" namespace duckdb { CacheValidationMode ExternalFileCacheUtil::GetCacheValidationMode(const OpenFileInfo &info, - optional_ptr client_context, - DatabaseInstance &db) { + optional_ptr context, DatabaseInstance &db) { // First check if explicitly set in OpenFileInfo options (per-file override). bool validate_cache; if (info.extended_info != nullptr && @@ -25,12 +25,12 @@ CacheValidationMode ExternalFileCacheUtil::GetCacheValidationMode(const OpenFile return validate_cache ? CacheValidationMode::VALIDATE_ALL : CacheValidationMode::NO_VALIDATION; } - // If client context is available, check client-local settings first, then fall back to database config. - if (client_context) { - return Settings::Get(*client_context); + // If context are available, check client-local settings first, then fall back to database config. + if (context) { + return Settings::Get(*context); } - // No client context, fall back to database config. + // No context, fall back to database config. return Settings::Get(db); } diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index f5bacd046..3e97b3910 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -20,7 +20,7 @@ namespace duckdb { -LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &table) +LocalTableStorage::LocalTableStorage(Context &context, DataTable &table) : context(context), table_ref(table), allocator(Allocator::Get(table.db)), deleted_rows(0), optimistic_writer(context, table) { auto types = table.GetTypes(); @@ -37,7 +37,7 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data const idx_t alter_column_index, const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr, TransactionData transaction) - : context(context), table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), + : context(parent.context), table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), deleted_rows(parent.deleted_rows.load()), optimistic_collections(std::move(parent.optimistic_collections)), optimistic_writer(new_data_table, parent.optimistic_writer) { // Alter the column type. @@ -55,8 +55,8 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data LocalTableStorage::LocalTableStorage(DataTable &new_data_table, LocalTableStorage &parent, const idx_t drop_column_index) - : table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), deleted_rows(parent.deleted_rows.load()), - optimistic_collections(std::move(parent.optimistic_collections)), + : context(parent.context), table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), + deleted_rows(parent.deleted_rows.load()), optimistic_collections(std::move(parent.optimistic_collections)), optimistic_writer(new_data_table, parent.optimistic_writer) { // Remove the column from the previous table storage. auto &parent_collection = *parent.row_groups->collection; @@ -72,8 +72,8 @@ LocalTableStorage::LocalTableStorage(DataTable &new_data_table, LocalTableStorag LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_dt, LocalTableStorage &parent, ColumnDefinition &new_column, ExpressionExecutor &default_executor) - : table_ref(new_dt), allocator(Allocator::Get(new_dt.db)), deleted_rows(parent.deleted_rows.load()), - optimistic_collections(std::move(parent.optimistic_collections)), + : context(parent.context), table_ref(new_dt), allocator(Allocator::Get(new_dt.db)), + deleted_rows(parent.deleted_rows.load()), optimistic_collections(std::move(parent.optimistic_collections)), optimistic_writer(new_dt, parent.optimistic_writer) { auto &parent_collection = *parent.row_groups->collection; auto new_collection = parent_collection.AddColumn(context, new_column, default_executor); @@ -87,12 +87,13 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_dt, LocalTableStorage::~LocalTableStorage() { } -void LocalTableStorage::InitializeScan(CollectionScanState &state, optional_ptr table_filters) { +void LocalTableStorage::InitializeScan(const QueryContext &scan_context, CollectionScanState &state, + optional_ptr table_filters) { auto &collection = *row_groups->collection; if (collection.GetTotalRows() == 0) { throw InternalException("No rows in LocalTableStorage row group for scan"); } - collection.InitializeScan(context, state, state.GetColumnIds(), table_filters.get()); + collection.InitializeScan(scan_context, state, state.GetColumnIds(), table_filters.get()); } idx_t LocalTableStorage::EstimatedSize() const { @@ -307,7 +308,7 @@ optional_ptr LocalTableManager::GetStorage(const DataTable &t return entry == table_storage.end() ? nullptr : entry->second.get(); } -LocalTableStorage &LocalTableManager::GetOrCreateStorage(ClientContext &context, DataTable &table) { +LocalTableStorage &LocalTableManager::GetOrCreateStorage(Context &context, DataTable &table) { lock_guard l(table_storage_lock); auto entry = table_storage.find(table); if (entry == table_storage.end()) { @@ -369,7 +370,7 @@ void LocalTableManager::InsertEntry(DataTable &table, shared_ptr table_filters) { auto storage = table_manager.GetStorage(table); if (storage == nullptr || storage->GetCollection().GetTotalRows() == 0) { return; } - storage->InitializeScan(state, table_filters); + storage->InitializeScan(context, state, table_filters); } void LocalStorage::Scan(CollectionScanState &state, const vector &, DataChunk &result) { @@ -750,7 +751,7 @@ void LocalStorage::MoveStorage(DataTable &old_dt, DataTable &new_dt) { table_manager.InsertEntry(new_dt, std::move(new_storage)); } -void LocalStorage::AddColumn(DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, +void LocalStorage::AddColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, ExpressionExecutor &default_executor) { // check if there are any pending appends for the old version of the table auto storage = table_manager.MoveEntry(old_dt); @@ -771,8 +772,9 @@ void LocalStorage::DropColumn(DataTable &old_dt, DataTable &new_dt, const idx_t table_manager.InsertEntry(new_dt, std::move(new_storage)); } -void LocalStorage::ChangeType(DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, const LogicalType &target_type, - const vector &bound_columns, Expression &cast_expr) { +void LocalStorage::ChangeType(ClientContext &context, DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, + const LogicalType &target_type, const vector &bound_columns, + Expression &cast_expr) { // check if there are any pending appends for the old version of the table auto storage = table_manager.MoveEntry(old_dt); if (!storage) { @@ -800,7 +802,7 @@ bool LocalStorage::CanFetch(DataTable &table, const row_t row_id) { return storage->GetCollection().CanFetch(transaction, row_id); } -TableIndexList &LocalStorage::GetIndexes(ClientContext &context, DataTable &table) { +TableIndexList &LocalStorage::GetIndexes(DataTable &table) { auto &storage = table_manager.GetOrCreateStorage(context, table); return storage.append_indexes; } diff --git a/src/duckdb/src/storage/metadata/metadata_manager.cpp b/src/duckdb/src/storage/metadata/metadata_manager.cpp index 7eb7b4adf..2e5128f6a 100644 --- a/src/duckdb/src/storage/metadata/metadata_manager.cpp +++ b/src/duckdb/src/storage/metadata/metadata_manager.cpp @@ -236,8 +236,8 @@ MetadataPointer MetadataManager::FromDiskPointerInternal(unique_lock &blo auto entry = blocks.find(block_id); if (entry == blocks.end()) { // LCOV_EXCL_START - throw InternalException("Failed to load metadata pointer (id %llu, idx %llu, ptr %llu)\n", block_id, index, - pointer.block_pointer); + throw DataCorruptionException("Failed to load metadata pointer (id %llu, idx %llu, ptr %llu)\n", block_id, + index, pointer.block_pointer); } // LCOV_EXCL_STOP MetadataPointer result; result.block_index = UnsafeNumericCast(block_id); diff --git a/src/duckdb/src/storage/optimistic_data_writer.cpp b/src/duckdb/src/storage/optimistic_data_writer.cpp index 3d9ed96f6..77464a9b8 100644 --- a/src/duckdb/src/storage/optimistic_data_writer.cpp +++ b/src/duckdb/src/storage/optimistic_data_writer.cpp @@ -14,11 +14,15 @@ namespace duckdb { OptimisticWriteCollection::~OptimisticWriteCollection() { } -OptimisticDataWriter::OptimisticDataWriter(ClientContext &context, DataTable &table) : context(context), table(table) { +OptimisticDataWriter::OptimisticDataWriter(ClientContext &context, DataTable &table) + : OptimisticDataWriter(context.GetContext(), table) { +} + +OptimisticDataWriter::OptimisticDataWriter(Context &context, DataTable &table) : context(context), table(table) { } OptimisticDataWriter::OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent) - : context(parent.GetClientContext()), table(table) { + : context(parent.GetContext()), table(table) { if (parent.partial_manager) { parent.partial_manager->ClearBlocks(); } @@ -66,8 +70,8 @@ unique_ptr OptimisticDataWriter::CreateCollection(Dat if (type == OptimisticWritePartialManagers::PER_COLUMN) { for (idx_t i = 0; i < insert_types.size(); i++) { auto &block_manager = table.GetTableIOManager().GetBlockManagerForRowData(); - result->partial_block_managers.push_back(make_uniq( - QueryContext(context), block_manager, PartialBlockType::APPEND_TO_TABLE)); + result->partial_block_managers.push_back( + make_uniq(context, block_manager, PartialBlockType::APPEND_TO_TABLE)); } } return result; @@ -93,7 +97,7 @@ void OptimisticDataWriter::WriteNewRowGroup(OptimisticWriteCollection &row_group if (!need_to_flush) { // we don't need to flush based on the amount of row groups - but we still might need to flush based on the // amount of - auto &config = DBConfig::GetConfig(context); + auto &config = DBConfig::GetConfig(context.GetDatabase()); auto memory_limit = config.GetWriteBufferMemoryLimit(); if (row_groups.unflushed_data_size >= memory_limit) { // we exhausted our memory available for buffering - flush diff --git a/src/duckdb/src/storage/partial_block_manager.cpp b/src/duckdb/src/storage/partial_block_manager.cpp index 2926fc51c..4699acebd 100644 --- a/src/duckdb/src/storage/partial_block_manager.cpp +++ b/src/duckdb/src/storage/partial_block_manager.cpp @@ -242,10 +242,10 @@ void PartialBlock::Clear() { // PartialBlockManager //===--------------------------------------------------------------------===// -PartialBlockManager::PartialBlockManager(QueryContext context, BlockManager &block_manager, +PartialBlockManager::PartialBlockManager(Context &context_p, BlockManager &block_manager, PartialBlockType partial_block_type, optional_idx max_partial_block_size_p, uint32_t max_use_count) - : context(context.GetClientContext()), block_manager(block_manager), partial_block_type(partial_block_type), + : context(context_p), block_manager(block_manager), partial_block_type(partial_block_type), max_use_count(max_use_count) { if (max_partial_block_size_p.IsValid()) { max_partial_block_size = NumericCast(max_partial_block_size_p.GetIndex()); @@ -302,7 +302,7 @@ void PartialBlockManager::ClearBlocks() { void PartialBlockManager::FlushPartialBlocks() { for (auto &e : partially_filled_blocks) { - e.second->Flush(context, partial_block_type); + e.second->Flush(GetQueryContext(), partial_block_type); } partially_filled_blocks.clear(); } @@ -365,18 +365,18 @@ void PartialBlockManager::RetainOrFlush(unique_ptr partial_block) auto available_space = partial_block->AvailableSpace(); if (partial_block->UseCount() >= max_use_count) { - partial_block->Flush(context, partial_block_type); + partial_block->Flush(GetQueryContext(), partial_block_type); return; } if (available_space < min_reusable_space) { - partial_block->Flush(context, partial_block_type); + partial_block->Flush(GetQueryContext(), partial_block_type); return; } partially_filled_blocks.insert(make_pair(partial_block->AvailableSpace(), std::move(partial_block))); if (auto pruned_block = PruneFreeList()) { - pruned_block->Flush(context, partial_block_type); + pruned_block->Flush(GetQueryContext(), partial_block_type); } } @@ -416,8 +416,8 @@ BlockManager &PartialBlockManager::GetBlockManager() const { return block_manager; } -optional_ptr PartialBlockManager::GetClientContext() const { - return context; +QueryContext PartialBlockManager::GetQueryContext() const { + return QueryContext(context); } } // namespace duckdb diff --git a/src/duckdb/src/storage/serialization/serialize_nodes.cpp b/src/duckdb/src/storage/serialization/serialize_nodes.cpp index 49e030697..472f02bf5 100644 --- a/src/duckdb/src/storage/serialization/serialize_nodes.cpp +++ b/src/duckdb/src/storage/serialization/serialize_nodes.cpp @@ -250,6 +250,9 @@ ColumnDefinition ColumnDefinition::Deserialize(Deserializer &deserializer) { deserializer.ReadProperty(104, "compression_type", result.compression_type); deserializer.ReadPropertyWithExplicitDefault(105, "comment", result.comment, Value()); deserializer.ReadPropertyWithExplicitDefault>(106, "tags", result.tags, InsertionOrderPreservingMap()); + if (result.Generated() && !result.HasGeneratedExpression()) { + throw SerializationException("Failed to deserialize: generated column has no expression"); + } return result; } @@ -433,6 +436,7 @@ Literal Literal::Deserialize(Deserializer &deserializer) { deserializer.ReadProperty(100, "kind", result.kind); deserializer.ReadPropertyWithDefault(101, "text", result.text); result.Verify(); + deserializer.CheckAllowed(result.kind); return result; } diff --git a/src/duckdb/src/storage/serialization/serialize_types.cpp b/src/duckdb/src/storage/serialization/serialize_types.cpp index 4188a5e69..274829ec1 100644 --- a/src/duckdb/src/storage/serialization/serialize_types.cpp +++ b/src/duckdb/src/storage/serialization/serialize_types.cpp @@ -101,14 +101,14 @@ unique_ptr ArrayTypeInfo::Deserialize(Deserializer &deserialize void DecimalTypeInfo::Serialize(Serializer &serializer) const { LogicalTypeInfo::Serialize(serializer); - serializer.WritePropertyWithDefault(200, "width", width); - serializer.WritePropertyWithDefault(201, "scale", scale); + serializer.WritePropertyWithDefault(200, "width", width); + serializer.WritePropertyWithDefault(201, "scale", scale); } unique_ptr DecimalTypeInfo::Deserialize(Deserializer &deserializer) { auto result = duckdb::unique_ptr(new DecimalTypeInfo()); - deserializer.ReadPropertyWithDefault(200, "width", result->width); - deserializer.ReadPropertyWithDefault(201, "scale", result->scale); + deserializer.ReadPropertyWithDefault(200, "width", result->width); + deserializer.ReadPropertyWithDefault(201, "scale", result->scale); return std::move(result); } diff --git a/src/duckdb/src/storage/single_file_block_manager.cpp b/src/duckdb/src/storage/single_file_block_manager.cpp index 002ff6c8a..03eacaac3 100644 --- a/src/duckdb/src/storage/single_file_block_manager.cpp +++ b/src/duckdb/src/storage/single_file_block_manager.cpp @@ -836,7 +836,10 @@ void SingleFileBlockManager::Initialize(const DatabaseHeader &header, const opti free_list_id = header.free_list; meta_block = header.meta_block; iteration_count = header.iteration; - max_block = NumericCast(header.block_count); + if (header.block_count > static_cast(NumericLimits::Maximum())) { + throw DataCorruptionException("Corrupt database file: invalid block count %llu", header.block_count); + } + max_block = UnsafeNumericCast(header.block_count); if (options.storage_version != StorageVersion::INVALID) { // storage version specified explicitly - use requested storage version auto requested_compat_version = options.storage_version; diff --git a/src/duckdb/src/storage/standard_buffer_manager.cpp b/src/duckdb/src/storage/standard_buffer_manager.cpp index 02d8ebed9..5af88943e 100644 --- a/src/duckdb/src/storage/standard_buffer_manager.cpp +++ b/src/duckdb/src/storage/standard_buffer_manager.cpp @@ -4,7 +4,6 @@ #include "duckdb/common/enums/memory_tag.hpp" #include "duckdb/common/enums/storage_block_prefetch.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/set.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/query_profiler.hpp" @@ -81,6 +80,11 @@ StandardBufferManager::StandardBufferManager(DatabaseInstance &db, string tmp) temp_block_manager = make_uniq(*this, DEFAULT_BLOCK_ALLOC_SIZE, DEFAULT_BLOCK_HEADER_STORAGE_SIZE); temporary_directory.path = std::move(tmp); + // 'max_temp_directory_size' set before the database was created is only stored in the config + auto &config = DBConfig::GetConfig(db); + if (config.options.maximum_swap_space != DConstants::INVALID_INDEX) { + temporary_directory.maximum_swap_space = config.options.maximum_swap_space; + } for (idx_t i = 0; i < MEMORY_TAG_COUNT; i++) { evicted_data_per_tag[i] = 0; } @@ -441,9 +445,13 @@ void StandardBufferManager::AddToEvictionQueue(shared_ptr &handle) void StandardBufferManager::VerifyZeroReaders(BlockLock &lock, shared_ptr &handle) { #ifdef DUCKDB_DEBUG_DESTROY_BLOCKS + auto &buffer = handle->GetMemory().GetBuffer(lock); + // A failed persistence write can leave an empty, moved-from buffer. + if (buffer->Size() == 0) { + return; + } unique_ptr replacement_buffer; auto &block_allocator = BlockAllocator::Get(db); - auto &buffer = handle->GetMemory().GetBuffer(lock); auto block_header_size = buffer->GetHeaderSize(); auto alloc_size = buffer->AllocSize() - block_header_size; if (handle->GetMemory().GetBufferType() == FileBufferType::BLOCK) { @@ -549,8 +557,9 @@ void StandardBufferManager::WriteTemporaryBuffer(QueryContext context, MemoryTag if (buffer.AllocSize() == GetBlockAllocSize()) { idx_t eviction_size = temporary_directory.handle->GetTempFile().WriteTemporaryBuffer(context, block_id, buffer); evicted_data_per_tag[uint8_t(tag)] += eviction_size; - if (context.GetClientContext()) { - QueryProfiler::Get(*context.GetClientContext()).TrackBytesSpilled(eviction_size); + auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + if (profiler) { + profiler->TrackBytesSpilled(eviction_size); } return; } @@ -598,8 +607,9 @@ void StandardBufferManager::WriteTemporaryBuffer(QueryContext context, MemoryTag throw; } evicted_data_per_tag[uint8_t(tag)] += buffer.AllocSize(); - if (context.GetClientContext()) { - QueryProfiler::Get(*context.GetClientContext()).TrackBytesSpilled(buffer.AllocSize() + header_size); + auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + if (profiler) { + profiler->TrackBytesSpilled(buffer.AllocSize() + header_size); } } @@ -912,6 +922,10 @@ BufferAllocator &BufferAllocator::Get(ClientContext &context) { return manager.GetBufferAllocator(); } +BufferAllocator &BufferAllocator::Get(Context &context) { + return Get(context.GetDatabase()); +} + BufferAllocator &BufferAllocator::Get(DatabaseInstance &db) { return StandardBufferManager::GetBufferManager(db).GetBufferAllocator(); } diff --git a/src/duckdb/src/storage/statistics/base_statistics.cpp b/src/duckdb/src/storage/statistics/base_statistics.cpp index 75be432c4..b5365a6bb 100644 --- a/src/duckdb/src/storage/statistics/base_statistics.cpp +++ b/src/duckdb/src/storage/statistics/base_statistics.cpp @@ -187,6 +187,9 @@ void BaseStatistics::ResetAdditiveStatistics() { stats_union.string_data.has_total_string_length = false; break; case StatisticsType::LIST_STATS: + ListStats::ResetTotalListLength(*this); + child_stats[0].ResetAdditiveStatistics(); + break; case StatisticsType::ARRAY_STATS: child_stats[0].ResetAdditiveStatistics(); break; @@ -585,6 +588,7 @@ BaseStatistics BaseStatistics::FromConstantType(const Value &input) { auto &child_stats = ListStats::GetChildStats(result); if (!input.IsNull()) { auto &list_children = ListValue::GetChildren(input); + ListStats::SetLengthBounds(result, list_children.size(), list_children.size()); for (auto &child_element : list_children) { child_stats.Merge(FromConstant(child_element)); } diff --git a/src/duckdb/src/storage/statistics/list_stats.cpp b/src/duckdb/src/storage/statistics/list_stats.cpp index 4fcde047d..b8ee6ecb5 100644 --- a/src/duckdb/src/storage/statistics/list_stats.cpp +++ b/src/duckdb/src/storage/statistics/list_stats.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/operator/add.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" @@ -6,9 +7,26 @@ #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" +#include "duckdb/storage/storage_info.hpp" namespace duckdb { +bool ListStatsData::HasMinListLength() const { + return has_min_list_length && min_list_length != NumericLimits::Maximum(); +} + +optional_idx ListStatsData::MinLength() const { + return HasMinListLength() ? optional_idx(min_list_length) : optional_idx(); +} + +optional_idx ListStatsData::MaxLength() const { + return has_max_list_length ? optional_idx(max_list_length) : optional_idx(); +} + +optional_idx ListStatsData::TotalLength() const { + return has_total_list_length ? optional_idx(total_list_length) : optional_idx(); +} + void ListStats::Construct(BaseStatistics &stats) { stats.child_stats = unsafe_unique_array(new BaseStatistics[1]); BaseStatistics::Construct(stats.child_stats[0], ListType::GetChildType(stats.GetType())); @@ -18,6 +36,13 @@ BaseStatistics ListStats::CreateUnknown(LogicalType type) { auto &child_type = ListType::GetChildType(type); BaseStatistics result(std::move(type)); result.InitializeUnknown(); + auto &list_data = GetDataUnsafe(result); + list_data.has_min_list_length = false; + list_data.has_max_list_length = false; + list_data.has_total_list_length = false; + list_data.min_list_length = 0; + list_data.max_list_length = 0; + list_data.total_list_length = 0; result.child_stats[0].Copy(BaseStatistics::CreateUnknown(child_type)); return result; } @@ -26,6 +51,7 @@ BaseStatistics ListStats::CreateEmpty(LogicalType type) { auto &child_type = ListType::GetChildType(type); BaseStatistics result(std::move(type)); result.InitializeEmpty(); + ResetLengthData(result); result.child_stats[0].Copy(BaseStatistics::CreateEmpty(child_type)); return result; } @@ -33,9 +59,79 @@ BaseStatistics ListStats::CreateEmpty(LogicalType type) { void ListStats::Copy(BaseStatistics &stats, const BaseStatistics &other) { D_ASSERT(stats.child_stats); D_ASSERT(other.child_stats); + GetDataUnsafe(stats) = GetDataUnsafe(other); stats.child_stats[0].Copy(other.child_stats[0]); } +ListStatsData &ListStats::GetDataUnsafe(BaseStatistics &stats) { + D_ASSERT(stats.GetStatsType() == StatisticsType::LIST_STATS); + return stats.stats_union.list_data; +} + +const ListStatsData &ListStats::GetDataUnsafe(const BaseStatistics &stats) { + D_ASSERT(stats.GetStatsType() == StatisticsType::LIST_STATS); + return stats.stats_union.list_data; +} + +optional_idx ListStats::MinListLength(const BaseStatistics &stats) { + auto &data = GetDataUnsafe(stats); + return data.HasMinListLength() ? optional_idx(data.min_list_length) : optional_idx(); +} + +optional_idx ListStats::MaxListLength(const BaseStatistics &stats) { + auto &data = GetDataUnsafe(stats); + return data.has_max_list_length ? optional_idx(data.max_list_length) : optional_idx(); +} + +optional_idx ListStats::TotalListLength(const BaseStatistics &stats) { + auto &data = GetDataUnsafe(stats); + return data.has_total_list_length ? optional_idx(data.total_list_length) : optional_idx(); +} + +void ListStats::ResetLengthData(BaseStatistics &stats) { + auto &data = GetDataUnsafe(stats); + data.has_min_list_length = true; + data.has_max_list_length = true; + data.has_total_list_length = true; + data.min_list_length = NumericLimits::Maximum(); + data.max_list_length = 0; + data.total_list_length = 0; +} + +void ListStats::SetLengthBounds(BaseStatistics &stats, optional_idx min_length, optional_idx max_length) { + auto &data = GetDataUnsafe(stats); + data.has_min_list_length = min_length.IsValid(); + data.min_list_length = min_length.IsValid() ? min_length.GetIndex() : 0; + data.has_max_list_length = max_length.IsValid(); + data.max_list_length = max_length.IsValid() ? max_length.GetIndex() : 0; + data.has_total_list_length = false; + data.total_list_length = 0; +} + +void ListStats::MergeInLengths(BaseStatistics &stats, idx_t min_length, idx_t max_length, idx_t total_length) { + auto &data = GetDataUnsafe(stats); + data.min_list_length = MinValue(data.min_list_length, min_length); + data.max_list_length = MaxValue(data.max_list_length, max_length); + if (!TryAddOperator::Operation(data.total_list_length, total_length, + data.total_list_length)) { + // the sum of the lengths overflows - the total is no longer known + data.has_total_list_length = false; + data.total_list_length = 0; + } +} + +ListStatsData ListStats::GetLengthData(const BaseStatistics &stats) { + return GetDataUnsafe(stats); +} + +void ListStats::SetLengthData(BaseStatistics &stats, const ListStatsData &data) { + GetDataUnsafe(stats) = data; +} + +void ListStats::ResetTotalListLength(BaseStatistics &stats) { + GetDataUnsafe(stats).has_total_list_length = false; +} + const BaseStatistics &ListStats::GetChildStats(const BaseStatistics &stats) { if (stats.GetStatsType() != StatisticsType::LIST_STATS) { throw InternalException("ListStats::GetChildStats called on stats that is not a list"); @@ -64,6 +160,25 @@ void ListStats::Merge(BaseStatistics &stats, const BaseStatistics &other, StatsM return; } + auto &list_data = GetDataUnsafe(stats); + auto &other_data = GetDataUnsafe(other); + list_data.has_min_list_length = list_data.has_min_list_length && other_data.has_min_list_length; + list_data.min_list_length = MinValue(list_data.min_list_length, other_data.min_list_length); + list_data.has_max_list_length = list_data.has_max_list_length && other_data.has_max_list_length; + list_data.max_list_length = MaxValue(list_data.max_list_length, other_data.max_list_length); + if (merge_type == StatsMergeType::EXPAND_BOUNDS) { + // the other side may overlap with our data, so the total cannot be summed + list_data.has_total_list_length = false; + } else { + list_data.has_total_list_length = list_data.has_total_list_length && other_data.has_total_list_length; + if (!TryAddOperator::Operation( + list_data.total_list_length, other_data.total_list_length, list_data.total_list_length)) { + // the sum of the totals overflows - the total is no longer known + list_data.has_total_list_length = false; + list_data.total_list_length = 0; + } + } + auto &child_stats = ListStats::GetChildStats(stats); auto &other_child_stats = ListStats::GetChildStats(other); child_stats.Merge(other_child_stats, merge_type); @@ -72,6 +187,11 @@ void ListStats::Merge(BaseStatistics &stats, const BaseStatistics &other, StatsM void ListStats::Serialize(const BaseStatistics &stats, Serializer &serializer) { auto &child_stats = ListStats::GetChildStats(stats); serializer.WriteProperty(200, "child_stats", child_stats); + if (serializer.ShouldSerialize(StorageVersion::V2_1_0)) { + serializer.WritePropertyWithDefault(201, "min_list_length", MinListLength(stats)); + serializer.WritePropertyWithDefault(202, "max_list_length", MaxListLength(stats)); + serializer.WritePropertyWithDefault(203, "total_list_length", TotalListLength(stats)); + } } void ListStats::Deserialize(Deserializer &deserializer, BaseStatistics &base) { @@ -83,11 +203,32 @@ void ListStats::Deserialize(Deserializer &deserializer, BaseStatistics &base) { deserializer.Set(child_type); base.child_stats[0].Copy(deserializer.ReadProperty(200, "child_stats")); deserializer.Unset(); + + auto &list_data = GetDataUnsafe(base); + auto min_list_length = deserializer.ReadPropertyWithDefault(201, "min_list_length"); + auto max_list_length = deserializer.ReadPropertyWithDefault(202, "max_list_length"); + auto total_list_length = deserializer.ReadPropertyWithDefault(203, "total_list_length"); + list_data.has_min_list_length = min_list_length.IsValid(); + list_data.min_list_length = min_list_length.IsValid() ? min_list_length.GetIndex() : 0; + list_data.has_max_list_length = max_list_length.IsValid(); + list_data.max_list_length = max_list_length.IsValid() ? max_list_length.GetIndex() : 0; + list_data.has_total_list_length = total_list_length.IsValid(); + list_data.total_list_length = total_list_length.IsValid() ? total_list_length.GetIndex() : 0; } child_list_t ListStats::ToStruct(const BaseStatistics &stats) { auto &child_stats = ListStats::GetChildStats(stats); child_list_t result; + auto &list_data = GetDataUnsafe(stats); + if (list_data.HasMinListLength()) { + result.emplace_back("min_list_length", Value::UBIGINT(list_data.min_list_length)); + } + if (list_data.has_max_list_length) { + result.emplace_back("max_list_length", Value::UBIGINT(list_data.max_list_length)); + } + if (list_data.has_total_list_length) { + result.emplace_back("total_list_length", Value::UBIGINT(list_data.total_list_length)); + } result.emplace_back("child_stats", child_stats.ToStruct()); return result; } @@ -96,13 +237,27 @@ void ListStats::Verify(const BaseStatistics &stats, const Vector &vector, const auto &child_stats = ListStats::GetChildStats(stats); const auto &child_entry = ListVector::GetChild(vector); auto entries = vector.Values(); + auto &list_data = GetDataUnsafe(stats); idx_t total_list_count = 0; for (idx_t i = 0; i < count; i++) { auto idx = sel.get_index(i); auto entry = entries[idx]; if (entry.IsValid()) { - total_list_count += entry.GetValue().length; + auto length = entry.GetValue().length; + // LCOV_EXCL_START + if (list_data.has_max_list_length && length > list_data.max_list_length) { + throw InternalException("Statistics mismatch: list length exceeds maximum list length.\nStatistics: " + "%s\nVector: %s", + stats.ToString(), vector.ToString()); + } + if (list_data.HasMinListLength() && length < list_data.min_list_length) { + throw InternalException("Statistics mismatch: list length is below minimum list length.\nStatistics: " + "%s\nVector: %s", + stats.ToString(), vector.ToString()); + } + // LCOV_EXCL_STOP + total_list_count += length; } } SelectionVector list_sel(total_list_count); diff --git a/src/duckdb/src/storage/statistics/string_stats.cpp b/src/duckdb/src/storage/statistics/string_stats.cpp index 358bb6304..118d36e81 100644 --- a/src/duckdb/src/storage/statistics/string_stats.cpp +++ b/src/duckdb/src/storage/statistics/string_stats.cpp @@ -1,6 +1,7 @@ #include "duckdb/storage/statistics/string_stats.hpp" #include "duckdb/common/types/value.hpp" +#include "duckdb/common/operator/add.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/typedefs.hpp" @@ -661,8 +662,12 @@ void StringStats::Merge(BaseStatistics &stats, const StringStatsData &other_data string_data.has_total_string_length = false; } else { string_data.has_total_string_length = string_data.has_total_string_length && other_data.has_total_string_length; - if (string_data.has_total_string_length) { - string_data.total_string_length += other_data.total_string_length; + if (string_data.has_total_string_length && + !TryAddOperator::Operation( + string_data.total_string_length, other_data.total_string_length, string_data.total_string_length)) { + // the sum of the totals overflows - the total is no longer known + string_data.has_total_string_length = false; + string_data.total_string_length = 0; } } } diff --git a/src/duckdb/src/storage/statistics/variant_stats.cpp b/src/duckdb/src/storage/statistics/variant_stats.cpp index 5440fb2d3..166a389fa 100644 --- a/src/duckdb/src/storage/statistics/variant_stats.cpp +++ b/src/duckdb/src/storage/statistics/variant_stats.cpp @@ -528,6 +528,7 @@ static unique_ptr TryBuildShreddingStats(const LogicalType &type // a variant stores both LISTs and fixed-size ARRAYs as a (variable length) array auto typed_value = BaseStatistics::CreateEmpty(LogicalType::LIST(child_result->GetType())); ListStats::SetChildStats(typed_value, std::move(child_result)); + ListStats::SetLengthBounds(typed_value, optional_idx(), optional_idx()); typed_value.CopyValidity(input); return WrapTypedValue(typed_value, nullptr).ToUnique(); } @@ -692,6 +693,7 @@ bool VariantStats::MergeShredding(const BaseStatistics &stats, const BaseStatist auto new_typed_value = BaseStatistics::CreateEmpty(LogicalType::LIST(new_child_stats.type)); new_typed_value.CombineValidity(stats_typed_value, other_typed_value); ListStats::SetChildStats(new_typed_value, new_child_stats.ToUnique()); + ListStats::SetLengthBounds(new_typed_value, optional_idx(), optional_idx()); new_stats = WrapTypedValue(new_typed_value, new_untyped_value_stats); return true; } else { diff --git a/src/duckdb/src/storage/storage_info.cpp b/src/duckdb/src/storage/storage_info.cpp index fadd6708c..7a21bf4d9 100644 --- a/src/duckdb/src/storage/storage_info.cpp +++ b/src/duckdb/src/storage/storage_info.cpp @@ -91,6 +91,7 @@ static const StorageVersionInfo storage_version_info[] = { {"v1.5.5", StorageVersion::V1_5_5}, {"v1.5.6", StorageVersion::V1_5_6}, {"v2.0.0", StorageVersion::V2_0_0}, + {"v2.0.1", StorageVersion::V2_0_1}, {"v2.1.0", StorageVersion::V2_1_0}, {"latest", StorageVersion::V2_1_0}, {nullptr, StorageVersion::INVALID} @@ -132,6 +133,7 @@ static const SerializationVersionInfo serialization_version_info[] = { {"v1.5.5", SerializationVersionDeprecated::V1_5_5}, {"v1.5.6", SerializationVersionDeprecated::V1_5_6}, {"v2.0.0", SerializationVersionDeprecated::V2_0_0}, + {"v2.0.1", SerializationVersionDeprecated::V2_0_1}, {"v2.1.0", SerializationVersionDeprecated::V2_1_0}, {"latest", SerializationVersionDeprecated::V2_1_0}, {nullptr, SerializationVersionDeprecated::INVALID} diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index 55a66aa9c..956a675dd 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -271,10 +271,6 @@ bool StorageManager::WALStartCheckpoint(MetaBlockPointer meta_block, CheckpointO return false; } // start the checkpoint process around the WAL - if (GetWALSize() == 0) { - // no WAL - we don't need to do anything here - return false; - } // verify the main WAL is the active WAL currently if (wal->GetPath() != wal_path) { throw InternalException("Current WAL path \"%s\" does not match base WAL path \"%s\" in WALStartCheckpoint", @@ -564,9 +560,8 @@ void SingleFileStorageManager::LoadDatabase(QueryContext context) { unique_ptr timer = nullptr; // Start timing the storage load step. - auto client_context = context.GetClientContext(); - if (client_context) { - auto profiler = client_context->client_data->profiler; + auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + if (profiler) { timer = make_uniq(profiler->StartTimer()); } @@ -580,8 +575,7 @@ void SingleFileStorageManager::LoadDatabase(QueryContext context) { } // Start timing the WAL replay step. - if (client_context) { - auto profiler = client_context->client_data->profiler; + if (profiler) { timer = make_uniq(profiler->StartTimer()); } @@ -760,15 +754,17 @@ bool SingleFileStorageManager::IsCheckpointClean(MetaBlockPointer checkpoint_id) return block_manager->IsRootBlock(checkpoint_id); } -unique_ptr SingleFileStorageManager::CreateCheckpointWriter(QueryContext context, - CheckpointOptions options) { +unique_ptr +SingleFileStorageManager::CreateCheckpointWriter(QueryContext context, CheckpointOptions options, + optional_ptr client_context) { if (InMemory()) { - return make_uniq(context, db, *block_manager, *this, options); + return make_uniq(context, db, *block_manager, *this, options, client_context); } - return make_uniq(context, db, *block_manager, options); + return make_uniq(context, db, *block_manager, options, client_context); } -void SingleFileStorageManager::CreateCheckpoint(QueryContext context, CheckpointOptions options) { +void SingleFileStorageManager::CreateCheckpoint(QueryContext context, CheckpointOptions options, + optional_ptr client_context) { if (read_only || !load_complete) { return; } @@ -796,14 +792,14 @@ void SingleFileStorageManager::CreateCheckpoint(QueryContext context, Checkpoint if (wal_size > 0 || config.options.force_checkpoint || options.action == CheckpointAction::ALWAYS_CHECKPOINT) { try { // Start timing the checkpoint. - auto client_context = context.GetClientContext(); + auto profiler = Context::TryGetQueryProfiler(context.GetContext()); MetricsTimer timer; - if (client_context) { - timer = client_context->client_data->profiler->StartTimer(); + if (profiler) { + timer = profiler->StartTimer(); } // Write the checkpoint. - auto checkpointer = CreateCheckpointWriter(context, options); + auto checkpointer = CreateCheckpointWriter(context, options, client_context); checkpointer->CreateCheckpoint(); timer.EndTimer(); diff --git a/src/duckdb/src/storage/table/array_column_data.cpp b/src/duckdb/src/storage/table/array_column_data.cpp index 94b961700..e104b0213 100644 --- a/src/duckdb/src/storage/table/array_column_data.cpp +++ b/src/duckdb/src/storage/table/array_column_data.cpp @@ -27,16 +27,18 @@ void ArrayColumnData::SetDataType(ColumnDataType data_type) { validity->SetDataType(data_type); } -FilterPropagateResult ArrayColumnData::CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) { - return CheckValidityZonemap(state, filter, checked_segment, *validity); +FilterPropagateResult ArrayColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { + return CheckValidityZonemap(state, filter, checked_end, *validity); } -void ArrayColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { - ColumnData::InitializePrefetch(prefetch_state, scan_state, rows); - validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], rows); +void ArrayColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { + ColumnData::InitializePrefetch(prefetch_state, scan_state, start_row, end_row); + validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], start_row, end_row); auto array_size = ArrayType::GetSize(type); - child_column->InitializePrefetch(prefetch_state, scan_state.child_states[1], rows * array_size); + child_column->InitializePrefetch(prefetch_state, scan_state.child_states[1], start_row * array_size, + end_row * array_size); } void ArrayColumnData::InitializeScan(ColumnScanState &state) { @@ -181,10 +183,12 @@ void ArrayColumnData::Skip(ColumnScanState &state, idx_t count) { void ArrayColumnData::InitializeAppend(ColumnAppendState &state) { ColumnAppendState validity_append; + validity_append.transient = state.transient; validity->InitializeAppend(validity_append); state.child_appends.push_back(std::move(validity_append)); ColumnAppendState child_append; + child_append.transient = state.transient; child_column->InitializeAppend(child_append); state.child_appends.push_back(std::move(child_append)); } @@ -224,10 +228,6 @@ void ArrayColumnData::RevertAppend(row_t new_count) { this->count = UnsafeNumericCast(new_count); } -idx_t ArrayColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - throw NotImplementedException("Array Fetch"); -} - void ArrayColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t row_group_start) { throw NotImplementedException("Array Update is not supported."); diff --git a/src/duckdb/src/storage/table/chunk_info.cpp b/src/duckdb/src/storage/table/chunk_info.cpp index d9e319395..f0a6c17c2 100644 --- a/src/duckdb/src/storage/table/chunk_info.cpp +++ b/src/duckdb/src/storage/table/chunk_info.cpp @@ -631,7 +631,7 @@ void ChunkVectorInfo::VerifyCachedCompressionState() const { #endif } -VersionCompressionResult ChunkVectorInfo::CompressVersionIds(VisibilityBound lowest_visibility_bound) { +VersionCompressionResult ChunkVectorInfo::CompressVersionIds(VisibilityBound lowest_visibility_bound, idx_t row_count) { if (!recheck_compression) { // no ids were modified since this vector last settled - only a further modification // (which re-arms the check) can make it compressible, so skip re-scanning the ids @@ -741,7 +741,7 @@ VersionCompressionResult ChunkVectorInfo::CompressVersionIds(VisibilityBound low { auto segment = allocator.GetHandle(GetInsertedPointer()); auto inserted = segment.GetPtr(); - for (idx_t i = 0; i < STANDARD_VECTOR_SIZE; i++) { + for (idx_t i = 0; i < row_count; i++) { if (inserted[i] >= lowest_visibility_bound) { // the insert is not yet visible to all transactions can_compress = false; @@ -823,7 +823,7 @@ bool ChunkVectorInfo::Cleanup(VisibilityBound lowest_visibility_bound) const { return true; } -bool ChunkVectorInfo::HasDeletes(VisibilityBound visibility_bound) const { +bool ChunkVectorInfo::HasDeletes(VisibilityBound visibility_bound, idx_t row_count) const { if (HasConstantInsertionId() && !IsCommitted(ConstantInsertId())) { // the vector was inserted by a transaction that has not committed yet // the rows have to be masked as deleted when writing a checkpoint @@ -844,7 +844,7 @@ bool ChunkVectorInfo::HasDeletes(VisibilityBound visibility_bound) const { case DeleteIdState::ARRAY: { auto segment = allocator.GetHandle(GetDeletedPointer()); auto deleted = segment.GetPtr(); - for (idx_t i = 0; i < STANDARD_VECTOR_SIZE; i++) { + for (idx_t i = 0; i < row_count; i++) { if (deleted[i] < visibility_bound) { return true; } @@ -984,22 +984,23 @@ transaction_t ChunkVectorInfo::ConstantDeleteId() const { return constant_delete_id; } -void ChunkVectorInfo::Write(WriteStream &writer, VisibilityBound visibility_bound) const { +void ChunkVectorInfo::Write(WriteStream &writer, VisibilityBound visibility_bound, idx_t row_count) const { + D_ASSERT(row_count > 0 && row_count <= STANDARD_VECTOR_SIZE); SelectionVector sel(STANDARD_VECTOR_SIZE); transaction_t transaction_id = DConstants::INVALID_INDEX; - idx_t count = GetSelVector(TransactionData(transaction_id, visibility_bound), sel, STANDARD_VECTOR_SIZE); - if (count == STANDARD_VECTOR_SIZE) { + idx_t count = GetSelVector(TransactionData(transaction_id, visibility_bound), sel, row_count); + if (count == row_count) { // nothing is deleted: skip writing anything writer.Write(ChunkInfoType::EMPTY_INFO); return; } - if (count == 0) { + if (count == 0 && row_count == STANDARD_VECTOR_SIZE) { // everything is deleted: write a constant vector writer.Write(ChunkInfoType::CONSTANT_INFO); writer.Write(start); return; } - // write a boolean vector + // write a boolean vector - rows appended past row_count later must not be loaded as deleted writer.Write(ChunkInfoType::VECTOR_INFO); writer.Write(start); ValidityMask mask(STANDARD_VECTOR_SIZE); @@ -1007,6 +1008,9 @@ void ChunkVectorInfo::Write(WriteStream &writer, VisibilityBound visibility_boun for (idx_t i = 0; i < count; i++) { mask.SetInvalid(sel.get_index(i)); } + for (idx_t i = row_count; i < STANDARD_VECTOR_SIZE; i++) { + mask.SetInvalid(i); + } mask.Write(writer, STANDARD_VECTOR_SIZE); } diff --git a/src/duckdb/src/storage/table/column_data.cpp b/src/duckdb/src/storage/table/column_data.cpp index 0976ce251..64872a439 100644 --- a/src/duckdb/src/storage/table/column_data.cpp +++ b/src/duckdb/src/storage/table/column_data.cpp @@ -1,4 +1,5 @@ #include "duckdb/storage/table/column_data.hpp" +#include "duckdb/storage/table/list_column_data.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/common/exception/transaction_exception.hpp" @@ -49,14 +50,12 @@ bool ColumnData::IsDirectNullCheckFilter(const TableFilter &filter) { return op.GetChildren()[0]->GetExpressionClass() == ExpressionClass::BOUND_REF; } -FilterPropagateResult ColumnData::CheckValidityZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment, - ColumnData &validity_column) { - if (!IsDirectNullCheckFilter(filter) || state.child_states.empty()) { - checked_segment = nullptr; +FilterPropagateResult ColumnData::CheckValidityZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end, ColumnData &validity_column) { + if (!IsDirectNullCheckFilter(filter.filter) || state.child_states.empty()) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } - return validity_column.CheckZonemap(state.child_states[0], filter, checked_segment); + return validity_column.CheckZonemap(state.child_states[0], filter, checked_end); } ColumnData::ColumnData(BlockManager &block_manager, DataTableInfo &info, idx_t column_index, LogicalType type_p, @@ -95,6 +94,7 @@ bool ColumnData::HasUpdates() const { } bool ColumnData::HasChanges(idx_t start_row, idx_t end_row) const { + lock_guard update_guard(update_lock); if (!updates) { return false; } @@ -172,29 +172,19 @@ ScanVectorType ColumnData::GetVectorScanType(ColumnScanState &state, idx_t scan_ return ScanVectorType::SCAN_ENTIRE_VECTOR; } -void ColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t remaining) { - auto current_segment = scan_state.current; - if (!current_segment) { +void ColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { + if (!scan_state.current || start_row >= MinValue(end_row, count)) { + // columns without segments have no blocks to prefetch, and the estimated rows of a child can lie past its end return; } - if (!scan_state.initialized) { - // need to prefetch for the current segment if we have not yet initialized the scan for this segment - current_segment->GetNode().InitializePrefetch(prefetch_state, scan_state); - } - idx_t row_index = scan_state.offset_in_column; - while (remaining > 0) { - auto ¤t = current_segment->GetNode(); - idx_t scan_count = MinValue(remaining, current_segment->GetRowStart() + current.count - row_index); - remaining -= scan_count; - row_index += scan_count; - if (remaining > 0) { - auto next = data.GetNextSegment(*current_segment); - if (!next) { - break; - } - next->GetNode().InitializePrefetch(prefetch_state, scan_state); - current_segment = next; + for (auto segment = data.GetSegment(start_row); segment && segment->GetRowStart() < end_row; + segment = data.GetNextSegment(*segment)) { + if (scan_state.initialized && segment == scan_state.current) { + // the scan has initialized this segment and pinned its block + continue; } + segment->GetNode().InitializePrefetch(prefetch_state, scan_state); } } @@ -366,7 +356,7 @@ void ColumnData::FetchUpdateRow(TransactionData transaction, row_t row_id, Vecto } void ColumnData::UpdateInternal(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, - Vector &update_vector, row_t *row_ids, idx_t update_count, Vector &base_vector, + Vector &update_vector, row_t *row_ids, idx_t update_count, const Vector &base_vector, idx_t row_group_start) { lock_guard update_guard(update_lock); if (!updates) { @@ -476,9 +466,12 @@ void ColumnData::FinalizeAppendLocked(ColumnDataFinalizeAppendState &finalize_st FinalizeAppend(finalize_state, state); } -FilterPropagateResult ColumnData::CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) { - checked_segment = nullptr; +FilterPropagateResult ColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { + if (filter.IsAlwaysTrue()) { + // the filter does not need to be checked in this row group + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } if (state.segment_checked) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } @@ -486,23 +479,50 @@ FilterPropagateResult ColumnData::CheckZonemap(ColumnScanState &state, TableFilt return FilterPropagateResult::NO_PRUNING_POSSIBLE; } // for dynamic filters we never consider the segment being "checked" as it can always change - auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "ColumnData::CheckZonemap"); + auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter.filter, "ColumnData::CheckZonemap"); bool is_dynamic = ExpressionFilter::ContainsInternalFunction(*expr_filter.expr, DynamicFilterScalarFun::NAME); state.segment_checked = !is_dynamic; - checked_segment = IsDirectNullCheckFilter(filter) && !state.child_states.empty() && state.child_states[0].current - ? state.child_states[0].current - : state.current; - auto prune_result = CheckSegmentStatistics(state.context.GetClientContext(), *checked_segment, expr_filter); + auto &checked_segment = + IsDirectNullCheckFilter(filter.filter) && !state.child_states.empty() && state.child_states[0].current + ? *state.child_states[0].current + : *state.current; + // segment rows are relative to the row group + checked_end = checked_segment.GetRowStart() + checked_segment.GetNode().count; + return CheckSegmentStatistics(state.context.GetClientContext(), checked_segment, expr_filter); +} + +FilterPropagateResult ColumnData::CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, + optional_idx &checked_end) { + if (filter.IsAlwaysTrue() || !data.GetRootSegment() || IsDirectNullCheckFilter(filter.filter)) { + // the filter needs no check in this row group, the column has no segments, or the scan judges the null check + // on the validity child + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter.filter, "ColumnData::CheckZonemapAt"); + auto segment = data.GetSegment(row); + checked_end = segment->GetRowStart() + segment->GetNode().count; + return CheckSegmentStatistics(state.context.GetClientContext(), *segment, expr_filter); +} + +FilterPropagateResult ColumnData::CheckSegmentStatistics(optional_ptr context, + SegmentNode &segment, + ExpressionFilter &expr_filter) { + FilterPropagateResult prune_result; + { + lock_guard l(stats_lock); + auto &segment_stats = segment.GetNode().GetStatsMutable(); + prune_result = + context ? expr_filter.CheckStatistics(*context, segment_stats) : expr_filter.CheckStatistics(segment_stats); + } if (prune_result == FilterPropagateResult::NO_PRUNING_POSSIBLE) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } auto update_stats = GetUpdateStatistics(); if (!update_stats) { - // no updates - return original result + // without updates the result of the segment holds return prune_result; } // combine the update and original prune result - auto context = state.context.GetClientContext(); FilterPropagateResult update_result = context ? expr_filter.CheckStatistics(*context, *update_stats) : expr_filter.CheckStatistics(*update_stats); if (prune_result == update_result) { @@ -511,47 +531,6 @@ FilterPropagateResult ColumnData::CheckZonemap(ColumnScanState &state, TableFilt return FilterPropagateResult::NO_PRUNING_POSSIBLE; } -FilterPropagateResult ColumnData::CheckSegmentStatistics(optional_ptr context, - SegmentNode &segment, - ExpressionFilter &expr_filter) { - lock_guard l(stats_lock); - auto &segment_stats = segment.GetNode().GetStatsMutable(); - return context ? expr_filter.CheckStatistics(*context, segment_stats) : expr_filter.CheckStatistics(segment_stats); -} - -idx_t ColumnData::ZonemapScanEnd(optional_ptr context, idx_t start_row, idx_t end_row, - TableFilter &filter) { - if (!data.GetRootSegment() || IsDirectNullCheckFilter(filter)) { - // columns without segments of their own have no zonemaps, null checks are judged on the validity child - return end_row; - } - auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "ColumnData::ZonemapScanEnd"); - auto update_stats = GetUpdateStatistics(); - if (update_stats) { - auto update_result = - context ? expr_filter.CheckStatistics(*context, *update_stats) : expr_filter.CheckStatistics(*update_stats); - if (update_result != FilterPropagateResult::FILTER_ALWAYS_FALSE) { - // updated rows can pass the filter anywhere in the column - return end_row; - } - } - // a vector is only skipped when it lies entirely inside a rejected segment - idx_t scan_end = start_row; - for (auto segment = data.GetSegment(start_row); segment; segment = data.GetNextSegment(*segment)) { - const idx_t segment_start = segment->GetRowStart(); - if (segment_start >= end_row) { - break; - } - const idx_t segment_end = MinValue(segment_start + segment->GetNode().count, end_row); - const auto prune_result = CheckSegmentStatistics(context, *segment, expr_filter); - const bool straddles_vector = segment_end < end_row && segment_end % STANDARD_VECTOR_SIZE != 0; - if (prune_result != FilterPropagateResult::FILTER_ALWAYS_FALSE || straddles_vector) { - scan_end = AlignValue(segment_end); - } - } - return MinValue(scan_end, end_row); -} - FilterPropagateResult ColumnData::CheckZonemap(optional_ptr context, const StorageIndex &index, TableFilter &filter) { if (!stats) { @@ -759,18 +738,6 @@ void ColumnData::RevertAppend(row_t new_count_p) { this->count = new_count; } -idx_t ColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - if (UnsafeNumericCast(row_id) > count) { - throw InternalException("ColumnData::Fetch - row_id out of range"); - } - D_ASSERT(row_id >= 0); - // perform the fetch within the segment - state.offset_in_column = UnsafeNumericCast(row_id) / STANDARD_VECTOR_SIZE * STANDARD_VECTOR_SIZE; - state.current = data.GetSegment(state.offset_in_column); - state.internal_index = state.current->GetRowStart(); - return ScanVector(state, result, STANDARD_VECTOR_SIZE, ScanVectorType::SCAN_FLAT_VECTOR); -} - void ColumnData::FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t fetch_count, Vector &result, idx_t result_offset) { @@ -897,20 +864,22 @@ void ColumnData::FetchBaseRows(const QueryContext &context, const idx_t *offsets } } -idx_t ColumnData::FetchUpdateData(ColumnScanState &state, row_t *row_ids, Vector &base_vector, idx_t row_group_start) { - if (row_ids[0] < UnsafeNumericCast(row_group_start)) { - throw InternalException("ColumnData::FetchUpdateData out of range"); +void ColumnData::FetchBaseRows(const row_t *row_ids, idx_t count, Vector &result, idx_t row_group_start) { + D_ASSERT(count > 0 && count <= STANDARD_VECTOR_SIZE); + vector offsets(count); + for (idx_t i = 0; i < count; i++) { + if (row_ids[i] < UnsafeNumericCast(row_group_start)) { + throw InternalException("ColumnData::FetchBaseRows - row id out of range"); + } + offsets[i] = UnsafeNumericCast(row_ids[i]) - row_group_start; } - auto fetch_count = ColumnData::Fetch(state, row_ids[0] - UnsafeNumericCast(row_group_start), base_vector); - base_vector.Flatten(); - return fetch_count; + FetchBaseRows(QueryContext(), offsets.data(), *FlatVector::IncrementalSelectionVector(), count, result, 0); } void ColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t row_group_start) { - Vector base_vector(type); - ColumnScanState state(nullptr); - FetchUpdateData(state, row_ids, base_vector, row_group_start); + Vector base_vector(type, update_count); + FetchBaseRows(row_ids, update_count, base_vector, row_group_start); UpdateInternal(transaction, table_entry, column_index, update_vector, row_ids, update_count, base_vector, row_group_start); @@ -930,8 +899,10 @@ void ColumnData::AppendTransientSegment(SegmentLock &l, optional_ptr(config); + const bool first_transient_segment = + !prev_segment || prev_segment->GetSegmentType() == ColumnSegmentType::PERSISTENT; idx_t segment_size; - if (!prev_segment || prev_segment->GetSegmentType() == ColumnSegmentType::PERSISTENT) { + if (first_transient_segment) { // We start with the `initial_bytes` setting, but we ensure that we have enough space for at least one row. segment_size = MaxValue(GetTypeIdSize(type.InternalType()), initial_bytes); } else { @@ -960,7 +931,8 @@ void ColumnData::AppendTransientSegment(SegmentLock &l, optional_ptr new_segment; - if (transient && segment_size < block_size && initial_bytes < segment_size) { + // first segments stay tiny until a column grows and creates the shared block, so small tables never allocate one + if (transient && segment_size < block_size && (!first_transient_segment || transient->block)) { new_segment = transient->CreateTransientSegment(db, function, type, segment_size, block_manager); } else { new_segment = ColumnSegment::CreateTransientSegment(db, function, type, segment_size, block_manager); @@ -1107,7 +1079,9 @@ void PersistentColumnData::Serialize(Serializer &serializer) const { } // Serialize the extra data - serializer.WritePropertyWithDefault(99, "extra_data", extra_data); + if (!extra_data || extra_data->IsSupported(serializer)) { + serializer.WritePropertyWithDefault(99, "extra_data", extra_data); + } // TODO: Dont special-case this if (logical_type.id() == LogicalTypeId::VARIANT) { @@ -1185,6 +1159,14 @@ static PersistentColumnData GetPersistentColumnDataType(Deserializer &deserializ result.extra_data = std::move(extra_data); return result; } + case ExtraPersistentColumnDataType::LIST: { + if (column_type.InternalType() != PhysicalType::LIST) { + throw DataCorruptionException("LIST column data found for a column of type %s", column_type); + } + PersistentColumnData result(column_type); + result.extra_data = std::move(extra_data); + return result; + } default: throw InternalException(""); } @@ -1381,6 +1363,9 @@ void ExtraPersistentColumnData::Serialize(Serializer &serializer) const { const auto &geometry_data = Cast(); serializer.WritePropertyWithDefault(101, "storage_type", geometry_data.storage_type, GeometryStorageType::WKB); } break; + case ExtraPersistentColumnDataType::LIST: + Cast().SerializeFields(serializer); + break; default: throw InternalException("Unknown PersistentColumnData type"); } @@ -1399,6 +1384,8 @@ unique_ptr ExtraPersistentColumnData::Deserialize(Des 101, "storage_type", GeometryStorageType::WKB); return make_uniq(storage_type); } + case ExtraPersistentColumnDataType::LIST: + return ListPersistentColumnData::Deserialize(deserializer); default: throw InternalException("Unknown PersistentColumnData type"); } diff --git a/src/duckdb/src/storage/table/geo_column_data.cpp b/src/duckdb/src/storage/table/geo_column_data.cpp index dc4f5591a..05343d7b0 100644 --- a/src/duckdb/src/storage/table/geo_column_data.cpp +++ b/src/duckdb/src/storage/table/geo_column_data.cpp @@ -34,8 +34,9 @@ GeoColumnData::GeoColumnData(BlockManager &block_manager, DataTableInfo &info, i // Scan //---------------------------------------------------------------------------------------------------------------------- -void GeoColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { - return base_column->InitializePrefetch(prefetch_state, scan_state, rows); +void GeoColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { + return base_column->InitializePrefetch(prefetch_state, scan_state, start_row, end_row); } void GeoColumnData::InitializeChildScanStates(ColumnScanState &state) { @@ -123,25 +124,6 @@ void GeoColumnData::RevertAppend(row_t new_count) { // Fetch //---------------------------------------------------------------------------------------------------------------------- -idx_t GeoColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - // Not a shredded column, so just emit the binary format immediately - if (storage_type == GeometryStorageType::WKB) { - return base_column->Fetch(state, row_id, result); - } - - // Otherwise, we need to fetch and reassemble - auto &layout_type = base_column->GetType(); - - DataChunk chunk; - chunk.Initialize(Allocator::DefaultAllocator(), {layout_type}, 1); - - const auto fetch_count = base_column->Fetch(state, row_id, chunk.data[0]); - - Reassemble(chunk.data[0], result, fetch_count, storage_type, 0); - - return fetch_count; -} - void GeoColumnData::FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t fetch_count, Vector &result, idx_t result_offset) { diff --git a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp index 76185b9f5..21fd27e82 100644 --- a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp +++ b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp @@ -20,16 +20,17 @@ namespace duckdb { // In-Memory Checkpoint Writer //===--------------------------------------------------------------------===// InMemoryCheckpointer::InMemoryCheckpointer(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, - StorageManager &storage_manager, CheckpointOptions options_p) - : CheckpointWriter(db), context(context.GetClientContext()), - partial_block_manager(context, block_manager, PartialBlockType::IN_MEMORY_CHECKPOINT), + StorageManager &storage_manager, CheckpointOptions options_p, + optional_ptr client_context) + : CheckpointWriter(db, context, client_context), + partial_block_manager(GetContext(), block_manager, PartialBlockType::IN_MEMORY_CHECKPOINT), storage_manager(storage_manager), options(options_p) { } 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(context, db, transaction_manager); + ActiveCheckpointWrapper active_checkpoint(GetContext(), db, transaction_manager); { unique_lock commit_lock; if (!options.commit_lock) { @@ -118,7 +119,7 @@ optional_ptr InMemoryRowGroupWriter::GetMetadataManager() { } InMemoryTableDataWriter::InMemoryTableDataWriter(InMemoryCheckpointer &checkpoint_manager, TableCatalogEntry &table) - : TableDataWriter(table, checkpoint_manager.GetClientContext()), checkpoint_manager(checkpoint_manager) { + : TableDataWriter(table, checkpoint_manager.GetContext()), checkpoint_manager(checkpoint_manager) { } void InMemoryTableDataWriter::WriteUnchangedTable(MetaBlockPointer pointer, @@ -133,7 +134,7 @@ void InMemoryTableDataWriter::FinalizeTable(const TableStatistics &global_stats, // nop: no need to write anything } -unique_ptr InMemoryTableDataWriter::GetRowGroupWriter(RowGroup &row_group) { +unique_ptr InMemoryTableDataWriter::GetRowGroupWriter() { return make_uniq(*this, table, checkpoint_manager.GetPartialBlockManager(), checkpoint_manager); } diff --git a/src/duckdb/src/storage/table/list_column_data.cpp b/src/duckdb/src/storage/table/list_column_data.cpp index d86ae7700..ffb60ebe4 100644 --- a/src/duckdb/src/storage/table/list_column_data.cpp +++ b/src/duckdb/src/storage/table/list_column_data.cpp @@ -3,6 +3,8 @@ #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/storage/table/list_column_data.hpp" #include "duckdb/storage/statistics/list_stats.hpp" +#include "duckdb/storage/storage_info.hpp" +#include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/storage/table/column_checkpoint_state.hpp" #include "duckdb/storage/table/append_state.hpp" @@ -50,14 +52,15 @@ void ListColumnData::SetDataType(ColumnDataType data_type) { validity->SetDataType(data_type); } -FilterPropagateResult ListColumnData::CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) { - return CheckValidityZonemap(state, filter, checked_segment, *validity); +FilterPropagateResult ListColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { + return CheckValidityZonemap(state, filter, checked_end, *validity); } -void ListColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { - ColumnData::InitializePrefetch(prefetch_state, scan_state, rows); - validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], rows); +void ListColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { + ColumnData::InitializePrefetch(prefetch_state, scan_state, start_row, end_row); + validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], start_row, end_row); // we can't know how many rows we need to prefetch for the child of this list without looking at the actual data // we make an estimation by looking at how many rows the child column has versus this column @@ -66,7 +69,15 @@ void ListColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnSca if (child_column->count > this->count && this->count > 0) { rows_per_list = child_column->count / this->count; } - child_column->InitializePrefetch(prefetch_state, scan_state.child_states[1], rows * rows_per_list); + // the child rows of the range are estimated from the child row the list scan is at, which last_offset holds + D_ASSERT(start_row >= scan_state.offset_in_column); + const idx_t child_start = scan_state.last_offset + (start_row - scan_state.offset_in_column) * rows_per_list; + if (child_start >= child_column->GetMaxEntry()) { + // no child rows remain + return; + } + const idx_t child_end = scan_state.last_offset + (end_row - scan_state.offset_in_column) * rows_per_list; + child_column->InitializePrefetch(prefetch_state, scan_state.child_states[1], child_start, child_end); } void ListColumnData::InitializeScan(ColumnScanState &state) { @@ -110,6 +121,9 @@ void ListColumnData::InitializeScanWithOffset(ColumnScanState &state, idx_t row_ auto child_offset = FetchListOffset(row_idx - 1); if (child_offset < child_column->GetMaxEntry()) { child_column->InitializeScanWithOffset(state.child_states[1], child_offset); + } else { + // no child rows remain, start the child scan over so that it does not keep the position of an earlier scan + child_column->InitializeScan(state.child_states[1]); } state.last_offset = child_offset; } @@ -201,11 +215,13 @@ void ListColumnData::InitializeAppend(ColumnAppendState &state) { // initialize the validity append ColumnAppendState validity_append_state; + validity_append_state.transient = state.transient; validity->InitializeAppend(validity_append_state); state.child_appends.push_back(std::move(validity_append_state)); // initialize the child column append ColumnAppendState child_append_state; + child_append_state.transient = state.transient; child_column->InitializeAppend(child_append_state); state.child_appends.push_back(std::move(child_append_state)); } @@ -217,6 +233,9 @@ void ListColumnData::Append(ColumnAppendState &state, const Vector &vector, idx_ auto input_offsets = vector.Values(); auto start_offset = child_column->GetMaxEntry(); idx_t child_count = 0; + idx_t min_length = NumericLimits::Maximum(); + idx_t max_length = 0; + bool has_valid_list = false; ValidityMask append_mask(count); auto append_offsets = unique_ptr(new uint64_t[count]); @@ -229,12 +248,18 @@ void ListColumnData::Append(ColumnAppendState &state, const Vector &vector, idx_ continue; } auto &input_list = list_entry.GetValue(); + has_valid_list = true; + min_length = MinValue(min_length, input_list.length); + max_length = MaxValue(max_length, input_list.length); if (input_list.offset != child_count) { child_contiguous = false; } append_offsets[i] = start_offset + child_count + input_list.length; child_count += input_list.length; } + if (has_valid_list) { + ListStats::MergeInLengths(*state.append_stats, min_length, max_length, child_count); + } auto &list_child = ListVector::GetChild(vector); Vector child_vector(Vector::Ref(list_child)); if (!child_contiguous) { @@ -289,10 +314,6 @@ void ListColumnData::RevertAppend(row_t new_count) { child_column->RevertAppend(UnsafeNumericCast(list_offset)); } -idx_t ListColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - throw NotImplementedException("List Fetch"); -} - void ListColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t row_group_start) { throw NotImplementedException("List Update is not supported."); @@ -413,6 +434,8 @@ struct ListColumnCheckpointState : public ColumnCheckpointState { unique_ptr validity_state; unique_ptr child_state; + //! The list length statistics of the column + ListStatsData length_data = ListStatsData {false, false, false, 0, 0, 0}; public: shared_ptr CreateEmptyColumnData() override { @@ -435,11 +458,19 @@ struct ListColumnCheckpointState : public ColumnCheckpointState { auto stats = global_stats->Copy(); stats.Merge(*validity_state->GetStatistics()); ListStats::SetChildStats(stats, child_state->GetStatistics()); + ListStats::SetLengthData(stats, length_data); return stats.ToUnique(); } + void FlushSegmentInternal(unique_ptr segment, idx_t segment_size) override { + // the list length stats are stored with the column and not with the segments of the offsets + ListStats::SetLengthBounds(segment->GetStatsMutable(), optional_idx(), optional_idx()); + ColumnCheckpointState::FlushSegmentInternal(std::move(segment), segment_size); + } + PersistentColumnData ToPersistentData() override { auto data = ColumnCheckpointState::ToPersistentData(); + data.extra_data = make_uniq(length_data); data.child_columns.push_back(validity_state->ToPersistentData()); data.child_columns.push_back(child_state->ToPersistentData()); return data; @@ -461,6 +492,7 @@ unique_ptr ListColumnData::Checkpoint(const RowGroup &row auto &checkpoint_state = base_state->Cast(); checkpoint_state.validity_state = std::move(validity_state); checkpoint_state.child_state = std::move(child_state); + checkpoint_state.length_data = ListStats::GetLengthData(old_stats); return base_state; } @@ -472,8 +504,52 @@ bool ListColumnData::HasAnyChanges() const { return ColumnData::HasAnyChanges() || validity->HasAnyChanges() || child_column->HasAnyChanges(); } +optional_ptr ListColumnData::GetColumnStatistics() const { + if (stats) { + return stats->statistics; + } + if (!HasParent()) { + return nullptr; + } + // the statistics of the children of these columns are not tracked in their parent + auto parent_type = Parent().GetType().id(); + if (parent_type == LogicalTypeId::VARIANT || parent_type == LogicalTypeId::GEOMETRY) { + return nullptr; + } + return GetStatisticsRef(); +} + +bool ListPersistentColumnData::IsSupported(const Serializer &serializer) const { + return serializer.ShouldSerialize(StorageVersion::V2_1_0); +} + +void ListPersistentColumnData::SerializeFields(Serializer &serializer) const { + serializer.WritePropertyWithDefault(101, "min_list_length", length_data.MinLength()); + serializer.WritePropertyWithDefault(102, "max_list_length", length_data.MaxLength()); + serializer.WritePropertyWithDefault(103, "total_list_length", length_data.TotalLength()); +} + +unique_ptr ListPersistentColumnData::Deserialize(Deserializer &deserializer) { + auto min_length = deserializer.ReadPropertyWithDefault(101, "min_list_length"); + auto max_length = deserializer.ReadPropertyWithDefault(102, "max_list_length"); + auto total_length = deserializer.ReadPropertyWithDefault(103, "total_list_length"); + auto result = make_uniq(); + auto &data = result->length_data; + data.has_min_list_length = min_length.IsValid(); + data.min_list_length = min_length.IsValid() ? min_length.GetIndex() : 0; + data.has_max_list_length = max_length.IsValid(); + data.max_list_length = max_length.IsValid() ? max_length.GetIndex() : 0; + data.has_total_list_length = total_length.IsValid(); + data.total_list_length = total_length.IsValid() ? total_length.GetIndex() : 0; + return std::move(result); +} + PersistentColumnData ListColumnData::Serialize() { auto persistent_data = ColumnData::Serialize(); + auto column_stats = GetColumnStatistics(); + if (column_stats) { + persistent_data.extra_data = make_uniq(ListStats::GetLengthData(*column_stats)); + } persistent_data.child_columns.push_back(validity->Serialize()); persistent_data.child_columns.push_back(child_column->Serialize()); return persistent_data; @@ -481,6 +557,11 @@ PersistentColumnData ListColumnData::Serialize() { void ListColumnData::InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) { ColumnData::InitializeColumn(column_data, target_stats); + if (column_data.extra_data && column_data.extra_data->GetType() == ExtraPersistentColumnDataType::LIST) { + ListStats::SetLengthData(target_stats, column_data.extra_data->Cast().length_data); + } else { + ListStats::SetLengthBounds(target_stats, optional_idx(), optional_idx()); + } validity->InitializeColumn(column_data.child_columns[0], target_stats); auto &child_stats = ListStats::GetChildStats(target_stats); child_column->InitializeColumn(column_data.child_columns[1], child_stats); diff --git a/src/duckdb/src/storage/table/row_group.cpp b/src/duckdb/src/storage/table/row_group.cpp index dbace4b6f..7a0bac679 100644 --- a/src/duckdb/src/storage/table/row_group.cpp +++ b/src/duckdb/src/storage/table/row_group.cpp @@ -793,7 +793,7 @@ bool RowGroup::CheckZonemap(optional_ptr context, ScanFilterInfo return false; } if (ExpressionFilter::IsRootNonSelectivityOptionalFilter(filter)) { - // these are only for row group checking, set as always true so we don't check it + // these are only for pruning, set as always true so we don't execute them filters.SetFilterAlwaysTrue(i); } else if (prune_result == FilterPropagateResult::FILTER_ALWAYS_TRUE) { // filter is always true - no need to check it @@ -808,37 +808,26 @@ bool RowGroup::CheckZonemapSegments(CollectionScanState &state) { auto &filters = state.GetFilterInfo(); optional_idx target_vector_index_max; for (auto &entry : filters.GetFilterList()) { - if (entry.IsAlwaysTrue()) { - // filter is always true - avoid checking - continue; - } - auto column_idx = entry.scan_column_index; - auto base_column_idx = entry.table_column_index; - auto &filter = entry.filter; - auto &column_data = GetColumn(base_column_idx); - - optional_ptr> current_segment; - auto prune_result = column_data.CheckZonemap(state.column_scans[column_idx], filter, current_segment); + auto &column_data = GetColumn(entry.table_column_index); + optional_idx checked_end; + auto prune_result = column_data.CheckZonemap(state.column_scans[entry.scan_column_index], entry, checked_end); if (prune_result != FilterPropagateResult::FILTER_ALWAYS_FALSE && prune_result != FilterPropagateResult::FILTER_FALSE_OR_NULL) { continue; } - - // check zone map segment. - if (!current_segment) { - // no segment to skip + if (!checked_end.IsValid()) { + // no rows to skip continue; } - auto row_start = current_segment->GetRowStart(); - idx_t target_row = row_start + current_segment->GetNode().count; - if (target_row >= state.max_row) { - target_row = state.max_row; + // checked_end is relative to the row group, as state.vector_index is + idx_t target_vector_index; + if (checked_end.GetIndex() >= state.max_row_group_row) { + // the filter rejects the rest of the scan + target_vector_index = (state.max_row_group_row + STANDARD_VECTOR_SIZE - 1) / STANDARD_VECTOR_SIZE; + } else { + // the vector that holds checked_end can hold rows the filter accepts + target_vector_index = checked_end.GetIndex() / STANDARD_VECTOR_SIZE; } - D_ASSERT(target_row >= row_start); - D_ASSERT(target_row <= row_start + this->count); - // current_segment->GetRowStart() is already row-group-relative, and state.vector_index uses the same - // coordinate space. Subtracting row_start here incorrectly makes the target segment-local. - idx_t target_vector_index = target_row / STANDARD_VECTOR_SIZE; if (!target_vector_index_max.IsValid() || target_vector_index_max.GetIndex() < target_vector_index) { target_vector_index_max = target_vector_index; @@ -846,12 +835,8 @@ bool RowGroup::CheckZonemapSegments(CollectionScanState &state) { } if (target_vector_index_max.IsValid()) { if (state.vector_index == target_vector_index_max.GetIndex()) { - // we can't skip any full vectors because this segment contains less than a full vector - // for now we just bail-out - // FIXME: we could check if we can ALSO skip the next segments, in which case skipping a full vector - // might be possible - // we don't care that much though, since a single segment that fits less than a full vector is - // exceedingly rare + // the rejected rows end inside the current vector, which can hold rows of the next segment + // FIXME: the next segments could reject the rest of the vector, which would let the scan skip it return true; } while (state.vector_index < target_vector_index_max.GetIndex()) { @@ -863,20 +848,22 @@ bool RowGroup::CheckZonemapSegments(CollectionScanState &state) { } } -bool RowGroup::RegisterScanIO(CollectionScanState &state, idx_t row_count, PrefetchState &prefetch_state) const { +bool RowGroup::RegisterScanIO(CollectionScanState &state, idx_t start_row, idx_t end_row, + PrefetchState &prefetch_state) const { if (!GetBlockManager().Prefetch()) { return false; } const auto &column_ids = state.GetColumnIds(); for (idx_t i = 0; i < column_ids.size(); i++) { - GetColumn(column_ids[i]).InitializePrefetch(prefetch_state, state.column_scans[i], row_count); + GetColumn(column_ids[i]).InitializePrefetch(prefetch_state, state.column_scans[i], start_row, end_row); } return true; } void RowGroup::PrefetchScanIO(CollectionScanState &state, idx_t row_count) const { PrefetchState prefetch_state; - if (!RegisterScanIO(state, row_count, prefetch_state)) { + const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; + if (!RegisterScanIO(state, start_row, start_row + row_count, prefetch_state)) { return; } GetBlockManager().buffer_manager.Prefetch(state.context, prefetch_state.blocks); @@ -884,24 +871,53 @@ void RowGroup::PrefetchScanIO(CollectionScanState &state, idx_t row_count) const vector> RowGroup::CollectScanIOTasks(CollectionScanState &state, idx_t row_count) const { PrefetchState prefetch_state; - if (!RegisterScanIO(state, row_count, prefetch_state)) { + const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; + if (!RegisterScanIO(state, start_row, start_row + row_count, prefetch_state)) { return vector>(); } return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); } -idx_t RowGroup::PrefetchRowCount(CollectionScanState &state) { - const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; - idx_t end_row = state.max_row_group_row; - auto context = state.context.GetClientContext(); - for (auto &entry : state.GetFilterInfo().GetFilterList()) { - if (entry.IsAlwaysTrue() || entry.table_column_index.IsPushdownExtract()) { +vector> RowGroup::CollectAssignmentIOTasks(CollectionScanState &state) const { + if (!GetBlockManager().Prefetch()) { + return vector>(); + } + PrefetchState prefetch_state; + const auto &filters = state.GetFilterInfo().GetFilterList(); + const idx_t end_row = state.max_row_group_row; + idx_t row = state.vector_index * STANDARD_VECTOR_SIZE; + while (row < end_row) { + // the rows from row that a zonemap rejects, or up to which every zonemap keeps its result + idx_t rejected_end = row; + idx_t accepted_end = end_row; + for (auto &entry : filters) { + auto &column_data = GetColumn(entry.table_column_index); + optional_idx checked_end; + auto prune_result = + column_data.CheckZonemapAt(state.column_scans[entry.scan_column_index], entry, row, checked_end); + if (!checked_end.IsValid()) { + continue; + } + const idx_t result_end = MinValue(checked_end.GetIndex(), end_row); + if (prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE || + prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL) { + rejected_end = MaxValue(rejected_end, result_end); + } else { + accepted_end = MinValue(accepted_end, result_end); + } + } + if (rejected_end > row) { + row = rejected_end; continue; } - auto &column_data = GetColumn(entry.table_column_index); - end_row = MinValue(end_row, column_data.ZonemapScanEnd(context, start_row, end_row, entry.filter)); + // the vectors that hold the accepted rows are read, the following vector is checked again + D_ASSERT(accepted_end > row); + const idx_t run_start = row - row % STANDARD_VECTOR_SIZE; + const idx_t run_end = MinValue(AlignValue(accepted_end), end_row); + RegisterScanIO(state, run_start, run_end, prefetch_state); + row = run_end; } - return end_row > start_row ? end_row - start_row : 0; + return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); } bool RowGroup::PrepareScan(ScanOptions options, CollectionScanState &state) { @@ -1484,7 +1500,9 @@ shared_ptr RowGroup::CheckpointColumn(const RowGroup &row_group, idx // FIXME: we should get rid of the checkpoint state statistics - and instead use the stats in the ColumnData // directly auto stats = checkpoint_state->GetStatistics(); - result_col->MergeStatistics(*stats); + if (result_col.get() != &column) { + result_col->MergeStatistics(*stats); + } write_data.statistics.push_back(stats->Copy()); write_data.states.push_back(std::move(checkpoint_state)); @@ -1992,7 +2010,7 @@ void RowGroup::CompressVersionInfo(VisibilityBound lowest_visibility_bound) { if (!vinfo) { return; } - vinfo->CompressVersionIds(lowest_visibility_bound); + vinfo->CompressVersionIds(lowest_visibility_bound, count); } vector RowGroup::CheckpointDeletes(RowGroupWriter &writer) { @@ -2009,7 +2027,7 @@ vector RowGroup::CheckpointDeletes(RowGroupWriter &writer) { // no version information: write nothing return vector(); } - return vinfo->Checkpoint(writer); + return vinfo->Checkpoint(writer, count); } void RowGroup::Serialize(RowGroupPointer &pointer, Serializer &serializer, bool supports_per_column_writes) { diff --git a/src/duckdb/src/storage/table/row_group_collection.cpp b/src/duckdb/src/storage/table/row_group_collection.cpp index c1c611e1b..79836b5e4 100644 --- a/src/duckdb/src/storage/table/row_group_collection.cpp +++ b/src/duckdb/src/storage/table/row_group_collection.cpp @@ -385,7 +385,10 @@ optional_idx RowGroupCollection::NextParallelScan(ClientContext &context, Parall } auto ¤t_row_group = state.current_row_group->GetNode(); if (current_row_group.count == 0) { - break; + // InitializeAppend creates a row group before any rows are written. A later merge in the + // same transaction can append real groups after that empty one, so it is not the end of the table. + state.AssignRowGroup(state.GetNextRowGroup(*state.row_groups, *state.current_row_group).get()); + continue; } auto row_start = state.current_row_group->GetRowStart(); collection = state.collection; @@ -1201,7 +1204,7 @@ class CheckpointTask : public BaseCheckpointTask { void ExecuteTask() override { auto entry = checkpoint_state.GetSegment(index); auto &row_group = entry->GetNode(); - checkpoint_state.writers[index] = checkpoint_state.writer.GetRowGroupWriter(row_group); + checkpoint_state.writers[index] = checkpoint_state.writer.GetRowGroupWriter(); checkpoint_state.write_data[index] = row_group.WriteToDisk(*checkpoint_state.writers[index]); } @@ -1343,9 +1346,9 @@ class VacuumTask : public BaseCheckpointTask { void ExecuteTask() override { MetricsTimer timer; - auto context = checkpoint_state.writer.TryGetClientContext(); - if (context) { - timer = QueryProfiler::Get(*context).StartTimer(); + auto profiler = checkpoint_state.writer.GetContext().TryGetQueryProfiler(); + if (profiler) { + timer = profiler->StartTimer(); } auto &collection = checkpoint_state.collection; @@ -1845,7 +1848,7 @@ CollectionCheckpointResult RowGroupCollection::Checkpoint(TableDataWriter &write RowGroupWriteAction::REUSE_EXISTING_ROW_GROUP_METADATA); vector extra_metadata_block_pointers = row_group.GetExtraMetadataBlockPointers(); metadata_manager.ClearModifiedBlocks(extra_metadata_block_pointers); - auto row_group_writer = checkpoint_state.writer.GetRowGroupWriter(row_group); + auto row_group_writer = checkpoint_state.writer.GetRowGroupWriter(); row_group.CheckpointDeletes(*row_group_writer); } // the totals as of the snapshot: rows appended since stay in the WAL @@ -2122,15 +2125,14 @@ CollectionCheckpointResult RowGroupCollection::Checkpoint(TableDataWriter &write } } - // flush any partial blocks BEFORE updating the row group pointer - // flushing partial blocks updates where data lives - // this cannot be done after other threads start scanning the row groups - // so this HAS to happen before we call "SetRowGroups" to update the row groups - writer.FlushPartialBlocks(); - // Rebuild indexes if the REBUILD strategy was chosen (legacy vacuum_rebuild_indexes path) and rowids changed. + // Index rebuilds need the checkpointed row groups to be installed first. if (vacuum_state.index_strategy == VacuumIndexStrategy::REBUILD && writer.RowIdsChanged()) { writer.SetRebuildIndexes(); } + // Flush before installing row groups, since flushing changes their segment locations. + if (!writer.CanDeferPublication()) { + writer.FlushPartialBlocks(); + } CollectionCheckpointResult result; result.row_groups = std::move(new_row_groups); diff --git a/src/duckdb/src/storage/table/row_id_column_data.cpp b/src/duckdb/src/storage/table/row_id_column_data.cpp index a285c42e4..75ac97037 100644 --- a/src/duckdb/src/storage/table/row_id_column_data.cpp +++ b/src/duckdb/src/storage/table/row_id_column_data.cpp @@ -1,6 +1,7 @@ #include "duckdb/storage/table/row_id_column_data.hpp" #include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/storage/table/scan_state.hpp" namespace duckdb { @@ -15,14 +16,49 @@ idx_t RowIdColumnData::GetRowStart(ColumnScanState &state) { return state.parent->GetRowGroup()->GetRowStart(); } -FilterPropagateResult RowIdColumnData::CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) { - checked_segment = nullptr; - auto row_start = GetRowStart(state); - return RowGroup::CheckRowIdFilter(filter, row_start, row_start + count); +//! Optional filters are not executed, but the row ids they reject still let the scan skip vectors +static bool PrunesVectors(const ScanFilter &filter) { + return !filter.IsAlwaysTrue() || ExpressionFilter::IsRootNonSelectivityOptionalFilter(filter.filter); +} + +static bool RejectsRowIds(const TableFilter &filter, idx_t start_row_id, idx_t end_row_id) { + const auto prune_result = RowGroup::CheckRowIdFilter(filter, start_row_id, end_row_id); + return prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE || + prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL; +} + +FilterPropagateResult RowIdColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { + return CheckZonemapAt(state, filter, state.parent->vector_index * STANDARD_VECTOR_SIZE, checked_end); +} + +FilterPropagateResult RowIdColumnData::CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, + optional_idx &checked_end) { + if (!PrunesVectors(filter)) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + // the row ids of each vector are known, so look ahead for the first vector with a row id the filter accepts + const auto row_group_start = GetRowStart(state); + const idx_t scan_end = state.parent->max_row_group_row; + idx_t vector_start = row; + while (vector_start < scan_end) { + const idx_t vector_end = MinValue(AlignValue(vector_start + 1), scan_end); + if (!RejectsRowIds(filter.filter, row_group_start + vector_start, row_group_start + vector_end)) { + break; + } + vector_start = vector_end; + } + if (vector_start == row) { + // the vector of row can hold row ids the filter accepts, the next vector has to be checked again + checked_end = MinValue(AlignValue(row + 1), scan_end); + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + checked_end = vector_start; + return FilterPropagateResult::FILTER_ALWAYS_FALSE; } -void RowIdColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { +void RowIdColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { } void RowIdColumnData::InitializeScan(ColumnScanState &state) { @@ -96,8 +132,8 @@ void RowIdColumnData::Filter(TransactionData transaction, idx_t vector_index, Co return; } - // Now apply the filter - ColumnSegment::FilterSelection(sel, result, filter_state, count, count); + // the selection indexes the whole vector, so the filter needs max_count as its scan count + ColumnSegment::FilterSelection(sel, result, filter_state, max_count, count); } void RowIdColumnData::Select(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result, @@ -111,10 +147,6 @@ void RowIdColumnData::Select(TransactionData transaction, idx_t vector_index, Co state.offset_in_column += GetVectorCount(vector_index); } -idx_t RowIdColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - throw InternalException("Fetch is not supported for row id columns"); -} - void RowIdColumnData::FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t fetch_count, Vector &result, idx_t result_offset) { diff --git a/src/duckdb/src/storage/table/row_number_column_data.cpp b/src/duckdb/src/storage/table/row_number_column_data.cpp index 135a515a7..6d081eca7 100644 --- a/src/duckdb/src/storage/table/row_number_column_data.cpp +++ b/src/duckdb/src/storage/table/row_number_column_data.cpp @@ -13,14 +13,14 @@ idx_t RowNumberColumnData::GetRowNumberBase(ColumnScanState &state) { return state.parent->row_number_base.GetIndex(); } -FilterPropagateResult RowNumberColumnData::CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) { +FilterPropagateResult RowNumberColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { // row_number columns don't have zonemaps - we cannot prune based on row number - checked_segment = nullptr; return FilterPropagateResult::NO_PRUNING_POSSIBLE; } -void RowNumberColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { +void RowNumberColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, + idx_t start_row, idx_t end_row) { } void RowNumberColumnData::InitializeScan(ColumnScanState &state) { @@ -70,10 +70,6 @@ void RowNumberColumnData::Select(TransactionData transaction, idx_t vector_index state.offset_in_column += count; } -idx_t RowNumberColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - throw InternalException("Fetch is not supported for row number columns"); -} - void RowNumberColumnData::FetchRows(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t fetch_count, Vector &result, idx_t result_offset) { diff --git a/src/duckdb/src/storage/table/row_version_manager.cpp b/src/duckdb/src/storage/table/row_version_manager.cpp index 17c316777..9f140a095 100644 --- a/src/duckdb/src/storage/table/row_version_manager.cpp +++ b/src/duckdb/src/storage/table/row_version_manager.cpp @@ -226,7 +226,12 @@ void RowVersionManager::RollbackWrite(idx_t vector_idx, const uint16_t rows[], i GetVectorInfo(vector_idx).RollbackWrite(rows, count, previous_ids, previous_id_count); } -void RowVersionManager::CompressVersionIds(VisibilityBound lowest_visibility_bound) { +static idx_t VectorRowCount(idx_t vector_idx, idx_t row_count) { + idx_t vector_start = vector_idx * STANDARD_VECTOR_SIZE; + return row_count > vector_start ? MinValue(row_count - vector_start, STANDARD_VECTOR_SIZE) : 0; +} + +void RowVersionManager::CompressVersionIds(VisibilityBound lowest_visibility_bound, idx_t row_count) { lock_guard lock(version_lock); if (!needs_compression_check) { // no version ids were modified since the last pass, and the last pass left nothing @@ -244,8 +249,10 @@ void RowVersionManager::CompressVersionIds(VisibilityBound lowest_visibility_bou return; } bool pending = false; - for (auto &info : vector_info) { - if (info && info->CompressVersionIds(lowest_visibility_bound) == VersionCompressionResult::PENDING) { + for (idx_t vector_idx = 0; vector_idx < vector_info.size(); vector_idx++) { + auto &info = vector_info[vector_idx]; + if (info && info->CompressVersionIds(lowest_visibility_bound, VectorRowCount(vector_idx, row_count)) == + VersionCompressionResult::PENDING) { // some ids can still compress once the lowest active start advances - check again next pass pending = true; } @@ -256,7 +263,7 @@ void RowVersionManager::CompressVersionIds(VisibilityBound lowest_visibility_bou allocator.RemoveEmptyBuffers(); } -vector RowVersionManager::Checkpoint(RowGroupWriter &writer) { +vector RowVersionManager::Checkpoint(RowGroupWriter &writer, idx_t row_count) { lock_guard lock(version_lock); auto &manager = *writer.GetMetadataManager(); auto options = writer.GetCheckpointOptions(); @@ -275,7 +282,12 @@ vector RowVersionManager::Checkpoint(RowGroupWriter &writer) { if (!chunk_info) { continue; } - if (!chunk_info->HasDeletes(options.visibility_bound)) { + auto vector_row_count = VectorRowCount(vector_idx, row_count); + if (vector_row_count == 0) { + // the vector holds no rows - there is nothing to write + continue; + } + if (!chunk_info->HasDeletes(options.visibility_bound, vector_row_count)) { continue; } to_serialize.emplace_back(vector_idx, *chunk_info); @@ -291,7 +303,7 @@ vector RowVersionManager::Checkpoint(RowGroupWriter &writer) { auto &vector_idx = entry.first; auto &chunk_info = entry.second.get(); metadata_writer.Write(vector_idx); - chunk_info.Write(metadata_writer, options.visibility_bound); + chunk_info.Write(metadata_writer, options.visibility_bound, VectorRowCount(vector_idx, row_count)); } metadata_writer.Flush(); } diff --git a/src/duckdb/src/storage/table/scan_state.cpp b/src/duckdb/src/storage/table/scan_state.cpp index 9e4eaaba7..5ba7a5573 100644 --- a/src/duckdb/src/storage/table/scan_state.cpp +++ b/src/duckdb/src/storage/table/scan_state.cpp @@ -90,7 +90,7 @@ void ScanFilterInfo::Initialize(ClientContext &context, TableFilterSet &filters, this->column_ids = &column_ids; if (filters.HasFilters()) { adaptive_filter = make_uniq(filters); - adaptive_filter->SetLogger(context.logger); + adaptive_filter->SetLogger(context.GetContext().GetLoggerPtr()); } filter_list.reserve(filters.FilterCount()); for (auto &entry : filters) { @@ -371,8 +371,7 @@ vector> CollectionScanState::RegisterAssignmentIO() { D_ASSERT(row_group); D_ASSERT(!assignment_io_registered); assignment_io_registered = true; - auto ¤t_row_group = *pinned_row_group; - return current_row_group.CollectScanIOTasks(*this, current_row_group.PrefetchRowCount(*this)); + return pinned_row_group->CollectAssignmentIOTasks(*this); } void CollectionScanState::InitializeColumnScans() { diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index ac2fa3ed2..01842616d 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -35,9 +35,10 @@ ScanVectorType StandardColumnData::GetVectorScanType(ColumnScanState &state, idx return validity->GetVectorScanType(state.child_states[0], scan_count, result); } -void StandardColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { - ColumnData::InitializePrefetch(prefetch_state, scan_state, rows); - validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], rows); +void StandardColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { + ColumnData::InitializePrefetch(prefetch_state, scan_state, start_row, end_row); + validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], start_row, end_row); } void StandardColumnData::InitializeScan(ColumnScanState &state) { @@ -125,6 +126,7 @@ void StandardColumnData::Select(TransactionData transaction, idx_t vector_index, void StandardColumnData::InitializeAppend(ColumnAppendState &state) { ColumnData::InitializeAppend(state); ColumnAppendState child_append; + child_append.transient = state.transient; validity->InitializeAppend(child_append); state.child_appends.push_back(std::move(child_append)); } @@ -144,26 +146,11 @@ void StandardColumnData::RevertAppend(row_t new_count) { validity->RevertAppend(new_count); } -idx_t StandardColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - // fetch validity mask - if (state.child_states.empty()) { - ColumnScanState child_state(state.parent); - child_state.scan_options = state.scan_options; - state.child_states.push_back(std::move(child_state)); - } - auto scan_count = ColumnData::Fetch(state, row_id, result); - validity->Fetch(state.child_states[0], row_id, result); - return scan_count; -} - void StandardColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t row_group_start) { - ColumnScanState standard_state(nullptr); - ColumnScanState validity_state(nullptr); - Vector base_vector(type); - - FetchUpdateData(standard_state, row_ids, base_vector, row_group_start); - validity->FetchUpdateData(validity_state, row_ids, base_vector, row_group_start); + Vector base_vector(type, update_count); + FetchBaseRows(row_ids, update_count, base_vector, row_group_start); + validity->FetchBaseRows(row_ids, update_count, base_vector, row_group_start); UpdateInternal(transaction, table_entry, column_index, update_vector, row_ids, update_count, base_vector, row_group_start); @@ -340,6 +327,21 @@ PersistentColumnData StandardColumnData::Serialize() { void StandardColumnData::InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) { ColumnData::InitializeColumn(column_data, target_stats); validity->InitializeColumn(column_data.child_columns[0], target_stats); + // segments without a byte size come from older storage, which may record NULLs only in the validity statistics + bool legacy_segments = false; + for (auto &pointer : column_data.pointers) { + legacy_segments = legacy_segments || !pointer.byte_size; + } + bool validity_has_null = false; + for (auto &pointer : column_data.child_columns[0].pointers) { + validity_has_null = validity_has_null || pointer.statistics.CanHaveNull(); + } + if (!legacy_segments || !validity_has_null) { + return; + } + for (auto &node : data.SegmentNodes()) { + node.GetNode().GetStatsMutable().SetHasNull(); + } } void StandardColumnData::GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, diff --git a/src/duckdb/src/storage/table/struct_column_data.cpp b/src/duckdb/src/storage/table/struct_column_data.cpp index bae1392a4..44813294f 100644 --- a/src/duckdb/src/storage/table/struct_column_data.cpp +++ b/src/duckdb/src/storage/table/struct_column_data.cpp @@ -47,18 +47,28 @@ idx_t StructColumnData::GetMaxEntry() { return validity->GetMaxEntry(); } -FilterPropagateResult StructColumnData::CheckZonemap(ColumnScanState &state, TableFilter &filter, - optional_ptr> &checked_segment) { - if (state.expression_state) { - checked_segment = nullptr; +FilterPropagateResult StructColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { + if (state.expression_state || filter.IsAlwaysTrue()) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } if (state.storage_index.IsPushdownExtract()) { auto children = GetStructChildren(state); D_ASSERT(children.size() == 1); - return children[0].col.CheckZonemap(children[0].state, filter, checked_segment); + return children[0].col.CheckZonemap(children[0].state, filter, checked_end); } - return CheckValidityZonemap(state, filter, checked_segment, *validity); + return CheckValidityZonemap(state, filter, checked_end, *validity); +} + +FilterPropagateResult StructColumnData::CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, + optional_idx &checked_end) { + if (state.expression_state || !state.storage_index.IsPushdownExtract()) { + // the scan judges null checks on the validity child + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + auto children = GetStructChildren(state); + D_ASSERT(children.size() == 1); + return children[0].col.CheckZonemapAt(children[0].state, filter, row, checked_end); } vector StructColumnData::GetStructChildren(ColumnScanState &state) const { @@ -80,14 +90,15 @@ vector StructColumnData::GetStructChild return res; } -void StructColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { - validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], rows); +void StructColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { + validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], start_row, end_row); auto struct_children = GetStructChildren(scan_state); for (auto &child : struct_children) { if (!child.should_scan) { continue; } - child.col.InitializePrefetch(prefetch_state, child.state, rows); + child.col.InitializePrefetch(prefetch_state, child.state, start_row, end_row); } } @@ -225,11 +236,13 @@ void StructColumnData::Skip(ColumnScanState &state, idx_t count) { void StructColumnData::InitializeAppend(ColumnAppendState &state) { ColumnAppendState validity_append; + validity_append.transient = state.transient; validity->InitializeAppend(validity_append); state.child_appends.push_back(std::move(validity_append)); for (auto &sub_column : sub_columns) { ColumnAppendState child_append; + child_append.transient = state.transient; sub_column->InitializeAppend(child_append); state.child_appends.push_back(std::move(child_append)); } @@ -270,24 +283,6 @@ void StructColumnData::RevertAppend(row_t new_count) { this->count = UnsafeNumericCast(new_count); } -idx_t StructColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - // fetch validity mask - auto &child_entries = StructVector::GetEntries(result); - // insert any child states that are required - for (idx_t i = state.child_states.size(); i < child_entries.size() + 1; i++) { - ColumnScanState child_state(state.parent); - child_state.scan_options = state.scan_options; - state.child_states.push_back(std::move(child_state)); - } - // fetch the validity state - idx_t scan_count = validity->Fetch(state.child_states[0], row_id, result); - // fetch the sub-column states - for (idx_t i = 0; i < child_entries.size(); i++) { - sub_columns[i]->Fetch(state.child_states[i + 1], row_id, child_entries[i]); - } - return scan_count; -} - void StructColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t row_group_start) { validity->Update(transaction, table_entry, column_index, update_vector, row_ids, update_count, row_group_start); diff --git a/src/duckdb/src/storage/table/update_segment.cpp b/src/duckdb/src/storage/table/update_segment.cpp index e06beb16e..f47c0d7da 100644 --- a/src/duckdb/src/storage/table/update_segment.cpp +++ b/src/duckdb/src/storage/table/update_segment.cpp @@ -21,8 +21,7 @@ static UpdateSegment::statistics_update_function_t GetStatisticsUpdateFunction(P static UpdateSegment::fetch_rows_function_t GetFetchRowsFunction(PhysicalType type); static UpdateSegment::get_effective_updates_t GetEffectiveUpdatesFunction(PhysicalType type); -UpdateSegment::UpdateSegment(ColumnData &column_data) - : column_data(column_data), stats(column_data.type), heap(BufferAllocator::Get(column_data.GetDatabase())) { +UpdateSegment::UpdateSegment(ColumnData &column_data) : column_data(column_data), stats(column_data.type) { auto physical_type = column_data.type.InternalType(); this->type_size = GetTypeIdSize(physical_type); @@ -375,6 +374,7 @@ void UpdateSegment::FetchUpdates(TransactionData transaction, idx_t vector_index D_ASSERT(result.GetVectorType() == VectorType::FLAT_VECTOR); auto pin = node.Pin(); fetch_update_function(transaction.view, UpdateInfo::Get(pin), result); + AddStringHeapReference(*lock_handle, vector_index, result); } UpdateNode::UpdateNode(BufferManager &manager) : allocator(manager, false) { @@ -383,6 +383,101 @@ UpdateNode::UpdateNode(BufferManager &manager) : allocator(manager, false) { UpdateNode::~UpdateNode() { } +//===--------------------------------------------------------------------===// +// String Heap +//===--------------------------------------------------------------------===// +UpdateStringHeap::UpdateStringHeap(Allocator &allocator, idx_t initial_capacity) + : allocator(allocator, initial_capacity) { +} + +string_t UpdateStringHeap::AddString(const string_t &str) { + if (str.IsInlined()) { + return str; + } + auto length = str.GetSize(); + auto data = allocator.Allocate(length); + memcpy(data, str.GetData(), length); + size += length; + return string_t(char_ptr_cast(data), UnsafeNumericCast(length)); +} + +//! Keeps the string heap of a vector alive while the strings are referenced by a scanned vector +struct UpdateStringHeapHolder : public AuxiliaryDataHolder { + explicit UpdateStringHeapHolder(shared_ptr heap_p) : heap(std::move(heap_p)) { + } + + shared_ptr heap; +}; + +//! Strings are only compacted once the heap has grown by at least this amount since the last compaction +static constexpr idx_t MINIMUM_STRING_HEAP_COMPACTION_SIZE = 16384; + +void UpdateSegment::AddStringHeapReference(const StorageLockKey &, idx_t vector_index, Vector &result) const { + if (vector_index >= root->string_heaps.size()) { + return; + } + auto &string_heap = root->string_heaps[vector_index]; + if (!string_heap || string_heap->size == 0) { + return; + } + result.AddAuxiliaryData(make_uniq(string_heap)); +} + +//! Call the callback for every string stored in the root, and in the (pinned) update infos of its chain +template +static void ForEachUpdateString(UpdateInfo &root_info, vector &chain, FUNC &&callback) { + auto root_data = root_info.GetData(); + for (idx_t i = 0; i < root_info.N; i++) { + callback(root_data[i]); + } + for (auto &pin : chain) { + auto &info = UpdateInfo::Get(pin); + auto info_data = info.GetData(); + auto value_count = info.GetValueMask().CountValid(info.N); + for (idx_t i = 0; i < value_count; i++) { + callback(info_data[i]); + } + } +} + +void UpdateSegment::CompactStringHeapIfNeeded(UpdateInfo &root_info, idx_t vector_index, idx_t new_size) { + auto &string_heap = root->string_heaps[vector_index]; + if (string_heap->size + new_size < 2 * string_heap->compacted_size + MINIMUM_STRING_HEAP_COMPACTION_SIZE) { + return; + } + // the strings in the heap are referenced by the root and by the update infos in its chain + vector chain; + auto next = root_info.next; + while (next.IsSet()) { + chain.push_back(next.Pin()); + next = UpdateInfo::Get(chain.back()).next; + } + idx_t live_size = 0; + ForEachUpdateString(root_info, chain, [&](string_t &str) { + if (!str.IsInlined()) { + live_size += str.GetSize(); + } + }); + // allocate everything up front, so nothing is modified if this fails + // the first block of the arena is twice its initial capacity: it fits all strings until the next compaction + auto capacity = MaxValue(2 * live_size + MINIMUM_STRING_HEAP_COMPACTION_SIZE, live_size + new_size); + auto new_heap = make_shared_ptr(BufferAllocator::Get(column_data.GetDatabase()), capacity / 2); + auto target = live_size == 0 ? nullptr : new_heap->allocator.Allocate(live_size); + ForEachUpdateString(root_info, chain, [&](string_t &str) { + if (str.IsInlined()) { + return; + } + auto length = str.GetSize(); + memcpy(target, str.GetData(), length); + str = string_t(char_ptr_cast(target), UnsafeNumericCast(length)); + target += length; + }); + new_heap->size = live_size; + new_heap->compacted_size = live_size; + // scans that still reference strings in the old heap keep it alive + string_heap = std::move(new_heap); +} + //===--------------------------------------------------------------------===// // Fetch Committed //===--------------------------------------------------------------------===// @@ -445,6 +540,7 @@ void UpdateSegment::FetchCommitted(idx_t vector_index, Vector &result) { D_ASSERT(result.GetVectorType() == VectorType::FLAT_VECTOR); auto pin = node.Pin(); fetch_committed_function(UpdateInfo::Get(pin), result); + AddStringHeapReference(*lock_handle, vector_index, result); } //===--------------------------------------------------------------------===// @@ -560,6 +656,7 @@ void UpdateSegment::FetchCommittedRange(idx_t start_row, idx_t count, Vector &re D_ASSERT(end_in_vector > 0 && end_in_vector <= STANDARD_VECTOR_SIZE); idx_t result_offset = ((vector_idx * STANDARD_VECTOR_SIZE) + start_in_vector) - start_row; fetch_committed_range(UpdateInfo::Get(pin), start_in_vector, end_in_vector, result_offset, result); + AddStringHeapReference(*lock_handle, vector_idx, result); } } @@ -704,6 +801,7 @@ void UpdateSegment::FetchRows(TransactionData transaction, const idx_t *offsets, auto pin = entry.Pin(); fetch_rows_function(transaction.view, UpdateInfo::Get(pin), offsets, sel, idx, vector_count, vector_offset, result, result_offset); + AddStringHeapReference(*lock_handle, vector_index, result); } idx += vector_count; } @@ -1272,9 +1370,10 @@ UpdateSegment::statistics_update_function_t GetStatisticsUpdateFunction(Physical //===--------------------------------------------------------------------===// // Get Effective Updates //===--------------------------------------------------------------------===// -idx_t GetEffectiveUpdatesValidity(UnifiedVectorFormat &update, row_t *ids, idx_t count, SelectionVector &sel, - Vector &base_data, idx_t id_offset) { - auto &original_validity = FlatVector::ValidityMutable(base_data); +// base_data is dense and aligned with the update vector: index i is update row i +idx_t GetEffectiveUpdatesValidity(UnifiedVectorFormat &update, idx_t count, SelectionVector &sel, + const Vector &base_data) { + auto &original_validity = FlatVector::Validity(base_data); SelectionVector new_sel; new_sel.Initialize(STANDARD_VECTOR_SIZE); @@ -1283,8 +1382,7 @@ idx_t GetEffectiveUpdatesValidity(UnifiedVectorFormat &update, row_t *ids, idx_t for (idx_t i = 0; i < count; i++) { auto sel_idx = sel.get_index(i); auto update_idx = update.sel->get_index(sel_idx); - auto original_idx = UnsafeNumericCast(ids[sel_idx]) - id_offset; - if (original_validity.RowIsValid(original_idx) == update.validity.RowIsValid(update_idx)) { + if (original_validity.RowIsValid(sel_idx) == update.validity.RowIsValid(update_idx)) { continue; } new_sel.set_index(effective_count++, sel_idx); @@ -1294,12 +1392,12 @@ idx_t GetEffectiveUpdatesValidity(UnifiedVectorFormat &update, row_t *ids, idx_t } template -idx_t TemplatedGetEffectiveUpdates(UnifiedVectorFormat &update, row_t *ids, idx_t count, SelectionVector &sel, - Vector &base_data, idx_t id_offset) { +idx_t TemplatedGetEffectiveUpdates(UnifiedVectorFormat &update, idx_t count, SelectionVector &sel, + const Vector &base_data) { auto data = UnifiedVectorFormat::GetData(update); auto original_data = FlatVector::GetData(base_data); - auto &original_validity = FlatVector::ValidityMutable(base_data); + auto &original_validity = FlatVector::Validity(base_data); SelectionVector new_sel; new_sel.Initialize(STANDARD_VECTOR_SIZE); @@ -1308,10 +1406,9 @@ idx_t TemplatedGetEffectiveUpdates(UnifiedVectorFormat &update, row_t *ids, idx_ for (idx_t i = 0; i < count; i++) { auto sel_idx = sel.get_index(i); auto update_idx = update.sel->get_index(sel_idx); - auto original_idx = UnsafeNumericCast(ids[sel_idx]) - id_offset; // NULL values in the updates should have been filtered out before D_ASSERT(update.validity.RowIsValid(update_idx)); - if (original_validity.RowIsValid(original_idx) && data[update_idx] == original_data[original_idx]) { + if (original_validity.RowIsValid(sel_idx) && data[update_idx] == original_data[sel_idx]) { // data is equivalent - skip continue; } @@ -1457,20 +1554,21 @@ void UpdateSegment::ReallocateRootInfoIfNeeded(UpdateInfo ¤t_info, idx_t u } void UpdateSegment::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, - Vector &update_p, row_t *ids, idx_t count, Vector &base_data, idx_t row_group_start) { + Vector &update_p, row_t *ids, idx_t count, const Vector &base_data, idx_t row_group_start) { // obtain an exclusive lock auto write_lock = lock.GetExclusiveLock(); UnifiedVectorFormat update_format; update_p.ToUnifiedFormat(update_format); + const idx_t input_count = count; - // update statistics + // the statistics of this update join those of the segment only once it cannot fail anymore, as RowGroup::Update + // publishes them after the next update of the column, which must not see the values of a failed update SelectionVector sel; - { - lock_guard stats_guard(stats_lock); - count = statistics_update_function(this, stats, update_format, count, sel); - } + SegmentStatistics update_stats(column_data.type); + count = statistics_update_function(this, update_stats, update_format, count, sel); if (count == 0) { + MergeStatistics(update_stats); return; } @@ -1492,22 +1590,13 @@ void UpdateSegment::Update(TransactionData transaction, DuckTableEntry &table_en // if updates have the same value as the base row we can skip them // we only do that if we have no updates for this vector // we could do it otherwise - but that would require merging updates in order to find the current values - count = get_effective_updates(update_format, ids, count, sel, base_data, vector_offset); + D_ASSERT(base_data.GetVectorType() == VectorType::FLAT_VECTOR); + count = get_effective_updates(update_format, count, sel, base_data); if (count == 0) { + MergeStatistics(update_stats); return; } } - if (statistics_update_function == UpdateStringStatistics) { - // for strings - we need to push all strings we are going to place here into the string heap of the segment - update_p.Flatten(); - auto update_data = FlatVector::GetDataMutable(update_p); - for (idx_t i = 0; i < count; i++) { - auto idx = sel.get_index(i); - update_data[idx] = GetStringHeap().AddBlob(update_data[idx]); - } - update_p.ToUnifiedFormat(update_format); - } - InitializeUpdateInfo(vector_index); D_ASSERT(idx_t(first_id) >= row_group_start); @@ -1523,7 +1612,6 @@ void UpdateSegment::Update(TransactionData transaction, DuckTableEntry &table_en root_info.column_index = column_index; root->info[vector_index] = handle.GetBufferPointer(); } - // make room in the root before modifying anything { auto root_pin = root->info[vector_index].Pin(); @@ -1532,6 +1620,42 @@ void UpdateSegment::Update(TransactionData transaction, DuckTableEntry &table_en auto root_pointer = root->info[vector_index]; auto root_pin = root_pointer.Pin(); auto &root_info = UpdateInfo::Get(root_pin); + // for strings - copy the new strings into the string heap of the vector before modifying anything + unique_ptr heap_strings; + idx_t new_size = 0; + if (statistics_update_function == UpdateStringStatistics) { + auto update_data = UnifiedVectorFormat::GetData(update_format); + for (idx_t i = 0; i < count; i++) { + auto &str = update_data[update_format.sel->get_index(sel.get_index(i))]; + if (!str.IsInlined()) { + new_size += str.GetSize(); + } + } + } + if (new_size > 0) { + if (root->string_heaps.size() <= vector_index) { + root->string_heaps.resize(vector_index + 1); + } + auto &heap_entry = root->string_heaps[vector_index]; + if (!heap_entry) { + // the first block of the arena is twice its initial capacity: it fits exactly these strings + heap_entry = + make_shared_ptr(BufferAllocator::Get(column_data.GetDatabase()), (new_size + 1) / 2); + heap_entry->compacted_size = new_size; + } else { + CompactStringHeapIfNeeded(root_info, vector_index, new_size); + } + auto update_data = UnifiedVectorFormat::GetData(update_format); + auto &string_heap = *heap_entry; + heap_strings = make_uniq(update_p.GetType(), input_count); + auto heap_data = FlatVector::GetDataMutable(*heap_strings); + for (idx_t i = 0; i < count; i++) { + auto idx = sel.get_index(i); + heap_data[idx] = string_heap.AddString(update_data[update_format.sel->get_index(idx)]); + } + FlatVector::SetSize(*heap_strings, input_count); + heap_strings->ToUnifiedFormat(update_format); + } if (transaction.transaction) { // search for the update info that belongs to this transaction auto node_ref = GetTransactionUpdate(root_info.next, transaction); @@ -1617,6 +1741,12 @@ void UpdateSegment::Update(TransactionData transaction, DuckTableEntry &table_en // write the new values into the root merge_update_function(root_info, update_format, ids, count, sel, vector_offset); root_info.Verify(); + MergeStatistics(update_stats); +} + +void UpdateSegment::MergeStatistics(const SegmentStatistics &update_stats) { + lock_guard stats_guard(stats_lock); + stats.statistics.Merge(update_stats.statistics); } bool UpdateSegment::HasUpdates() const { diff --git a/src/duckdb/src/storage/table/validity_column_data.cpp b/src/duckdb/src/storage/table/validity_column_data.cpp index 32812c2c8..6399ef004 100644 --- a/src/duckdb/src/storage/table/validity_column_data.cpp +++ b/src/duckdb/src/storage/table/validity_column_data.cpp @@ -1,6 +1,5 @@ #include "duckdb/storage/table/validity_column_data.hpp" #include "duckdb/storage/table/column_checkpoint_state.hpp" -#include "duckdb/storage/table/scan_state.hpp" namespace duckdb { @@ -17,15 +16,18 @@ ValidityColumnData::ValidityColumnData(BlockManager &block_manager, DataTableInf void ValidityColumnData::UpdateWithBase(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, ColumnData &base, idx_t row_group_start) { - Vector base_vector(base.type); - ColumnScanState validity_scan_state(nullptr); - FetchUpdateData(validity_scan_state, row_ids, base_vector, row_group_start); - if (validity_scan_state.current.get()->ReferenceNode().get()->GetCompressionFunction().type == - CompressionType::COMPRESSION_EMPTY) { + D_ASSERT(update_count > 0); + if (row_ids[0] < UnsafeNumericCast(row_group_start)) { + throw InternalException("ValidityColumnData::UpdateWithBase - row id out of range"); + } + const idx_t row_offset = UnsafeNumericCast(row_ids[0]) - row_group_start; + Vector base_vector(base.type, update_count); + auto &segment = data.GetSegment(row_offset)->GetNode(); + if (segment.GetCompressionFunction().type == CompressionType::COMPRESSION_EMPTY) { // The validity is actually covered by the data, so we read it to get the validity for UpdateInternal. - ColumnScanState data_scan_state(nullptr); - base.Fetch(data_scan_state, row_ids[0] - UnsafeNumericCast(row_group_start), base_vector); - base_vector.Flatten(); + base.FetchBaseRows(row_ids, update_count, base_vector, row_group_start); + } else { + FetchBaseRows(row_ids, update_count, base_vector, row_group_start); } UpdateInternal(transaction, table_entry, column_index, update_vector, row_ids, update_count, base_vector, diff --git a/src/duckdb/src/storage/table/variant/variant_shredding.cpp b/src/duckdb/src/storage/table/variant/variant_shredding.cpp index e1b01b959..3bcfb9483 100644 --- a/src/duckdb/src/storage/table/variant/variant_shredding.cpp +++ b/src/duckdb/src/storage/table/variant/variant_shredding.cpp @@ -104,8 +104,19 @@ struct VariantStatsVisitor { } } + static bool ChildrenTooDeep(const VariantNestedData &nested_data, idx_t depth, VariantShreddingStats &stats) { + if (!nested_data.child_count || depth + 1 < VariantVisitor::MAX_RECURSION_DEPTH) { + return false; + } + stats.SetTooDeep(); + return true; + } + static void VisitArray(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, idx_t depth, VariantShreddingStats &stats, idx_t stats_column_index) { + if (ChildrenTooDeep(nested_data, depth, stats)) { + return; + } auto &element_stats = stats.GetOrCreateElement(stats_column_index); auto index = element_stats.index; VariantVisitor::VisitArrayItems(variant, row, nested_data, depth, stats, index); @@ -113,6 +124,9 @@ struct VariantStatsVisitor { static void VisitObject(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, idx_t depth, VariantShreddingStats &stats, idx_t stats_column_index) { + if (ChildrenTooDeep(nested_data, depth, stats)) { + return; + } //! Then visit the fields in sorted order for (idx_t i = 0; i < nested_data.child_count; i++) { auto source_children_idx = nested_data.children_idx + i; @@ -446,14 +460,14 @@ bool VariantShreddingStats::GetShreddedTypeInternal(const VariantColumnStatsData //! Do not include empty field names in the shredded type! continue; } - auto field_name = entry.first.GetString(); - if (!field_names.emplace(field_name).second) { + //! the set only refers to the name, which the stats own for as long as this runs + if (!field_names.emplace(entry.first).second) { //! STRUCT field names are case-insensitive, but VARIANT object keys are case-sensitive. return false; } LogicalType child_type; if (GetShreddedTypeInternal(child_column, child_type, total_value_count, force_partial)) { - child_types.emplace_back(field_name, child_type); + child_types.emplace_back(entry.first.GetString(), child_type); } } if (child_types.empty()) { @@ -477,8 +491,7 @@ bool VariantShreddingStats::GetShreddedTypeInternal(const VariantColumnStatsData return true; } if (type_index == static_cast(VariantLogicalType::DECIMAL)) { - auto shredded_type = LogicalType::DECIMAL(static_cast(column.decimal_width), - static_cast(column.decimal_scale)); + auto shredded_type = LogicalType::DECIMAL(column.decimal_width, column.decimal_scale); out_type = SetShreddedType(shredded_type, fully_consistent); return true; } @@ -495,7 +508,7 @@ LogicalType VariantShreddingStats::GetShreddedType(bool force_partial) const { child_list_t child_types; child_types.emplace_back("unshredded", VariantShredding::GetUnshreddedType()); LogicalType shredded_type; - if (GetShreddedTypeInternal(root_column, shredded_type, optional_idx(), force_partial)) { + if (!too_deep && GetShreddedTypeInternal(root_column, shredded_type, optional_idx(), force_partial)) { child_types.emplace_back("shredded", shredded_type); } return LogicalType::STRUCT(child_types); @@ -842,6 +855,12 @@ void VariantColumnData::DebugShred(Vector &variant, idx_t count) { //! will be partially shredded (i.e. fall back to the unshredded/overlay component) VariantShreddingStats stats; stats.Update(materialized, 1); + //! the later values are shredded too, so none of them can be nested too deep for the normalizer + VariantShreddingStats depth_stats; + depth_stats.Update(materialized, count); + if (depth_stats.IsTooDeep()) { + return; + } //! force_partial keeps the overlay columns so that later values that don't match the first value's //! schema are partially shredded instead of failing to shred auto shredded_struct_type = stats.GetShreddedType(true); diff --git a/src/duckdb/src/storage/table/variant_column_data.cpp b/src/duckdb/src/storage/table/variant_column_data.cpp index f1ef92187..4edd72240 100644 --- a/src/duckdb/src/storage/table/variant_column_data.cpp +++ b/src/duckdb/src/storage/table/variant_column_data.cpp @@ -184,11 +184,12 @@ idx_t VariantColumnData::GetMaxEntry() { return sub_columns[0]->GetMaxEntry(); } -void VariantColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t rows) { +void VariantColumnData::InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t start_row, + idx_t end_row) { //! FIXME: does this also need CreateScanStates ?? - validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], rows); + validity->InitializePrefetch(prefetch_state, scan_state.child_states[0], start_row, end_row); for (idx_t i = 0; i < sub_columns.size(); i++) { - sub_columns[i]->InitializePrefetch(prefetch_state, scan_state.child_states[i + 1], rows); + sub_columns[i]->InitializePrefetch(prefetch_state, scan_state.child_states[i + 1], start_row, end_row); } } @@ -350,12 +351,14 @@ void VariantColumnData::Skip(ColumnScanState &state, idx_t count) { void VariantColumnData::InitializeAppend(ColumnAppendState &state) { ColumnAppendState validity_append; + validity_append.transient = state.transient; validity->InitializeAppend(validity_append); state.child_appends.push_back(std::move(validity_append)); for (idx_t i = 0; i < sub_columns.size(); i++) { auto &sub_column = sub_columns[i]; ColumnAppendState child_append; + child_append.transient = state.transient; sub_column->InitializeAppend(child_append); state.child_appends.push_back(std::move(child_append)); } @@ -418,10 +421,6 @@ void VariantColumnData::RevertAppend(row_t new_count) { this->count = UnsafeNumericCast(new_count); } -idx_t VariantColumnData::Fetch(ColumnScanState &state, row_t row_id, Vector &result) { - throw NotImplementedException("VARIANT Fetch"); -} - void VariantColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t row_group_start) { throw NotImplementedException("VARIANT Update is not supported."); @@ -751,9 +750,8 @@ unique_ptr VariantColumnData::Checkpoint(const RowGroup & LogicalType shredded_type; if (should_shred) { - if (config.options.force_variant_shredding.id() != LogicalTypeId::INVALID) { - shredded_type = config.options.force_variant_shredding; - } else { + shredded_type = config.GetForceVariantShredding(); + if (shredded_type.id() == LogicalTypeId::INVALID) { shredded_type = GetShreddedType(); } D_ASSERT(shredded_type.id() == LogicalTypeId::STRUCT); diff --git a/src/duckdb/src/storage/table_index_list.cpp b/src/duckdb/src/storage/table_index_list.cpp index 8f8ab9ae7..e4011dfd0 100644 --- a/src/duckdb/src/storage/table_index_list.cpp +++ b/src/duckdb/src/storage/table_index_list.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/shared_ptr_ipp.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/unique_ptr.hpp" +#include "duckdb/storage/checkpoint/pending_publication.hpp" #include "duckdb/storage/checkpoint/table_index_writer.hpp" #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" @@ -20,7 +21,6 @@ #include "duckdb/planner/expression_binder/index_binder.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/storage/table/data_table_info.hpp" -#include "duckdb/common/serializer/serializer.hpp" #include "duckdb/storage/table/scan_state.hpp" #include "duckdb/main/attached_database.hpp" #include @@ -411,25 +411,30 @@ void TableIndexList::Bind(ClientContext &context, DataTableInfo &table_info, con throw InternalException("index entry bind state cannot be BOUND here"); } - // Create a binder to bind this index. - auto binder = Binder::CreateBinder(context); + // Apply any outstanding buffered replays and replace the unbound index with a bound index. + unique_ptr bound_idx; + try { + // Create a binder to bind this index. + auto binder = Binder::CreateBinder(context); - // Add the table to the binder. - vector dummy_column_ids; - binder->bind_context.AddBaseTable(TableIndex(0), Identifier(), StringsToIdentifiers(column_names), column_types, - dummy_column_ids, table); + // Add the table to the binder. + vector dummy_column_ids; + binder->bind_context.AddBaseTable(TableIndex(0), Identifier(), StringsToIdentifiers(column_names), + column_types, dummy_column_ids, table); - // Create an IndexBinder to bind the index - IndexBinder idx_binder(*binder, context); + // Create an IndexBinder to bind the index + IndexBinder idx_binder(*binder, context); - // Apply any outstanding buffered replays and replace the unbound index with a bound index. - unique_ptr bound_idx; - { vector physical_column_types; for (auto &col : table.GetColumns().Physical()) { physical_column_types.push_back(col.Type()); } bound_idx = index_entry->Bind(idx_binder, physical_column_types); + } catch (...) { + // Leave the index unbound, so that a later attempt binds it instead of waiting for this one forever. + lock.lock(); + index_entry->SetBindState(IndexBindState::UNBOUND); + throw; } // Commit the bound index to the index entry. @@ -488,26 +493,42 @@ unordered_set TableIndexList::GetIndexedColumns() const { return column_ids; } +namespace { + +class PendingIndexPublication final : public PendingPublication { +public: + PendingIndexPublication(shared_ptr entry_p, unique_ptr shadow_index_p) + : entry(std::move(entry_p)), shadow_index(std::move(shadow_index_p)) { + D_ASSERT(entry); + D_ASSERT(shadow_index); + } + + void Publish() override { + D_ASSERT(shadow_index); + entry->InstallShadow(std::move(shadow_index)); + } + +private: + shared_ptr entry; + unique_ptr shadow_index; +}; + +} // namespace + vector> TableIndexList::Checkpoint(TableIndexWriter &writer) { annotated_lock_guard lock(index_entries_lock); - vector> shadows; vector> infos; - shadows.reserve(index_entries.size()); infos.reserve(index_entries.size()); for (const auto &entry : index_entries) { auto checkpoint = entry->Checkpoint(writer); - shadows.push_back(std::move(checkpoint.shadow_index)); + if (checkpoint.shadow_index) { + writer.AddPendingPublication(make_uniq(entry, std::move(checkpoint.shadow_index))); + } infos.push_back(std::move(checkpoint.storage_info)); } - writer.Flush(); - - for (idx_t i = 0; i < index_entries.size(); i++) { - index_entries[i]->InstallShadow(std::move(shadows[i])); - } - return infos; } diff --git a/src/duckdb/src/storage/temporary_file_manager.cpp b/src/duckdb/src/storage/temporary_file_manager.cpp index 5d6d89e41..33211ee99 100644 --- a/src/duckdb/src/storage/temporary_file_manager.cpp +++ b/src/duckdb/src/storage/temporary_file_manager.cpp @@ -384,8 +384,8 @@ void TemporaryFileHandle::RemoveTempBlockIndex(TemporaryFileLock &, idx_t index) // as a result we can truncate the file #ifndef WIN32 // this ended up causing issues when sorting auto max_index = index_manager.GetMaxIndex(); - auto &fs = FileSystem::GetFileSystem(db); - fs.Truncate(*handle, NumericCast(GetPositionInFile(max_index))); + // truncate through the file system that opened the handle, which a wrapper installed later does not own + handle->Truncate(NumericCast(GetPositionInFile(max_index))); #endif } } diff --git a/src/duckdb/src/storage/temporary_memory_manager.cpp b/src/duckdb/src/storage/temporary_memory_manager.cpp index 2432a15a4..78d98a517 100644 --- a/src/duckdb/src/storage/temporary_memory_manager.cpp +++ b/src/duckdb/src/storage/temporary_memory_manager.cpp @@ -1,6 +1,6 @@ #include "duckdb/storage/temporary_memory_manager.hpp" -#include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/connection_manager.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/parallel/task_scheduler.hpp" @@ -25,7 +25,7 @@ void TemporaryMemoryState::SetRemainingSize(idx_t new_remaining_size) { temporary_memory_manager.SetRemainingSize(*this, new_remaining_size); } -void TemporaryMemoryState::SetRemainingSizeAndUpdateReservation(ClientContext &context, idx_t new_remaining_size) { +void TemporaryMemoryState::SetRemainingSizeAndUpdateReservation(Context &context, idx_t new_remaining_size) { D_ASSERT(new_remaining_size != 0); // Use SetZero instead const annotated_lock_guard guard(temporary_memory_manager.lock); temporary_memory_manager.SetRemainingSize(*this, new_remaining_size); @@ -50,7 +50,7 @@ idx_t TemporaryMemoryState::GetMinimumReservation() const { return minimum_reservation; } -void TemporaryMemoryState::UpdateReservation(ClientContext &context) { +void TemporaryMemoryState::UpdateReservation(Context &context) { const annotated_lock_guard guard(temporary_memory_manager.lock); temporary_memory_manager.UpdateState(context, *this); } @@ -86,23 +86,23 @@ void TemporaryMemoryManager::Unregister(TemporaryMemoryState &temporary_memory_s Verify(); } -void TemporaryMemoryManager::UpdateConfiguration(ClientContext &context) { - auto &buffer_manager = BufferManager::GetBufferManager(context); - auto &task_scheduler = TaskScheduler::GetScheduler(context); +void TemporaryMemoryManager::UpdateConfiguration(Context &context) { + auto &buffer_manager = context.GetBufferManager(); + auto &task_scheduler = context.GetTaskScheduler(); memory_limit = LossyNumericCast(MAXIMUM_MEMORY_LIMIT_RATIO * static_cast(buffer_manager.GetMaxMemory())); has_temporary_directory = buffer_manager.HasTemporaryDirectory(); num_threads = task_scheduler.NumberOfThreads(); - num_connections = ConnectionManager::Get(context).GetConnectionCount(); + num_connections = ConnectionManager::Get(context.GetDatabase()).GetConnectionCount(); query_max_memory = buffer_manager.GetOperatorMemoryLimit(); } -TemporaryMemoryManager &TemporaryMemoryManager::Get(ClientContext &context) { - return BufferManager::GetBufferManager(context).GetTemporaryMemoryManager(); +TemporaryMemoryManager &TemporaryMemoryManager::Get(Context &context) { + return context.GetBufferManager().GetTemporaryMemoryManager(); } -unique_ptr TemporaryMemoryManager::Register(ClientContext &context) { +unique_ptr TemporaryMemoryManager::Register(Context &context) { const annotated_lock_guard guard(lock); UpdateConfiguration(context); @@ -115,7 +115,7 @@ unique_ptr TemporaryMemoryManager::Register(ClientContext return result; } -void TemporaryMemoryManager::UpdateState(ClientContext &context, TemporaryMemoryState &temporary_memory_state) { +void TemporaryMemoryManager::UpdateState(Context &context, TemporaryMemoryState &temporary_memory_state) { UpdateConfiguration(context); // The lower bound for the reservation of this state is either the minimum reservation or the remaining size diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index b455cb89d..ef0c6c90d 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -124,7 +124,7 @@ class WriteAheadLogDeserializer { auto offset = stream.CurrentOffset(); auto file_size = stream.FileSize(); - if (offset + size > file_size) { + if (offset > file_size || size > file_size - offset) { throw SerializationException( "Corrupt WAL file: entry size exceeded remaining data in file at byte position %llu " "(found entry with size %llu bytes, file size %llu bytes)", @@ -148,6 +148,9 @@ class WriteAheadLogDeserializer { } if (state_p.wal_version == 3) { + if (!state_p.db.GetStorageManager().IsEncrypted()) { + throw IOException("Failed to read WAL: the WAL is marked as encrypted, but the database is not"); + } auto &database = state_p.db.GetDatabase(); //! Version 3 means that the WAL is encrypted //! For encryption, the length field remains plaintext @@ -184,7 +187,8 @@ class WriteAheadLogDeserializer { tag.SetSize(0); } - if (offset + nonce.size() + ciphertext_size + tag.size() > file_size) { + const auto trailer_size = nonce.size() + sizeof(uint64_t) + tag.size(); + if (offset > file_size || trailer_size > file_size - offset || size > file_size - offset - trailer_size) { throw SerializationException( "Corrupt Encrypted WAL file: entry size exceeded remaining data in file at byte position %llu " "(found entry with size %llu bytes, file size %llu bytes)", @@ -516,10 +520,9 @@ unique_ptr WriteAheadLogReplayer::ReplayLog(unique_ptrclient_data->profiler; - profiler.AddToMetricCounter(MetricStorageWALReplayEntryCount::Name, replay_entry_count); + auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + if (profiler) { + profiler->AddToMetricCounter(MetricStorageWALReplayEntryCount::Name, replay_entry_count); } } catch (std::exception &ex) { // LCOV_EXCL_START ErrorData error(ex); @@ -792,7 +795,7 @@ void WriteAheadLogDeserializer::ReplayEntry(WALType entry_type) { ReplayDropTrigger(); break; default: - throw InternalException("Invalid WAL entry type!"); + throw DataCorruptionException("Invalid WAL entry type %d - corrupt WAL?", static_cast(entry_type)); } } @@ -861,12 +864,27 @@ static QualifiedName ReplayQualifiedName(Catalog &catalog, const QualifiedName & return entry_name.WithCatalog(catalog.GetName()).WithName(name); } +//! The catalog information of a (checksum-valid) WAL entry can still be missing or of the wrong type +template +static T &CheckedCreateInfo(const unique_ptr &info, CatalogType expected_type) { + if (!info) { + throw DataCorruptionException("Corrupt WAL file: entry is missing its catalog information"); + } + if (info->type != expected_type) { + throw DataCorruptionException("Corrupt WAL file: entry carries catalog information of an unexpected type"); + } + return info->Cast(); +} + //===--------------------------------------------------------------------===// // Replay Table //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateTable() { auto entry = WALCreateTable::Deserialize(deserializer); auto info = std::move(entry.table); + if (!info) { + throw DataCorruptionException("Corrupt WAL file: entry is missing its catalog information"); + } if (DeserializeOnly()) { return; } @@ -1031,11 +1049,11 @@ void WriteAheadLogDeserializer::ReplayAlter() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateView() { auto wal_entry = WALCreateView::Deserialize(deserializer); - auto &entry = wal_entry.view; + auto &entry = CheckedCreateInfo(wal_entry.view, CatalogType::VIEW_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateView(context, entry->Cast()); + catalog.CreateView(context, entry); } void WriteAheadLogDeserializer::ReplayDropView() { @@ -1089,12 +1107,12 @@ void WriteAheadLogDeserializer::ReplayDropSchema() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateType() { auto wal_entry = WALCreateType::Deserialize(deserializer); - auto &info = wal_entry.type; - info->on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + auto &info = CheckedCreateInfo(wal_entry.type, CatalogType::TYPE_ENTRY); + info.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; if (DeserializeOnly()) { return; } - catalog.CreateType(context, info->Cast()); + catalog.CreateType(context, info); } void WriteAheadLogDeserializer::ReplayDropType() { @@ -1115,12 +1133,14 @@ void WriteAheadLogDeserializer::ReplayDropType() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateTrigger() { auto wal_entry = WALCreateTrigger::Deserialize(deserializer); - auto &info = wal_entry.trigger; - info->on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + auto &trigger_info = CheckedCreateInfo(wal_entry.trigger, CatalogType::TRIGGER_ENTRY); + trigger_info.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; if (DeserializeOnly()) { return; } - auto &trigger_info = info->Cast(); + if (!trigger_info.base_table) { + throw DataCorruptionException("Corrupt WAL file: trigger entry is missing its base table"); + } // the trigger lives in the same (possibly nested) schema as its base table auto &table = Catalog::GetEntry( context, ReplayQualifiedName(catalog, trigger_info.GetQualifiedName(), trigger_info.base_table->Table())); @@ -1155,12 +1175,12 @@ void WriteAheadLogDeserializer::ReplayDropTrigger() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateSequence() { auto wal_entry = WALCreateSequence::Deserialize(deserializer); - auto &entry = wal_entry.sequence; + auto &entry = CheckedCreateInfo(wal_entry.sequence, CatalogType::SEQUENCE_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateSequence(context, entry->Cast()); + catalog.CreateSequence(context, entry); } void WriteAheadLogDeserializer::ReplayDropSequence() { @@ -1197,12 +1217,12 @@ void WriteAheadLogDeserializer::ReplaySequenceValue() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateMacro() { auto wal_entry = WALCreateMacro::Deserialize(deserializer); - auto &entry = wal_entry.macro; + auto &entry = CheckedCreateInfo(wal_entry.macro, CatalogType::MACRO_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateFunction(context, entry->Cast()); + catalog.CreateFunction(context, entry); } void WriteAheadLogDeserializer::ReplayDropMacro() { @@ -1222,11 +1242,11 @@ void WriteAheadLogDeserializer::ReplayDropMacro() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateTableMacro() { auto wal_entry = WALCreateTableMacro::Deserialize(deserializer); - auto &entry = wal_entry.table_macro; + auto &entry = CheckedCreateInfo(wal_entry.table_macro, CatalogType::TABLE_MACRO_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateFunction(context, entry->Cast()); + catalog.CreateFunction(context, entry); } void WriteAheadLogDeserializer::ReplayDropTableMacro() { @@ -1247,12 +1267,12 @@ void WriteAheadLogDeserializer::ReplayDropTableMacro() { void WriteAheadLogDeserializer::ReplayCreateIndex() { auto create_info = deserializer.ReadProperty>(101, "index_catalog_entry"); auto index_info = deserializer.ReadProperty(102, "index_storage_info"); + auto &info = CheckedCreateInfo(create_info, CatalogType::INDEX_ENTRY); ReplayIndexData(index_info); if (DeserializeOnly()) { return; } - auto &info = create_info->Cast(); // Ensure that the index type exists. if (info.index_type.empty()) { diff --git a/src/duckdb/src/storage/write_ahead_log.cpp b/src/duckdb/src/storage/write_ahead_log.cpp index 141f61d06..5e90b3e76 100644 --- a/src/duckdb/src/storage/write_ahead_log.cpp +++ b/src/duckdb/src/storage/write_ahead_log.cpp @@ -343,7 +343,8 @@ void WriteAheadLog::WriteSequenceValue(SequenceValue val) { WriteAheadLogSerializer serializer(*this, WALType::SEQUENCE_VALUE); // last_value (id 105) is only serialized from storage version v2.0.0 onwards, and is omitted when unset serializer.WriteEntry(WALSequenceValue(QualifiedName(sequence.schema.GetSchemaPath(), sequence.name), - val.usage_count, val.counter, val.entry->GetData().last_value)); + val.usage_count, val.counter, + val.has_last_value ? optional(val.last_value) : nullopt)); serializer.End(); } diff --git a/src/duckdb/src/transaction/duck_transaction.cpp b/src/duckdb/src/transaction/duck_transaction.cpp index acc7002a3..b6668ae12 100644 --- a/src/duckdb/src/transaction/duck_transaction.cpp +++ b/src/duckdb/src/transaction/duck_transaction.cpp @@ -39,7 +39,7 @@ DuckTransaction::DuckTransaction(DuckTransactionManager &manager, ClientContext SnapshotView view_p, idx_t catalog_version_p) : Transaction(manager, context_p), start_time(start_time), view(view_p), commit_id(0), catalog_version(catalog_version_p), awaiting_cleanup(false), undo_buffer(*this, context_p), - storage(make_uniq(context_p, *this)) { + storage(make_uniq(context_p.GetContext(), *this)) { D_ASSERT(IsCommitted(start_time) && !IsCommitted(view.transaction_id)); } @@ -143,12 +143,16 @@ void DuckTransaction::PushSequenceUsage(SequenceCatalogEntry &sequence, const Se sequence_info->entry = &sequence; sequence_info->usage_count = data.usage_count; sequence_info->counter = data.counter; + sequence_info->has_last_value = data.last_value.has_value(); + sequence_info->last_value = data.last_value.value_or(0); sequence_usage.emplace(sequence, *sequence_info); } else { auto &sequence_info = entry->second.get(); D_ASSERT(RefersToSameObject(*sequence_info.entry, sequence)); sequence_info.usage_count = data.usage_count; sequence_info.counter = data.counter; + sequence_info.has_last_value = data.last_value.has_value(); + sequence_info.last_value = data.last_value.value_or(0); } } @@ -230,7 +234,7 @@ ErrorData DuckTransaction::AppendLocalStorage(ClientContext &context, AttachedDa auto &storage_manager = db.GetStorageManager(); commit_state = storage_manager.GenStorageCommitState(*storage_manager.GetWAL()); } - auto &profiler = *context.client_data->profiler; + auto &profiler = QueryProfiler::Get(context.GetContext()); auto commit_timer = profiler.StartTimer(); storage->Commit(commit_state.get()); commit_timer.EndTimer(); @@ -251,7 +255,7 @@ ErrorData DuckTransaction::WriteToWAL(ClientContext &context, AttachedDatabase & // the append may have consumed the last local change: do not ask ShouldWriteToWAL again here D_ASSERT(commit_state); auto wal = db.GetStorageManager().GetWAL(); - auto &profiler = *context.client_data->profiler; + auto &profiler = QueryProfiler::Get(context.GetContext()); auto wal_timer = profiler.StartTimer(); undo_buffer.WriteToWAL(*wal, commit_state.get()); wal_timer.EndTimer(); @@ -350,6 +354,13 @@ void DuckTransaction::Cleanup(VisibilityBound lowest_visibility_bound) { undo_buffer.Cleanup(lowest_visibility_bound); } +unique_ptr DuckTransaction::GetCheckpointLockForStatement() { + if (checkpoint_lock) { + return nullptr; + } + return GetTransactionManager().SharedCheckpointLock(); +} + void DuckTransaction::SetModifications(DatabaseModificationType type) { if (!checkpoint_lock) { bool require_write_lock = false; diff --git a/src/duckdb/src/transaction/duck_transaction_manager.cpp b/src/duckdb/src/transaction/duck_transaction_manager.cpp index 5f9e59648..f19557670 100644 --- a/src/duckdb/src/transaction/duck_transaction_manager.cpp +++ b/src/duckdb/src/transaction/duck_transaction_manager.cpp @@ -260,7 +260,7 @@ void DuckTransactionManager::Checkpoint(ClientContext &context, bool force) { options.type = CheckpointType::CONCURRENT_CHECKPOINT; } - storage_manager.CreateCheckpoint(context, options); + storage_manager.CreateCheckpoint(context, options, &context); } unique_ptr DuckTransactionManager::SharedCheckpointLock() { diff --git a/src/duckdb/src/transaction/transaction_context.cpp b/src/duckdb/src/transaction/transaction_context.cpp index 0bd92b4ea..5e9abcec2 100644 --- a/src/duckdb/src/transaction/transaction_context.cpp +++ b/src/duckdb/src/transaction/transaction_context.cpp @@ -42,7 +42,7 @@ void TransactionContext::BeginTransaction() { current_transaction = make_uniq(context, start_timestamp, global_transaction_id); // Notify any registered state of transaction begin - for (auto &state : context.registered_state->States()) { + for (auto &state : context.GetContext().GetRegisteredState().States()) { state->TransactionBegin(*current_transaction, context); } } @@ -69,7 +69,7 @@ void TransactionContext::Commit() { auto error = transaction->Commit(); // Notify any registered state of transaction commit if (error.HasError()) { - for (auto const &s : context.registered_state->States()) { + for (auto const &s : context.GetContext().GetRegisteredState().States()) { s->TransactionRollback(*transaction, context, error); } if (Exception::InvalidatesDatabase(error.Type()) || error.Type() == ExceptionType::INTERNAL) { @@ -78,7 +78,7 @@ void TransactionContext::Commit() { } throw TransactionException("Failed to commit: %s", error.RawMessage()); } - for (auto &state : context.registered_state->States()) { + for (auto &state : context.GetContext().GetRegisteredState().States()) { state->TransactionCommit(*transaction, context); } transaction->Finalize(); @@ -114,7 +114,7 @@ void TransactionContext::Rollback(optional_ptr error) { rollback_error = ErrorData(ex); } // Notify any registered state of transaction rollback - all of them, also when one of them fails - for (auto const &s : context.registered_state->States()) { + for (auto const &s : context.GetContext().GetRegisteredState().States()) { try { s->TransactionRollback(*transaction, context, error); } catch (std::exception &ex) { diff --git a/src/duckdb/third_party/brotli/dec/decode.cpp b/src/duckdb/third_party/brotli/dec/decode.cpp index 2ee17d695..80de96165 100644 --- a/src/duckdb/third_party/brotli/dec/decode.cpp +++ b/src/duckdb/third_party/brotli/dec/decode.cpp @@ -1072,7 +1072,7 @@ static BrotliDecoderErrorCode DecodeContextMap(brotli_reg_t context_map_size, br /* Decodes a command or literal and updates block type ring-buffer. Reads 3..54 bits. */ -static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(int safe, BrotliDecoderState *s, int tree_type) { +static BROTLI_INLINE BrotliDecoderErrorCode DecodeBlockTypeAndLength(int safe, BrotliDecoderState *s, int tree_type) { brotli_reg_t max_block_type = s->num_block_types[tree_type]; const HuffmanCode *type_tree = &s->block_type_trees[tree_type * BROTLI_HUFFMAN_MAX_SIZE_258]; const HuffmanCode *len_tree = &s->block_len_trees[tree_type * BROTLI_HUFFMAN_MAX_SIZE_26]; @@ -1080,7 +1080,7 @@ static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(int safe, BrotliDecode brotli_reg_t *ringbuffer = &s->block_type_rb[tree_type * 2]; brotli_reg_t block_type; if (max_block_type <= 1) { - return BROTLI_FALSE; + return BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH; } /* Read 0..15 + 3..39 bits. */ @@ -1090,12 +1090,13 @@ static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(int safe, BrotliDecode } else { BrotliBitReaderState memento; BrotliBitReaderSaveState(br, &memento); - if (!SafeReadSymbol(type_tree, br, &block_type)) - return BROTLI_FALSE; + if (!SafeReadSymbol(type_tree, br, &block_type)) { + return BROTLI_DECODER_NEEDS_MORE_INPUT; + } if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) { s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; BrotliBitReaderRestoreState(br, &memento); - return BROTLI_FALSE; + return BROTLI_DECODER_NEEDS_MORE_INPUT; } } @@ -1111,7 +1112,7 @@ static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(int safe, BrotliDecode } ringbuffer[0] = ringbuffer[1]; ringbuffer[1] = block_type; - return BROTLI_TRUE; + return BROTLI_DECODER_SUCCESS; } static BROTLI_INLINE void DetectTrivialLiteralBlockTypes(BrotliDecoderState *s) { @@ -1148,56 +1149,59 @@ static BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState *s) { /* Decodes the block type and updates the state for literal context. Reads 3..54 bits. */ -static BROTLI_INLINE BROTLI_BOOL DecodeLiteralBlockSwitchInternal(int safe, BrotliDecoderState *s) { - if (!DecodeBlockTypeAndLength(safe, s, 0)) { - return BROTLI_FALSE; +static BROTLI_INLINE BrotliDecoderErrorCode DecodeLiteralBlockSwitchInternal(int safe, BrotliDecoderState *s) { + BrotliDecoderErrorCode result = DecodeBlockTypeAndLength(safe, s, 0); + if (result != BROTLI_DECODER_SUCCESS) { + return result; } PrepareLiteralDecoding(s); - return BROTLI_TRUE; + return BROTLI_DECODER_SUCCESS; } -static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState *s) { - DecodeLiteralBlockSwitchInternal(0, s); +static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeLiteralBlockSwitch(BrotliDecoderState *s) { + return DecodeLiteralBlockSwitchInternal(0, s); } -static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch(BrotliDecoderState *s) { +static BROTLI_NOINLINE BrotliDecoderErrorCode SafeDecodeLiteralBlockSwitch(BrotliDecoderState *s) { return DecodeLiteralBlockSwitchInternal(1, s); } /* Block switch for insert/copy length. Reads 3..54 bits. */ -static BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal(int safe, BrotliDecoderState *s) { - if (!DecodeBlockTypeAndLength(safe, s, 1)) { - return BROTLI_FALSE; +static BROTLI_INLINE BrotliDecoderErrorCode DecodeCommandBlockSwitchInternal(int safe, BrotliDecoderState *s) { + BrotliDecoderErrorCode result = DecodeBlockTypeAndLength(safe, s, 1); + if (result != BROTLI_DECODER_SUCCESS) { + return result; } s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]]; - return BROTLI_TRUE; + return BROTLI_DECODER_SUCCESS; } -static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState *s) { - DecodeCommandBlockSwitchInternal(0, s); +static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeCommandBlockSwitch(BrotliDecoderState *s) { + return DecodeCommandBlockSwitchInternal(0, s); } -static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch(BrotliDecoderState *s) { +static BROTLI_NOINLINE BrotliDecoderErrorCode SafeDecodeCommandBlockSwitch(BrotliDecoderState *s) { return DecodeCommandBlockSwitchInternal(1, s); } /* Block switch for distance codes. Reads 3..54 bits. */ -static BROTLI_INLINE BROTLI_BOOL DecodeDistanceBlockSwitchInternal(int safe, BrotliDecoderState *s) { - if (!DecodeBlockTypeAndLength(safe, s, 2)) { - return BROTLI_FALSE; +static BROTLI_INLINE BrotliDecoderErrorCode DecodeDistanceBlockSwitchInternal(int safe, BrotliDecoderState *s) { + BrotliDecoderErrorCode result = DecodeBlockTypeAndLength(safe, s, 2); + if (result != BROTLI_DECODER_SUCCESS) { + return result; } s->dist_context_map_slice = s->dist_context_map + (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS); s->dist_htree_index = s->dist_context_map_slice[s->distance_context]; - return BROTLI_TRUE; + return BROTLI_DECODER_SUCCESS; } -static void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliDecoderState *s) { - DecodeDistanceBlockSwitchInternal(0, s); +static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeDistanceBlockSwitch(BrotliDecoderState *s) { + return DecodeDistanceBlockSwitchInternal(0, s); } -static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch(BrotliDecoderState *s) { +static BROTLI_NOINLINE BrotliDecoderErrorCode SafeDecodeDistanceBlockSwitch(BrotliDecoderState *s) { return DecodeDistanceBlockSwitchInternal(1, s); } @@ -1811,6 +1815,9 @@ static BROTLI_INLINE BROTLI_BOOL CheckInputAmount(int safe, BrotliBitReader *con return BrotliCheckInputAmount(br); } +/* NB: METHOD should return BROTLI_FALSE only in case there is not enough input; + in case of "unsafe" execution, when input is guaranteed to be sufficient, + result is ignored. */ #define BROTLI_SAFE(METHOD) \ { \ if (safe) { \ @@ -1823,6 +1830,22 @@ static BROTLI_INLINE BROTLI_BOOL CheckInputAmount(int safe, BrotliBitReader *con } \ } +/* NB: METHOD should return BROTLI_DECODER_SUCCESS, BROTLI_DECODER_ERROR_*, or + BROTLI_DECODER_NEEDS_MORE_INPUT; the later two break the processing. */ +#define BROTLI_SAFE_WITH_STATUS(METHOD) \ + { \ + BrotliDecoderErrorCode status; \ + if (safe) { \ + status = Safe##METHOD; \ + } else { \ + status = METHOD; \ + } \ + if (status != BROTLI_DECODER_SUCCESS) { \ + result = status; \ + goto saveStateAndReturn; \ + } \ + } + static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(int safe, BrotliDecoderState *s) { int pos = s->pos; int i = s->loop_counter; @@ -1861,7 +1884,7 @@ static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(int safe, Br goto saveStateAndReturn; } if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)) { - BROTLI_SAFE(DecodeCommandBlockSwitch(s)); + BROTLI_SAFE_WITH_STATUS(DecodeCommandBlockSwitch(s)); goto CommandBegin; } /* Read the insert/copy length in the command. */ @@ -1967,7 +1990,7 @@ static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(int safe, Br } else { /* Read distance code in the command, unless it was implicitly zero. */ if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)) { - BROTLI_SAFE(DecodeDistanceBlockSwitch(s)); + BROTLI_SAFE_WITH_STATUS(DecodeDistanceBlockSwitch(s)); } BROTLI_SAFE(ReadDistance(s, br)); } @@ -2147,7 +2170,7 @@ CommandPostWrapCopy: { } NextLiteralBlock: - BROTLI_SAFE(DecodeLiteralBlockSwitch(s)); + BROTLI_SAFE_WITH_STATUS(DecodeLiteralBlockSwitch(s)); goto CommandInner; saveStateAndReturn: @@ -2360,6 +2383,7 @@ BrotliDecoderResult BrotliDecoderDecompressStream(BrotliDecoderState *s, size_t if (result != BROTLI_DECODER_SUCCESS) { break; } + BROTLI_DCHECK(s->meta_block_remaining_len <= (int)BROTLI_BLOCK_SIZE_CAP); BROTLI_LOG_UINT(s->is_last_metablock); BROTLI_LOG_UINT(s->meta_block_remaining_len); BROTLI_LOG_UINT(s->is_metadata); diff --git a/src/duckdb/third_party/brotli/include/brotli/decode.h b/src/duckdb/third_party/brotli/include/brotli/decode.h index 2288009cf..cf59ce076 100644 --- a/src/duckdb/third_party/brotli/include/brotli/decode.h +++ b/src/duckdb/third_party/brotli/include/brotli/decode.h @@ -83,9 +83,7 @@ typedef enum { BROTLI_ERROR_CODE(_ERROR_FORMAT_, PADDING_1, -14) SEPARATOR \ BROTLI_ERROR_CODE(_ERROR_FORMAT_, PADDING_2, -15) SEPARATOR \ BROTLI_ERROR_CODE(_ERROR_FORMAT_, DISTANCE, -16) SEPARATOR \ - \ - /* -17 code is reserved */ \ - \ + BROTLI_ERROR_CODE(_ERROR_FORMAT_, BLOCK_SWITCH, -17) SEPARATOR \ BROTLI_ERROR_CODE(_ERROR_, COMPOUND_DICTIONARY, -18) SEPARATOR \ BROTLI_ERROR_CODE(_ERROR_, DICTIONARY_NOT_SET, -19) SEPARATOR \ BROTLI_ERROR_CODE(_ERROR_, INVALID_ARGUMENTS, -20) SEPARATOR \ diff --git a/src/duckdb/third_party/fmt/include/fmt/format-inl.h b/src/duckdb/third_party/fmt/include/fmt/format-inl.h index b92c914b5..2dc5b6c4c 100644 --- a/src/duckdb/third_party/fmt/include/fmt/format-inl.h +++ b/src/duckdb/third_party/fmt/include/fmt/format-inl.h @@ -922,7 +922,7 @@ void fallback_format(Double d, buffer& buf, int& exp10) { upper = &upper_store; } denominator.assign_pow10(exp10); - denominator <<= 1; + denominator <<= shift; } else if (exp10 < 0) { numerator.assign_pow10(-exp10); lower.assign(numerator); diff --git a/src/duckdb/third_party/jemalloc/src/jemalloc.c b/src/duckdb/third_party/jemalloc/src/jemalloc.c index 01d328864..7953c5a36 100644 --- a/src/duckdb/third_party/jemalloc/src/jemalloc.c +++ b/src/duckdb/third_party/jemalloc/src/jemalloc.c @@ -4285,12 +4285,13 @@ jemalloc_constructor(void) { if (bgt_count == 0) { bgt_count = 1; } - // decay is in ms + // decay is in ms. muzzy_decay_ms is 0 (jemalloc's default), so purged pages go back with MADV_DONTNEED, never + // MADV_FREE: x86 kernels without f7491d7c81db discard MADV_FREE'd huge pages written again (CVE-2026-97945) unsigned long long decay = DUCKDB_JEMALLOC_DECAY * 1000; #ifdef DEBUG - snprintf(JE_MALLOC_CONF_BUFFER, JE_MALLOC_CONF_BUFFER_SIZE, "junk:true,oversize_threshold:268435456,dirty_decay_ms:%llu,muzzy_decay_ms:%llu,narenas:%llu,max_background_threads:%llu", decay, decay, narenas, bgt_count); + snprintf(JE_MALLOC_CONF_BUFFER, JE_MALLOC_CONF_BUFFER_SIZE, "junk:true,oversize_threshold:268435456,dirty_decay_ms:%llu,muzzy_decay_ms:0,narenas:%llu,max_background_threads:%llu", decay, narenas, bgt_count); #else - snprintf(JE_MALLOC_CONF_BUFFER, JE_MALLOC_CONF_BUFFER_SIZE, "oversize_threshold:268435456,dirty_decay_ms:%llu,muzzy_decay_ms:%llu,narenas:%llu,max_background_threads:%llu", decay, decay, narenas, bgt_count); + snprintf(JE_MALLOC_CONF_BUFFER, JE_MALLOC_CONF_BUFFER_SIZE, "oversize_threshold:268435456,dirty_decay_ms:%llu,muzzy_decay_ms:0,narenas:%llu,max_background_threads:%llu", decay, narenas, bgt_count); #endif je_malloc_conf = JE_MALLOC_CONF_BUFFER; malloc_init(); diff --git a/src/duckdb/third_party/jemalloc/src/pages.c b/src/duckdb/third_party/jemalloc/src/pages.c index 1657fa811..2167e1f31 100644 --- a/src/duckdb/third_party/jemalloc/src/pages.c +++ b/src/duckdb/third_party/jemalloc/src/pages.c @@ -79,6 +79,8 @@ static int madvise_MADV_DONTNEED_zeroes_pages(void) if (opt_abort) { abort(); } + /* DuckDB treats MADV_DONTNEED as faulty without memory to probe it. */ + return 0; } memset(addr, 'A', size); diff --git a/src/duckdb/third_party/miniz/miniz_wrapper.hpp b/src/duckdb/third_party/miniz/miniz_wrapper.hpp index 0c02a16a4..ab9713aaa 100644 --- a/src/duckdb/third_party/miniz/miniz_wrapper.hpp +++ b/src/duckdb/third_party/miniz/miniz_wrapper.hpp @@ -49,7 +49,7 @@ struct MiniZStream { FormatException(error_msg + std::string(": ") + (err ? err : "Unknown error code")); } - void Decompress(const char *compressed_data, size_t compressed_size, char *out_data, size_t out_size) { + size_t Decompress(const char *compressed_data, size_t compressed_size, char *out_data, size_t out_size) { type = MiniZStreamType::MINIZ_TYPE_INFLATE; // Loop over blocks @@ -96,6 +96,7 @@ struct MiniZStream { ResetStreamInternal(); } + return out_size; } static size_t MaxCompressedLength(size_t input_size) { diff --git a/src/duckdb/third_party/utf8proc/utf8proc.cpp b/src/duckdb/third_party/utf8proc/utf8proc.cpp index bfea42744..917b64cc8 100644 --- a/src/duckdb/third_party/utf8proc/utf8proc.cpp +++ b/src/duckdb/third_party/utf8proc/utf8proc.cpp @@ -673,7 +673,7 @@ UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_normalize_utf32(utf8proc_int32_t *b (hangul_sindex % UTF8PROC_HANGUL_TCOUNT) == 0) { utf8proc_int32_t hangul_tindex; hangul_tindex = current_char - UTF8PROC_HANGUL_TBASE; - if (hangul_tindex >= 0 && hangul_tindex < UTF8PROC_HANGUL_TCOUNT) { + if (hangul_tindex > 0 && hangul_tindex < UTF8PROC_HANGUL_TCOUNT) { *starter += hangul_tindex; starter_property = NULL; continue; diff --git a/src/duckdb/ub_src_common.cpp b/src/duckdb/ub_src_common.cpp index df2ce731c..433104204 100644 --- a/src/duckdb/ub_src_common.cpp +++ b/src/duckdb/ub_src_common.cpp @@ -82,6 +82,8 @@ #include "src/common/process_util.cpp" +#include "src/common/query_context.cpp" + #include "src/common/radix_partitioning.cpp" #include "src/common/random_engine.cpp" diff --git a/src/duckdb/ub_src_main.cpp b/src/duckdb/ub_src_main.cpp index 0c1e275e1..cf519f2f7 100644 --- a/src/duckdb/ub_src_main.cpp +++ b/src/duckdb/ub_src_main.cpp @@ -22,6 +22,8 @@ #include "src/main/connection_manager.cpp" +#include "src/main/context.cpp" + #include "src/main/database.cpp" #include "src/main/database_file_path_manager.cpp" diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index da1b256be..1167bd01a 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -32,6 +32,8 @@ #include "src/optimizer/cte_join_filter_pusher.cpp" +#include "src/optimizer/cte_runtime_filter_pushdown.cpp" + #include "src/optimizer/deliminator.cpp" #include "src/optimizer/disjunctive_join_rewriter.cpp" @@ -100,8 +102,12 @@ #include "src/optimizer/sampling_pushdown.cpp" +#include "src/optimizer/scalar_aggregate_merger.cpp" + #include "src/optimizer/scalar_fn_pushdown.cpp" +#include "src/optimizer/self_join_aggregate.cpp" + #include "src/optimizer/statistics_propagator.cpp" #include "src/optimizer/topn_optimizer.cpp" diff --git a/src/duckdb/ub_src_optimizer_rule.cpp b/src/duckdb/ub_src_optimizer_rule.cpp index 14b1de1b8..d3b9a32b0 100644 --- a/src/duckdb/ub_src_optimizer_rule.cpp +++ b/src/duckdb/ub_src_optimizer_rule.cpp @@ -44,6 +44,10 @@ #include "src/optimizer/rule/not_conjunction_simplification.cpp" +#include "src/optimizer/rule/not_constant_or_null_simplification.cpp" + +#include "src/optimizer/rule/or_range_merge.cpp" + #include "src/optimizer/rule/ordered_aggregate_optimizer.cpp" #include "src/optimizer/rule/predicate_factoring.cpp" diff --git a/src/duckdb/ub_src_parser_peg_transformer.cpp b/src/duckdb/ub_src_parser_peg_transformer.cpp index cb32cf39d..2bc4d9d02 100644 --- a/src/duckdb/ub_src_parser_peg_transformer.cpp +++ b/src/duckdb/ub_src_parser_peg_transformer.cpp @@ -60,6 +60,8 @@ #include "src/parser/peg/transformer/transform_external_resource_source.cpp" +#include "src/parser/peg/transformer/transform_frame_plan.cpp" + #include "src/parser/peg/transformer/transform_generated_trampoline.cpp" #include "src/parser/peg/transformer/transform_generic_copy_option.cpp" diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index c40cb29bb..32db30402 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -87,7 +87,7 @@ jobject _duckdb_jdbc_connect(JNIEnv *env, jclass, jobject conn_ref_buf) { auto conn_ref = get_connection_ref(env, conn_ref_buf); auto config = ClientConfig::GetConfig(*conn_ref->connection->context); auto conn = new ConnectionHolder(conn_ref->db); - conn->connection->context->config = config; + ClientConfig::GetConfig(*conn->connection->context) = config; return env->NewDirectByteBuffer(conn, 0); } diff --git a/src/jni/types.cpp b/src/jni/types.cpp index 0d71e2ad1..2bcbb8668 100644 --- a/src/jni/types.cpp +++ b/src/jni/types.cpp @@ -10,8 +10,8 @@ std::string type_to_jduckdb_type(duckdb::LogicalType logical_type) { switch (logical_type.id()) { case duckdb::LogicalTypeId::DECIMAL: { - uint8_t width = 0; - uint8_t scale = 0; + uint32_t width = 0; + uint32_t scale = 0; logical_type.GetDecimalProperties(width, scale); std::string width_scale = std::to_string(width) + std::string(";") + std::to_string(scale);