diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index 1d150ff19..bdae27032 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -1,13 +1,20 @@ #include "core_functions/aggregate/algebraic_functions.hpp" #include "core_functions/aggregate/sum_helpers.hpp" +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" +#include "duckdb/common/types/string_heap.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/time.hpp" +#include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/likely.hpp" #include "duckdb/function/function_set.hpp" #include "duckdb/planner/expression.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include + namespace duckdb { namespace { @@ -55,19 +62,21 @@ struct KahanAvgState { }; struct AverageDecimalBindData : public FunctionData { - explicit AverageDecimalBindData(double scale) : scale(scale) { + AverageDecimalBindData(double scale, uint32_t decimal_scale) : scale(scale), decimal_scale(decimal_scale) { } + //! 10^decimal_scale, the divisor of the unscaled sum double scale; + uint32_t decimal_scale; public: unique_ptr Copy() const override { - return make_uniq(scale); + return make_uniq(scale, decimal_scale); }; bool Equals(const FunctionData &other_p) const override { auto &other = other_p.Cast(); - return scale == other.scale; + return scale == other.scale && decimal_scale == other.decimal_scale; } }; @@ -496,6 +505,193 @@ struct TimeTZAverageOperation : public BaseSumOperation(i))); + } + if (magnitude <= uhugeint_t(NumericLimits::Maximum())) { + auto sum = hugeint_t(magnitude.upper, magnitude.lower); + return Hugeint::Cast(value.is_negative ? -sum : sum); + } + } + long double result = 0; + for (idx_t i = start; i < value.size; i++) { + result = result * 256 + value.GetAbsoluteByte(NumericCast(i)); + } + return value.is_negative ? -result : result; +} + +//! The digits a quotient carries beyond the 17 significant digits of a DOUBLE, so that the quotient and a sticky +//! digit for a nonzero remainder round to the DOUBLE nearest to the exact average +static constexpr idx_t AVERAGE_GUARD_DIGITS = 40; + +//! The average as the DOUBLE nearest to the exact quotient: the sum is scaled up by enough digits for the quotient to +//! carry the guard digits beyond those of the count, a nonzero remainder (which lies strictly between two quotients) +//! is kept as a trailing nonzero digit, and the decimal text is parsed once, so the result is rounded once +static double BignumExactAverage(const BignumIntermediate &sum, uint64_t count, uint32_t scale) { + StringHeap heap; + BignumArithmeticState state; + const idx_t extra_digits = AVERAGE_GUARD_DIGITS + std::to_string(count).size(); + const string power_blob = DecimalHelper::PowerOfTen(extra_digits); + const bignum_t power_value {string_t(power_blob)}; + const BignumIntermediate power(power_value); + const bignum_t scaled_value {BignumIntermediate::Multiply(heap, state, sum, power)}; + const BignumIntermediate scaled_sum(scaled_value); + const string count_blob = DecimalHelper::FromInteger(uhugeint_t(count)); + const bignum_t count_value {string_t(count_blob)}; + const BignumIntermediate divisor(count_value); + string_t quotient; + string_t remainder; + if (!BignumIntermediate::TryDivMod(heap, state, scaled_sum, divisor, quotient, remainder)) { + throw InternalException("avg: division of the wide decimal sum by the count failed"); + } + auto text = Bignum::BignumToVarchar(bignum_t(quotient)); + text += DecimalHelper::IsZero(bignum_t(remainder)) ? "0" : "1"; + text += "e-" + std::to_string(idx_t(scale) + extra_digits + 1); + double result; + if (!TryCast::Operation(string_t(text), result, false)) { + throw InternalException("avg: could not convert the wide decimal average '%s' to a DOUBLE", text); + } + return result; +} + +struct BignumAverageOperation { + template + static void Initialize(STATE &state) { + state.count = 0; + state.value = BignumIntermediate(); + } + + template + static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { + if (state.count == 0) { + state.value.Initialize(unary_input.input.allocator); + } + state.count++; + BignumIntermediate rhs(input); + state.value.AddInPlace(unary_input.input.allocator, rhs); + } + + template + static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input, + idx_t count) { + for (idx_t i = 0; i < count; i++) { + Operation(state, input, unary_input); + } + } + + template + static void Combine(const STATE &source, STATE &target, AggregateInputData &input) { + if (source.count == 0) { + return; + } + if (target.count == 0) { + target.value.Initialize(input.allocator); + } + target.count += source.count; + target.value.AddInPlace(input.allocator, source.value); + } + + template + static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) { + if (state.count == 0) { + finalize_data.ReturnNull(); + return; + } + long double divident = GetAverageDivident(state.count, finalize_data.input.bind_data); + const auto sum = BignumSumToLongDouble(state.value); + if (std::isfinite(sum) && std::isfinite(divident)) { + target = sum / divident; + return; + } + // beyond the range of a long double (a sum or a scale factor near the DOUBLE range) the exact sum is divided + // by the count instead, so that the average stays finite and a subnormal average keeps its value + auto &bind_data = finalize_data.input.bind_data->Cast(); + target = BignumExactAverage(state.value, state.count, bind_data.decimal_scale); + } + + static bool IgnoreNull() { + return true; + } +}; + +//! The states are exported as STRUCT(count UBIGINT, value BIGNUM), the value is NULL for an empty state +static LogicalType BignumAvgStateType() { + return LogicalType::STRUCT({{"count", LogicalType::UBIGINT}, {"value", LogicalType::BIGNUM}}); +} + +AggregateStateLayout BignumAvgStateLayout(AggregateLayoutInput &input) { + return AggregateStateLayout(BignumAvgStateType(), AlignValue(sizeof(BignumAvgState))); +} + +void BignumAvgExportState(Vector &state_vector, AggregateFinalizeInputData &, Vector &result, idx_t count, + idx_t offset) { + auto states = state_vector.Values(); + auto &entries = StructVector::GetEntries(result); + auto count_data = FlatVector::GetDataMutable(entries[0]); + auto value_data = FlatVector::GetDataMutable(entries[1]); + auto &value_validity = FlatVector::ValidityMutable(entries[1]); + for (idx_t i = 0; i < count; i++) { + auto &state = *states[i].GetValue(); + count_data[offset + i] = state.count; + if (state.count == 0) { + value_validity.SetInvalid(offset + i); + continue; + } + value_data[offset + i] = BignumAggregates::WriteBignum(state.value, entries[1]); + } +} + +void BignumAvgImportState(AggregateImportInputData &input) { + auto &input_vec = input.input_vec; + auto count = input_vec.size(); + UnifiedVectorFormat struct_format; + input_vec.ToUnifiedFormat(struct_format); + auto &entries = StructVector::GetEntries(input_vec); + UnifiedVectorFormat count_format; + UnifiedVectorFormat value_format; + entries[0].ToUnifiedFormat(count_format); + entries[1].ToUnifiedFormat(value_format); + auto count_data = count_format.GetData(count_format); + auto value_data = value_format.GetData(value_format); + for (idx_t i = 0; i < count; i++) { + auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); + BignumAverageOperation::Initialize(state); + const auto struct_idx = struct_format.sel->get_index(i); + const auto count_idx = count_format.sel->get_index(i); + const auto value_idx = value_format.sel->get_index(i); + if (!struct_format.validity.RowIsValid(struct_idx) || !count_format.validity.RowIsValid(count_idx) || + count_data[count_idx] == 0) { + // an empty state, e.g. to_aggregate_state(NULL, ...) + continue; + } + if (!value_format.validity.RowIsValid(value_idx)) { + throw InvalidInputException("Invalid avg state - the value cannot be NULL when the count is not 0"); + } + state.count = count_data[count_idx]; + state.value = BignumAggregates::ImportBignum(value_data[value_idx], input.allocator); + } +} + +AggregateFunction GetBignumAverageAggregate() { + auto function = AggregateFunction::UnaryAggregate( + LogicalTypeId::DECIMAL, LogicalType::DOUBLE); + function.SetStateExportCallbacks(BignumAvgStateLayout, BignumAvgExportState, BignumAvgImportState); + return function; +} + static AggregateFunction NameXParameter(AggregateFunction fun) { fun.GetSignature().GetParameter(0).SetName("x"); return fun; @@ -541,21 +737,39 @@ AggregateFunction GetAverageAggregate(PhysicalType type) { function.SetFallible(); // interval addition throws on overflow of any field return NameXParameter(std::move(function)); } + case PhysicalType::DOUBLE: { + return NameXParameter( + AggregateFunction::UnaryAggregate, double, double, NumericAverageOperation>( + LogicalType::DOUBLE, LogicalType::DOUBLE)); + } default: throw InternalException("Unimplemented average aggregate"); } } +//! 10^scale as a double, through the hugeint table where it reaches so that both decimal tiers divide identically +static double DecimalScaleFactor(uint32_t scale) { + if (scale < Hugeint::CACHED_POWERS_OF_TEN) { + return Hugeint::Cast(Hugeint::POWERS_OF_TEN[scale]); + } + return std::pow(10.0, static_cast(scale)); +} + unique_ptr BindDecimalAvg(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); auto decimal_type = BindDecimalArgument(input.GetClientContext(), arguments[0], "avg"); - function.ReplaceImplementation(GetAverageAggregate(decimal_type.InternalType())); + if (decimal_type.InternalType() == PhysicalType::VARCHAR) { + // the bignum_t tier of decimals sums its BIGNUM blobs + function.ReplaceImplementation(GetBignumAverageAggregate()); + } else { + function.ReplaceImplementation(GetAverageAggregate(decimal_type.InternalType())); + } function.SetName("avg"); function.GetArguments()[0] = decimal_type; function.SetReturnType(LogicalType::DOUBLE); - return make_uniq( - Hugeint::Cast(Hugeint::POWERS_OF_TEN[DecimalType::GetScale(decimal_type)])); + const auto scale = DecimalType::GetScale(decimal_type); + return make_uniq(DecimalScaleFactor(scale), scale); } AggregateFunction GetTimestampAverage() { @@ -602,10 +816,7 @@ AggregateFunctionSet AvgFun::GetFunctions() { avg.AddFunction(GetAverageAggregate(PhysicalType::INT64)); avg.AddFunction(GetAverageAggregate(PhysicalType::INT128)); avg.AddFunction(GetAverageAggregate(PhysicalType::INTERVAL)); - auto numeric_avg = AggregateFunction::UnaryAggregate, double, double, NumericAverageOperation>( - LogicalType::DOUBLE, LogicalType::DOUBLE); - numeric_avg.GetSignature().GetParameter(0).SetName("x"); - avg.AddFunction(numeric_avg); + avg.AddFunction(GetAverageAggregate(PhysicalType::DOUBLE)); avg.AddFunction(GetTimestampAverage()); for (auto &type : {LogicalType::TIMESTAMP_S, LogicalType::TIMESTAMP_MS, LogicalType::DATE}) { diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp index 61599af39..d1a4454dd 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp @@ -541,6 +541,9 @@ AggregateFunction GetDecimalArgMinMaxFunction(const LogicalType &by_type, const return GetArgMinMaxFunctionBy(by_type, type, null_handling); case PhysicalType::INT64: return GetArgMinMaxFunctionBy(by_type, type, null_handling); + case PhysicalType::VARCHAR: + // wide decimals are BIGNUM blobs + return GetArgMinMaxFunctionBy(by_type, type, null_handling); default: return GetArgMinMaxFunctionBy(by_type, type, null_handling); } diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index 1d981f8d5..c7914a941 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/bignum.hpp" #include "duckdb/common/bignum_limbs.hpp" #include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" @@ -291,25 +292,26 @@ struct DecimalSumOperation : public OP { if (!state.is_set) { return; } - const auto &max_value = Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_DECIMAL]; + const auto &max_value = Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_INT128]; if (target >= max_value || target <= -max_value) { throw OutOfRangeException("Overflow in SUM of DECIMAL: the result does not fit in DECIMAL(%d)", - Decimal::MAX_WIDTH_DECIMAL); + Decimal::MAX_WIDTH_INT128); } } }; //! Binds the regular sum that sum_no_overflow is a specialized implementation of -pair> BindLogicalSum(ClientContext &context, +pair> BindLogicalSum(FunctionBinder &binder, vector> &arguments) { + auto &context = binder.context; auto &entry = Catalog::GetEntry( context, QualifiedName(Identifier::SystemCatalog(), Identifier::DefaultSchema(), Identifier("sum"))); vector>> keyword_args; - auto selection = FunctionBinder::SelectFunction(context, entry.functions, {arguments, keyword_args}); + auto selection = FunctionBinder::SelectFunction(context, entry.functions, {arguments, keyword_args}, false, + binder.FixedDecimalWidthLimit()); if (!selection.IsSuccess()) { selection.GetError().Throw(); } - FunctionBinder binder(context); return binder.ResolveAggregateFunction(selection.GetBinding(), arguments, keyword_args); } @@ -330,7 +332,10 @@ unique_ptr SumNoOverflowDeserialize(Deserializer &deserializer, Bo for (auto &child : children) { arguments.push_back(child.get().Copy()); } - auto logical = BindLogicalSum(context, arguments); + // the sum is rebound within the decimal width it was bound in + const auto decimal_width_limit = DecimalWidthLimit::FromReturnType(return_type); + FunctionBinder binder(context, &decimal_width_limit); + auto logical = BindLogicalSum(binder, arguments); if (logical.second || (!return_type.IsAggregateState() && logical.first.GetReturnType() != return_type)) { throw SerializationException("Cannot reconstruct the logical sum signature"); } @@ -390,7 +395,8 @@ unique_ptr SumNoOverflowBind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); const auto parameter_type = function.GetArguments()[0]; - auto logical = BindLogicalSum(input.GetClientContext(), arguments); + auto binder = input.NestedFunctionBinder(); + auto logical = BindLogicalSum(binder, arguments); if (parameter_type.id() != LogicalTypeId::DECIMAL) { logical.first.ReplaceImplementation(GetSumAggregateNoOverflow(parameter_type.InternalType())); // bound by name there is no statistics proof that the int64 accumulator cannot overflow @@ -487,6 +493,8 @@ AggregateFunction GetSumAggregate(PhysicalType type) { } } +AggregateFunction GetWideDecimalSumAggregate(); + template AggregateFunction GetDecimalSumAggregate(const LogicalType &input_type) { auto function = @@ -517,14 +525,29 @@ AggregateFunction GetDecimalSumAggregate(PhysicalType type) { } } +//! The digits a wide decimal sum adds to the width of its input, enough for the sum of 2^64 values +static constexpr uint32_t WIDE_SUM_EXTRA_DIGITS = 20; + unique_ptr BindDecimalSum(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); auto decimal_type = BindDecimalArgument(input.GetClientContext(), arguments[0], "sum"); + if (decimal_type.InternalType() == PhysicalType::VARCHAR) { + // wide decimals sum their BIGNUM blobs exactly: 20 more digits hold the sum of any number of rows (below 2^64) + const auto input_width = DecimalType::GetWidth(decimal_type); + const auto result_width = input.GetDecimalWidthLimit().CheckedWidth(idx_t(input_width) + WIDE_SUM_EXTRA_DIGITS, + input_width, "The sum"); + function.ReplaceImplementation(GetWideDecimalSumAggregate()); + function.SetName("sum"); + function.GetArguments()[0] = decimal_type; + function.SetReturnType(LogicalType::DECIMAL(result_width, DecimalType::GetScale(decimal_type))); + function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); + return nullptr; + } function.ReplaceImplementation(GetDecimalSumAggregate(decimal_type.InternalType())); function.SetName("sum"); function.GetArguments()[0] = decimal_type; - function.SetReturnType(LogicalType::DECIMAL(Decimal::MAX_WIDTH_DECIMAL, DecimalType::GetScale(decimal_type))); + function.SetReturnType(LogicalType::DECIMAL(Decimal::MAX_WIDTH_INT128, DecimalType::GetScale(decimal_type))); function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); return nullptr; } @@ -666,6 +689,78 @@ struct BignumOperation { } }; +//! The BIGNUM sum states are exported as the BIGNUM blob of their sum, NULL for an empty state +AggregateStateLayout BignumSumStateLayout(AggregateLayoutInput &input) { + return AggregateStateLayout(LogicalType::BIGNUM, AlignValue(sizeof(BignumState))); +} + +void BignumSumExportState(Vector &state_vector, AggregateFinalizeInputData &, Vector &result, idx_t count, + idx_t offset) { + auto states = state_vector.Values(); + auto result_data = FlatVector::GetDataMutable(result); + auto &result_validity = FlatVector::ValidityMutable(result); + for (idx_t i = 0; i < count; i++) { + auto &state = *states[i].GetValue(); + if (!state.is_set) { + result_validity.SetInvalid(offset + i); + continue; + } + if (state.is_wide) { + result_data[offset + i] = BignumAggregates::WriteBignum(state.wide, result); + } else { + char blob[2 * BignumLimb::BYTES + Bignum::BIGNUM_HEADER_SIZE]; + const auto size = BignumOperation::EncodeSmall(state.small, blob); + result_data[offset + i] = StringVector::AddStringOrBlob(result, blob, size); + } + } +} + +void BignumSumImportState(AggregateImportInputData &input) { + auto entries = input.input_vec.Values(); + for (idx_t i = 0; i < input.input_vec.size(); i++) { + auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); + const auto entry = entries[i]; + state.is_set = entry.IsValid(); + state.is_wide = false; + state.small = 0; + if (!state.is_set) { + continue; + } + const bignum_t value(entry.GetValue()); + if (BignumOperation::TryGetSmall(BignumIntermediate(value), state.small)) { + continue; + } + state.is_wide = true; + state.wide = BignumAggregates::ImportBignum(value.data, input.allocator); + } +} + +//! Sums wide decimals as BIGNUMs, the result must still fit the width of the result decimal +struct WideDecimalSumOperation : public BignumOperation { + template + static void Finalize(STATE &state, TARGET_TYPE &target, AggregateFinalizeData &finalize_data) { + BignumOperation::Finalize(state, target, finalize_data); + if (!state.is_set) { + return; + } + // the result width holds the sum of 2^64 rows, but an imported state can carry any value + const auto &result_type = finalize_data.result.GetType(); + if (!DecimalHelper::FitsWidth(target, DecimalType::GetWidth(result_type))) { + throw OutOfRangeException("Overflow in SUM of DECIMAL: the result does not fit in %s", + result_type.ToString()); + } + } +}; + +AggregateFunction GetWideDecimalSumAggregate() { + auto function = AggregateFunction::UnaryAggregate( + LogicalTypeId::DECIMAL, LogicalTypeId::DECIMAL); + function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); + function.SetFallible(); // the finalize throws when the sum does not fit the width of the result + function.SetStateExportCallbacks(BignumSumStateLayout, BignumSumExportState, BignumSumImportState); + return function; +} + } // namespace AggregateFunctionSet SumFun::GetFunctions() { @@ -687,6 +782,7 @@ AggregateFunctionSet SumFun::GetFunctions() { auto sum_bignum = AggregateFunction::UnaryAggregate( LogicalType::BIGNUM, LogicalType::BIGNUM); sum_bignum.GetSignature().GetParameter(0).SetName("arg"); + sum_bignum.SetStateExportCallbacks(BignumSumStateLayout, BignumSumExportState, BignumSumImportState); sum.AddFunction(sum_bignum); return sum; } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp index 73b4aeaad..bd1389a2c 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/operator/add.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/vector_iterator.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -401,10 +402,18 @@ AggregateFunction GetApproximateQuantileAggregateFunction(const LogicalType &typ return AggregateFunction::UnaryAggregate( type, type); default: - throw InternalException("Unimplemented quantile aggregate"); + throw NotImplementedException("Unimplemented quantile aggregate"); } } +//! Wide decimals have no approximate quantile of their own, they are aggregated as DOUBLE +LogicalType ApproxQuantileInputType(const LogicalType &type) { + if (type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type))) { + return LogicalType::DOUBLE; + } + return type; +} + AggregateFunction GetApproximateQuantileDecimalAggregateFunction(const LogicalType &type) { switch (type.InternalType()) { case PhysicalType::INT8: @@ -412,10 +421,11 @@ AggregateFunction GetApproximateQuantileDecimalAggregateFunction(const LogicalTy case PhysicalType::INT32: case PhysicalType::INT64: case PhysicalType::INT128: + case PhysicalType::DOUBLE: // keep the DECIMAL type as the input and return type so that the width and scale survive the bind return GetApproximateQuantileAggregateFunction(type); default: - throw InternalException("Unimplemented quantile decimal aggregate"); + throw NotImplementedException("Unimplemented quantile decimal aggregate"); } } @@ -482,7 +492,7 @@ void ReplaceApproxQuantileImplementation(BoundAggregateFunction &function, const unique_ptr BindApproxQuantileDecimal(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto decimal_type = arguments[0]->GetReturnType(); + auto decimal_type = ApproxQuantileInputType(arguments[0]->GetReturnType()); auto bind_data = BindApproxQuantile(input); ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(decimal_type)); return bind_data; @@ -609,7 +619,7 @@ AggregateFunction ApproxQuantileDecimalListFunction(const LogicalType &type) { unique_ptr BindApproxQuantileDecimalList(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto decimal_type = arguments[0]->GetReturnType(); + auto decimal_type = ApproxQuantileInputType(arguments[0]->GetReturnType()); auto bind_data = BindApproxQuantile(input); ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(decimal_type)); return bind_data; diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp index c393067da..4db768ee4 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp @@ -1,4 +1,5 @@ #include "core_functions/aggregate/holistic_functions.hpp" +#include "duckdb/common/types/decimal.hpp" #include "core_functions/aggregate/quantile_state.hpp" #include "duckdb/common/enums/quantile_enum.hpp" #include "duckdb/common/operator/abs.hpp" @@ -47,6 +48,10 @@ inline Value QuantileAbs(const Value &v) { const auto &type = v.type(); switch (type.id()) { case LogicalTypeId::DECIMAL: { + if (type.InternalType() == PhysicalType::VARCHAR) { + // a wide decimal quantile has no HUGEINT representation, it is handled as DOUBLE + return Value::DOUBLE(QuantileAbs(v.GetValue())); + } const auto integral = IntegralValue::Get(v); const auto width = DecimalType::GetWidth(type); const auto scale = DecimalType::GetScale(type); @@ -716,6 +721,14 @@ static bool CanInterpolate(const LogicalType &type) { } } +//! Wide decimals have no exact interpolation, they are interpolated as DOUBLE +static LogicalType InterpolationType(const LogicalType &type) { + if (type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type))) { + return LogicalType::DOUBLE; + } + return type; +} + struct MedianFunction { static AggregateFunction GetAggregate(const LogicalType &type) { auto fun = CanInterpolate(type) ? GetContinuousQuantile(type) : GetDiscreteQuantile(type); @@ -736,7 +749,7 @@ struct MedianFunction { static unique_ptr Bind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - function.ReplaceImplementation(GetAggregate(arguments[0]->GetReturnType())); + function.ReplaceImplementation(GetAggregate(InterpolationType(arguments[0]->GetReturnType()))); return make_uniq(Value::DECIMAL(int16_t(5), 2, 1)); } }; @@ -845,9 +858,9 @@ struct ContinuousQuantileFunction { static unique_ptr Bind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto impl = - GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL ? arguments[0]->GetReturnType() - : function.GetArguments()[0]); + auto impl = GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL + ? InterpolationType(arguments[0]->GetReturnType()) + : function.GetArguments()[0]); function.ReplaceImplementation(impl); return BindQuantile(input); } @@ -879,9 +892,9 @@ struct ContinuousQuantileListFunction { static unique_ptr Bind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto impl = - GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL ? arguments[0]->GetReturnType() - : function.GetArguments()[0]); + auto impl = GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL + ? InterpolationType(arguments[0]->GetReturnType()) + : function.GetArguments()[0]); function.ReplaceImplementation(impl); return BindQuantile(input); } 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 b57809456..511dc3790 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/execution/expression_executor.hpp" @@ -370,8 +371,11 @@ static void SetDecimalImplementation(BoundAggregateFunction &function, const Log AggregateFunction::UnaryAggregate, hugeint_t, hugeint_t, ReservoirQuantileScalarOperation>(decimal_type, decimal_type)); break; + case PhysicalType::DOUBLE: + function.ReplaceImplementation(GetReservoirQuantileAggregateFunction(PhysicalType::DOUBLE)); + break; default: - throw InternalException("Invalid physical type for decimal reservoir quantile"); + throw NotImplementedException("Invalid physical type for decimal reservoir quantile"); } } for (idx_t i = function.GetArguments().size(); i < declared_arguments.size(); i++) { @@ -405,7 +409,11 @@ unique_ptr BindReservoirQuantileDecimal(BindAggregateFunctionInput auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); + // wide decimals have no reservoir quantile of their own, they are aggregated as DOUBLE auto decimal_type = arguments[0]->GetReturnType(); + if (Decimal::IsWide(DecimalType::GetWidth(decimal_type))) { + decimal_type = LogicalType::DOUBLE; + } bool is_list = arguments[1]->GetReturnType().id() == LogicalTypeId::LIST; auto bind_data_ptr = BindReservoirQuantile(input); diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp index 9617b8b4a..88752e395 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp @@ -20,6 +20,11 @@ struct QuantileValue { const auto &type = val.type(); switch (type.id()) { case LogicalTypeId::DECIMAL: { + if (type.InternalType() == PhysicalType::VARCHAR) { + // a wide decimal quantile has no HUGEINT representation, it is interpolated as DOUBLE + val = Value::DOUBLE(dbl); + break; + } integral = IntegralValue::Get(v); scaling = Hugeint::POWERS_OF_TEN[DecimalType::GetScale(type)]; break; diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp index 74394d750..a3671d203 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp @@ -369,6 +369,10 @@ inline Value QuantileNeg(const Value &v) { const auto &type = v.type(); switch (type.id()) { case LogicalTypeId::DECIMAL: { + if (type.InternalType() == PhysicalType::VARCHAR) { + // a wide decimal quantile has no HUGEINT representation, it is handled as DOUBLE + return Value::DOUBLE(QuantileNeg(v.GetValue())); + } const auto integral = IntegralValue::Get(v); const auto width = DecimalType::GetWidth(type); const auto scale = DecimalType::GetScale(type); 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 086fe7afb..58f5d5330 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 @@ -8,6 +8,8 @@ #pragma once +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/bignum.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/add.hpp" @@ -23,6 +25,48 @@ namespace duckdb { +//! The BIGNUM accumulators of aggregate states: exported as (trimmed) BIGNUM blobs, imported as copies in the arena +struct BignumAggregates { + //! Writes the value as a BIGNUM blob in the heap of the result vector + static string_t WriteBignum(const BignumIntermediate &value, Vector &result) { + // trimmed like BignumIntermediate::ToBignum, the intermediate itself is only read + auto start = value.GetStartDataPos(); + uint32_t size = value.size - start; + if (size == 0) { + // the value is all sign-extension bytes: keep one of them + start = 0; + size = 1; + } + auto blob = StringVector::EmptyString(result, Bignum::BIGNUM_HEADER_SIZE + size); + auto ptr = blob.GetDataWriteable(); + Bignum::SetHeader(ptr, size, value.is_negative); + memcpy(ptr + Bignum::BIGNUM_HEADER_SIZE, value.data + start, size); + blob.Finalize(); + return blob; + } + + //! Copies an imported BIGNUM blob into the arena and returns the intermediate over the copy + static BignumIntermediate ImportBignum(string_t blob, ArenaAllocator &allocator) { + const auto size = blob.GetSize(); + auto header = const_data_ptr_cast(blob.GetData()); + if (size < Bignum::BIGNUM_HEADER_SIZE + 1) { + throw InvalidInputException("Invalid BIGNUM state - the blob is shorter than a header and a byte"); + } + // the header holds the data size, inverted for negative values (see Bignum::SetHeader) + uint32_t data_size = (uint32_t(header[0]) << 16) | (uint32_t(header[1]) << 8) | uint32_t(header[2]); + if ((header[0] & 0x80) == 0) { + data_size = ~data_size; + } + data_size &= 0x7FFFFF; + if (size != data_size + Bignum::BIGNUM_HEADER_SIZE) { + throw InvalidInputException("Invalid BIGNUM state - the header does not match the size of the blob"); + } + auto ptr = allocator.Allocate(size); + memcpy(ptr, blob.GetData(), size); + return BignumIntermediate(ptr, size); + } +}; + struct AggregateStatisticsInput; struct SumAccumulatorBounds { diff --git a/src/duckdb/extension/core_functions/scalar/array/array_functions.cpp b/src/duckdb/extension/core_functions/scalar/array/array_functions.cpp index e794f2a29..94191b7d9 100644 --- a/src/duckdb/extension/core_functions/scalar/array/array_functions.cpp +++ b/src/duckdb/extension/core_functions/scalar/array/array_functions.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/vector/array_vector.hpp" +#include "duckdb/common/types/decimal.hpp" #include "core_functions/scalar/array_functions.hpp" #include "core_functions/array_kernels.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" @@ -41,7 +42,8 @@ static void ArrayGenericBinaryResolveTypes(ResolveScalarFunctionTypesInput &inpu // Resolve common type LogicalType common_type; - if (!LogicalType::TryGetMaxLogicalType(context, lhs_element_type, rhs_element_type, common_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, lhs_element_type, rhs_element_type, common_type, + input.GetDecimalWidthLimit())) { throw BinderException("%s: Cannot infer common element type (left = '%s', right = '%s')", SQLIdentifier(bound_function.GetName()), lhs_element_type.ToString(), rhs_element_type.ToString()); diff --git a/src/duckdb/extension/core_functions/scalar/array/array_value.cpp b/src/duckdb/extension/core_functions/scalar/array/array_value.cpp index 02db38ae3..4ce9db8b3 100644 --- a/src/duckdb/extension/core_functions/scalar/array/array_value.cpp +++ b/src/duckdb/extension/core_functions/scalar/array/array_value.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/array_vector.hpp" #include "core_functions/scalar/array_functions.hpp" #include "duckdb/function/scalar/nested_functions.hpp" @@ -56,7 +57,8 @@ void ArrayValueResolveTypes(ResolveScalarFunctionTypesInput &input) { // construct return type LogicalType child_type = arguments[0]->GetReturnType(); for (idx_t i = 1; i < arguments.size(); i++) { - child_type = LogicalType::MaxLogicalType(context, child_type, arguments[i]->GetReturnType()); + child_type = LogicalType::MaxLogicalType(context, child_type, arguments[i]->GetReturnType(), + input.GetDecimalWidthLimit()); } if (arguments.size() > ArrayType::MAX_ARRAY_SIZE) { diff --git a/src/duckdb/extension/core_functions/scalar/generic/least.cpp b/src/duckdb/extension/core_functions/scalar/generic/least.cpp index 00bc99451..cf211f449 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/least.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/least.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include "core_functions/scalar/generic_functions.hpp" #include "duckdb/common/operator/comparison_operators.hpp" #include "duckdb/common/smaller_binary.hpp" @@ -245,7 +246,8 @@ void LeastGreatestResolveTypes(ResolveScalarFunctionTypesInput &input) { LogicalType child_type = ExpressionBinder::GetExpressionReturnType(input.GetArgument(0)); for (idx_t i = 1; i < input.GetArgumentCount(); i++) { auto arg_type = ExpressionBinder::GetExpressionReturnType(input.GetArgument(i)); - if (!LogicalType::TryGetMaxLogicalType(context, child_type, arg_type, child_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, child_type, arg_type, child_type, + input.GetDecimalWidthLimit())) { throw BinderException(input.GetArgument(i).GetQueryLocation(), "Cannot combine types of %s and %s - an explicit cast is required", child_type.ToString(), arg_type.ToString()); diff --git a/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp b/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp index efa5070bb..6ca70cdb8 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/system_functions.cpp @@ -22,7 +22,7 @@ void CurrentQueryFunction(DataChunk &input, ExpressionState &state, Vector &resu // current_schema void CurrentSchemaFunction(DataChunk &input, ExpressionState &state, Vector &result) { - Value val(ClientData::Get(state.GetClientContext()).catalog_search_path->GetDefault().GetSchema()); + Value val(ClientData::Get(state.GetClientContext()).catalog_search_path->GetDefault().GetSchemaName()); result.Reference(val, count_t(input.size())); } @@ -67,7 +67,7 @@ unique_ptr CurrentSchemasBind(BindScalarFunctionInput &input) { auto &catalog_search_path = ClientData::Get(context).catalog_search_path; auto &search_path = implicit_schemas ? catalog_search_path->Get() : catalog_search_path->GetSetPaths(); std::transform(search_path.begin(), search_path.end(), std::back_inserter(schema_list), - [](const CatalogSearchEntry &s) -> Value { return Value(s.GetSchema()); }); + [](const CatalogSearchEntry &s) -> Value { return Value(s.GetSchemaName()); }); result_val = Value::LIST(LogicalType::VARCHAR, schema_list); } return make_uniq(std::move(result_val)); diff --git a/src/duckdb/extension/core_functions/scalar/generic/type_functions.cpp b/src/duckdb/extension/core_functions/scalar/generic/type_functions.cpp index 03fd01d40..55cdf6ab1 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/type_functions.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/type_functions.cpp @@ -3,6 +3,7 @@ #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/planner/binder.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/parser/expression/type_expression.hpp" #include "duckdb/execution/expression_executor.hpp" @@ -120,8 +121,10 @@ static unique_ptr BindMakeTypeFunctionExpression(FunctionBindExpress auto unbound_type = LogicalType::UNBOUND(make_uniq(std::move(qualified_name), std::move(type_args))); - // Bind the unbound type + // Bind the unbound type within the decimal width of the expression auto binder = Binder::CreateBinder(input.context); + const auto decimal_width_limit = input.GetDecimalWidthLimit(); + binder->SetDecimalWidthLimit(&decimal_width_limit); binder->BindLogicalType(unbound_type); return make_uniq(Value::TYPE(unbound_type)); } diff --git a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp index 1e6127b03..2750518a7 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp @@ -455,10 +455,10 @@ AggregateFunctionCatalogEntry &GetListAggregateEntry(ClientContext &context, con //! Binds the aggregate that is applied to the elements of the list template -unique_ptr BindListAggregate(ClientContext &context, LogicalType child_type, +unique_ptr BindListAggregate(FunctionBinder &function_binder, LogicalType child_type, const string &function_name, vector> extra_arguments) { - auto &func = GetListAggregateEntry(context, function_name); + auto &func = GetListAggregateEntry(function_binder.context, function_name); // the child expression refers to the list elements vector> children; @@ -467,7 +467,6 @@ unique_ptr BindListAggregate(ClientContext &context, L children.push_back(std::move(argument)); } - FunctionBinder function_binder(context); if (!IS_AGGR) { // the histogram is computed as an unordered map, which takes any type return function_binder.BindAggregateFunction(HistogramFun::GetHistogramUnorderedMap(child_type), @@ -511,8 +510,9 @@ void ListAggregatesResolveTypes(ResolveScalarFunctionTypesInput &input) { for (idx_t i = 2; i < input.GetArgumentCount(); i++) { extra_arguments.push_back(input.GetArgument(i).Copy()); } - auto bound_aggr_function = BindListAggregate(context, ListType::GetChildType(list_type), function_name, - std::move(extra_arguments)); + auto function_binder = input.NestedFunctionBinder(); + auto bound_aggr_function = BindListAggregate(function_binder, ListType::GetChildType(list_type), + function_name, std::move(extra_arguments)); bound_function.GetArguments()[0] = LogicalType::LIST(bound_aggr_function->Function().GetArguments()[0]); if (IS_AGGR) { @@ -546,8 +546,9 @@ unique_ptr ListAggregatesBind(BindScalarFunctionInput &input) { } auto function_name = IS_AGGR ? input.GetConstant(1).ToString() : string("histogram"); auto child_type = ListType::GetChildType(arguments[0]->GetReturnType()); + auto function_binder = input.NestedFunctionBinder(); auto bound_aggr_function = - BindListAggregate(context, child_type, function_name, std::move(extra_arguments)); + BindListAggregate(function_binder, child_type, function_name, std::move(extra_arguments)); // the extra arguments are passed to the aggregate as constant vectors, so they have to be constant - arguments // that the bind of the aggregate added after them are derived from the list elements diff --git a/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp b/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp index 5b3f0ed3f..2e8f9887e 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp @@ -1,5 +1,6 @@ #include "core_functions/scalar/list_functions.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/function/lambda_functions.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/context.hpp" @@ -203,9 +204,11 @@ bool ExecuteReduce(const idx_t loops, ReduceExecuteInfo &execute_info, LambdaFun } LogicalType ResolveReduceAccumulatorType(ClientContext &context, const LogicalType &initial_type, - const LogicalType &lambda_return_type) { + const LogicalType &lambda_return_type, + const DecimalWidthLimit &decimal_width_limit) { LogicalType max_logical_type; - if (LogicalType::TryGetMaxLogicalType(context, initial_type, lambda_return_type, max_logical_type)) { + if (LogicalType::TryGetMaxLogicalType(context, initial_type, lambda_return_type, max_logical_type, + decimal_width_limit)) { return max_logical_type; } throw BinderException("No common super type between initial value type %s and lambda return type %s", @@ -231,17 +234,20 @@ unique_ptr ListReduceBind(BindScalarFunctionInput &input) { bool has_initial = arguments.size() == 3; LogicalType accumulator_type; + const auto decimal_width_limit = input.GetDecimalWidthLimit(); if (has_initial) { const auto &initial_value_type = arguments[2]->GetReturnType(); auto &bound_lambda_expr = arguments[1]->Cast(); auto &lambda_return_type = bound_lambda_expr.LambdaExpr()->GetReturnType(); - accumulator_type = ResolveReduceAccumulatorType(context, initial_value_type, lambda_return_type); + accumulator_type = + ResolveReduceAccumulatorType(context, initial_value_type, lambda_return_type, decimal_width_limit); arguments[2] = BoundCastExpression::AddCastToType(context, std::move(arguments[2]), accumulator_type); } else { auto &bound_lambda_expr = arguments[1]->Cast(); auto list_child_type = LambdaFunctions::DetermineListChildType(arguments[0]->GetReturnType()); auto &lambda_return_type = bound_lambda_expr.LambdaExpr()->GetReturnType(); - if (!LogicalType::TryGetMaxLogicalType(context, list_child_type, lambda_return_type, accumulator_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, list_child_type, lambda_return_type, accumulator_type, + decimal_width_limit)) { throw BinderException("No common super type between list element type %s and lambda return type %s", list_child_type.ToString(), lambda_return_type.ToString()); } 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 20de34161..b2a98f86a 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_value.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_value.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/map_vector.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "core_functions/scalar/list_functions.hpp" @@ -246,7 +247,8 @@ void UnpivotResolveTypes(ResolveScalarFunctionTypesInput &input) { arguments.empty() ? LogicalType::SQLNULL : ExpressionBinder::GetExpressionReturnType(*arguments[0]); for (idx_t i = 1; i < arguments.size(); i++) { auto arg_type = ExpressionBinder::GetExpressionReturnType(*arguments[i]); - if (!LogicalType::TryGetMaxLogicalType(context, child_type, arg_type, child_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, child_type, arg_type, child_type, + input.GetDecimalWidthLimit())) { string list_arguments = "Full list: "; idx_t error_index = list_arguments.size(); for (idx_t k = 0; k < arguments.size(); k++) { diff --git a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp index 0b060ea0d..2866cf271 100644 --- a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp +++ b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp @@ -1,3 +1,5 @@ +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/operator/decimal_cast_operators.hpp" #include "duckdb/common/likely.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -222,6 +224,18 @@ static unique_ptr PropagateAbsStats(ClientContext &context, Func return stats.ToUnique(); } +//! abs() of a wide decimal negates the BIGNUM blob of negative values +static void WideDecimalAbs(DataChunk &args, ExpressionState &state, Vector &result) { + auto &heap = StringVector::GetStringHeap(result); + UnaryExecutor::Execute(args.data[0], result, [&](bignum_t a) { + const BignumIntermediate value(a); + if (value.is_negative) { + return value.Negate(heap); + } + return StringVector::AddStringOrBlob(result, a.data); + }); +} + template static void DecimalUnaryOpResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); @@ -236,6 +250,10 @@ static void DecimalUnaryOpResolveTypes(ResolveScalarFunctionTypesInput &input) { case PhysicalType::INT64: bound_function.SetFunctionCallback(ScalarFunction::GetScalarUnaryFunction(LogicalTypeId::BIGINT)); break; + case PhysicalType::VARCHAR: + // the unscaled value of a wide decimal is a BIGNUM blob + bound_function.SetFunctionCallback(WideDecimalAbs); + break; default: bound_function.SetFunctionCallback(ScalarFunction::GetScalarUnaryFunction(LogicalTypeId::HUGEINT)); break; @@ -507,11 +525,34 @@ struct CeilOperator { }; } // namespace -template +template static void GenericRoundFunctionDecimal(DataChunk &input, ExpressionState &state, Vector &result) { - auto &func_expr = state.expr.Cast(); - OP::template Operation(input, DecimalType::GetScale(func_expr.GetChildren()[0]->GetReturnType()), - result); + OP::template Operation(input, state, result); +} + +//! The SQL function a rounding mode belongs to, for error messages +static constexpr const char *DecimalRoundingName(DecimalRounding rounding) { + return rounding == DecimalRounding::TRUNCATE ? "TRUNC" + : rounding == DecimalRounding::FLOOR ? "FLOOR" + : rounding == DecimalRounding::CEIL ? "CEIL" + : rounding == DecimalRounding::HALF_AWAY_FROM_ZERO ? "ROUND" + : "ROUND_EVEN"; +} + +//! Rounds the values of a decimal vector of any tier: drop_digits digits are dropped with the rounding mode and +//! restore_digits zeros appended, a value that does not fit the width of the result type overflows +template +static void RoundDecimalVector(Vector &source, Vector &result, idx_t count, idx_t drop_digits, idx_t restore_digits, + const char *name, ExpressionState &expression_state) { + const auto width = DecimalType::GetWidth(result.GetType()); + typename DecimalHelper::RoundState state(result, expression_state.GetContext()); + UnaryExecutor::Execute(source, result, count, [&](T input) { + T rounded; + if (!DecimalHelper::template TryRound(input, drop_digits, restore_digits, width, state, rounded)) { + throw OutOfRangeException("Overflow in %s of DECIMAL(%d)", name, width); + } + return rounded; + }); } template @@ -526,16 +567,19 @@ static void GenericRoundFunctionDecimalResolveTypes(ResolveScalarFunctionTypesIn } else { switch (decimal_type.InternalType()) { case PhysicalType::INT16: - bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); + bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); break; case PhysicalType::INT32: - bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); + bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); break; case PhysicalType::INT64: - bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); + bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); + break; + case PhysicalType::INT128: + bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); break; default: - bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); + bound_function.SetFunctionCallback(GenericRoundFunctionDecimal); break; } } @@ -544,19 +588,16 @@ static void GenericRoundFunctionDecimalResolveTypes(ResolveScalarFunctionTypesIn } namespace { -struct CeilDecimalOperator { - template - 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) { - // below 0 we floor the number (e.g. -10.5 -> -10) - return UnsafeNumericCast(input / power_of_ten); - } else { - // above 0 we ceil the number - return UnsafeNumericCast(((input - 1) / power_of_ten) + 1); - } - }); +//! Removes the scale of a decimal with the rounding mode +template +struct DecimalRoundOperator { + static constexpr const char *NAME = DecimalRoundingName(ROUNDING); + + template + static void Operation(DataChunk &input, ExpressionState &state, Vector &result) { + auto &func_expr = state.expr.Cast(); + auto scale = DecimalType::GetScale(func_expr.GetChildren()[0]->GetReturnType()); + RoundDecimalVector(input.data[0], result, input.size(), scale, 0, NAME, state); } }; } // namespace @@ -578,7 +619,7 @@ ScalarFunctionSet CeilFun::GetFunctions() { func = ScalarFunction::UnaryFunction; break; case LogicalTypeId::DECIMAL: - resolve_func = GenericRoundFunctionDecimalResolveTypes; + resolve_func = GenericRoundFunctionDecimalResolveTypes>; break; default: throw InternalException("Unimplemented numeric type for function \"ceil\""); @@ -601,22 +642,6 @@ struct FloorOperator { return std::floor(left); } }; - -struct FloorDecimalOperator { - template - 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) { - // below 0 we ceil the number (e.g. -10.5 -> -11) - return UnsafeNumericCast(((input + 1) / power_of_ten) - 1); - } else { - // above 0 we floor the number - return UnsafeNumericCast(input / power_of_ten); - } - }); - } -}; } // namespace ScalarFunctionSet FloorFun::GetFunctions() { @@ -636,7 +661,7 @@ ScalarFunctionSet FloorFun::GetFunctions() { func = ScalarFunction::UnaryFunction; break; case LogicalTypeId::DECIMAL: - resolve_func = GenericRoundFunctionDecimalResolveTypes; + resolve_func = GenericRoundFunctionDecimalResolveTypes>; break; default: throw InternalException("Unimplemented numeric type for function \"floor\""); @@ -655,33 +680,32 @@ ScalarFunctionSet FloorFun::GetFunctions() { namespace { struct RoundPrecisionFunctionData : public FunctionData { - RoundPrecisionFunctionData(int32_t target_scale, uint32_t source_width, bool check_overflow) - : target_scale(target_scale), source_width(source_width), check_overflow(check_overflow) { + RoundPrecisionFunctionData(int32_t target_scale, uint32_t source_width) + : target_scale(target_scale), source_width(source_width) { } int32_t target_scale; uint32_t source_width; - bool check_overflow; unique_ptr Copy() const override { - return make_uniq(target_scale, source_width, check_overflow); + return make_uniq(target_scale, source_width); } bool Equals(const FunctionData &other_p) const override { auto &other = other_p.Cast(); - return target_scale == other.target_scale && source_width == other.source_width && - check_overflow == other.check_overflow; + return target_scale == other.target_scale && source_width == other.source_width; } }; -template +template void GenericRoundPrecisionDecimal(DataChunk &input, ExpressionState &state, Vector &result) { - OP::template Operation(input, state, result); + OP::template Operation(input, state, result); } //! Resolves the types and the function of a decimal round with a precision, given the original decimal type template -unique_ptr ResolveDecimalRoundPrecision(BoundScalarFunction &bound_function, +unique_ptr ResolveDecimalRoundPrecision(const DecimalWidthLimit &decimal_width_limit, + BoundScalarFunction &bound_function, const LogicalType &decimal_type, int32_t round_value) { // our new precision becomes the round value // e.g. ROUND(DECIMAL(18,3), 1) -> DECIMAL(18,1) @@ -693,36 +717,40 @@ unique_ptr ResolveDecimalRoundPrecision(BoundScalarFunction &bound auto scale = DecimalType::GetScale(decimal_type); auto result_width = width; auto argument_type = decimal_type; - bool check_overflow = false; if (round_value < 0) { target_scale = 0; - if (CAN_CARRY && scale == 0 && round_value >= -int32_t(width)) { - if (result_width < Decimal::MAX_WIDTH_DECIMAL) { + if (CAN_CARRY && scale == 0 && int64_t(round_value) >= -int64_t(width)) { + // a fixed-size decimal stays in the fixed-size tiers (a carry out of 38 digits overflows), a wide decimal + // grows by the carry digit + if (Decimal::IsWide(width)) { + result_width = decimal_width_limit.CheckedWidth(idx_t(result_width) + 1, width, "Rounding"); + } else if (result_width < Decimal::MAX_WIDTH_INT128) { result_width++; - } else { - check_overflow = true; } } auto result_type = LogicalType::DECIMAL(result_width, target_scale); switch (result_type.InternalType()) { case PhysicalType::INT16: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; case PhysicalType::INT32: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; case PhysicalType::INT64: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + break; + case PhysicalType::INT128: + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; default: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; } if (result_type.InternalType() != decimal_type.InternalType()) { argument_type = LogicalType::DECIMAL(result_width, scale); } } else { - if (round_value >= (int32_t)scale) { + if (NumericCast(round_value) >= scale) { // if round_value is bigger than or equal to scale we do nothing bound_function.SetFunctionCallback(ScalarFunction::NopFunction); target_scale = scale; @@ -730,30 +758,33 @@ unique_ptr ResolveDecimalRoundPrecision(BoundScalarFunction &bound target_scale = NumericCast(round_value); switch (decimal_type.InternalType()) { case PhysicalType::INT16: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; case PhysicalType::INT32: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; case PhysicalType::INT64: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + break; + case PhysicalType::INT128: + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; default: - bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); + bound_function.SetFunctionCallback(GenericRoundPrecisionDecimal); break; } } } bound_function.GetArguments()[0] = argument_type; bound_function.SetReturnType(LogicalType::DECIMAL(result_width, target_scale)); - return make_uniq(round_value, width, check_overflow); + return make_uniq(round_value, width); } template void DecimalRoundPrecisionResolveTypes(ResolveScalarFunctionTypesInput &input) { auto val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::INTEGER); - ResolveDecimalRoundPrecision(input.GetBoundFunction(), input.GetArgumentType(0), - IntegerValue::Get(val)); + ResolveDecimalRoundPrecision(input.GetDecimalWidthLimit(), input.GetBoundFunction(), + input.GetArgumentType(0), IntegerValue::Get(val)); } //! The bind data is derived from the type the function was called with, before it was cast @@ -762,7 +793,7 @@ unique_ptr BindDecimalRoundPrecision(BindScalarFunctionInput &inpu auto &bound_function = input.GetBoundFunction(); auto val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::INTEGER); return ResolveDecimalRoundPrecision( - bound_function, bound_function.GetLogicalArguments()[0], IntegerValue::Get(val)); + input.GetDecimalWidthLimit(), bound_function, bound_function.GetLogicalArguments()[0], IntegerValue::Get(val)); } struct TruncOperatorPrecision { @@ -794,48 +825,41 @@ struct TruncOperator { } }; -struct TruncDecimalOperator { - template - 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 - return UnsafeNumericCast((input / power_of_ten)); - }); - } -}; +//! Rounds a decimal to a negative precision: the digits below the precision are dropped with the rounding mode and +//! restored as zeros +template +struct DecimalRoundNegativePrecisionOperator { + static constexpr const char *NAME = DecimalRoundingName(ROUNDING); -struct TruncDecimalNegativePrecisionOperator { - template + template static void Operation(DataChunk &input, ExpressionState &state, Vector &result) { auto &func_expr = state.expr.Cast(); auto &info = func_expr.BindInfo()->Cast(); 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: every value truncates to zero, NULL stays NULL - UnaryExecutor::Execute(input.data[0], result, [](T) { return T(0); }); + const idx_t restore_digits = NumericCast(-static_cast(info.target_scale)); + const idx_t drop_digits = source_scale + restore_digits; + if (drop_digits > info.source_width) { + // more digits than the values hold are dropped, which leaves less than a tenth: every value rounds to zero + const auto zero = DecimalHelper::Store(result, DecimalHelper::FromInteger(hugeint_t(0))); + UnaryExecutor::Execute(input.data[0], result, input.size(), [&](T) { return zero; }); return; } - T divide_power_of_ten = - UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[-info.target_scale + source_scale]); - T multiply_power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[-info.target_scale]); - - UnaryExecutor::Execute(input.data[0], result, [&](T input) { - return UnsafeNumericCast(input / divide_power_of_ten * multiply_power_of_ten); - }); + RoundDecimalVector(input.data[0], result, input.size(), drop_digits, restore_digits, NAME, state); } }; -struct TruncDecimalPositivePrecisionOperator { - template +//! Rounds a decimal to a positive precision below its scale: the digits below the precision are dropped +template +struct DecimalRoundPositivePrecisionOperator { + static constexpr const char *NAME = DecimalRoundingName(ROUNDING); + + template static void Operation(DataChunk &input, ExpressionState &state, Vector &result) { auto &func_expr = state.expr.Cast(); auto &info = func_expr.BindInfo()->Cast(); auto source_scale = DecimalType::GetScale(func_expr.GetChildren()[0]->GetReturnType()); - T power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[source_scale - info.target_scale]); - UnaryExecutor::Execute(input.data[0], result, - [&](T input) { return UnsafeNumericCast(input / power_of_ten); }); + const idx_t drop_digits = source_scale - NumericCast(info.target_scale); + RoundDecimalVector(input.data[0], result, input.size(), drop_digits, 0, NAME, state); } }; @@ -884,11 +908,13 @@ ScalarFunctionSet TruncFun::GetFunctions() { trunc_prec_func = ScalarFunction::BinaryFunction; break; case LogicalTypeId::DECIMAL: - resolve_func = GenericRoundFunctionDecimalResolveTypes; + resolve_func = GenericRoundFunctionDecimalResolveTypes>; bind_prec_func = - BindDecimalRoundPrecision; - resolve_prec_func = DecimalRoundPrecisionResolveTypes; + BindDecimalRoundPrecision, + DecimalRoundPositivePrecisionOperator>; + resolve_prec_func = + DecimalRoundPrecisionResolveTypes, + DecimalRoundPositivePrecisionOperator>; break; case LogicalTypeId::TINYINT: trunc_func = ScalarFunction::NopFunction; @@ -949,52 +975,20 @@ ScalarFunctionSet TruncFun::GetFunctions() { //===--------------------------------------------------------------------===// namespace { -template -inline T RoundDivide(T input, T power_of_ten) { - // power_of_ten is ten raised to the digits being dropped and is at least ten because the binder replaces round - // with ScalarFunction::NopFunction if the round would not drop digits - D_ASSERT(power_of_ten >= 10); - T quotient; - T remainder; - if constexpr (std::is_same::value) { - // hugeint division and modulo both run a full DivMod and discard half of the result - quotient = Hugeint::DivMod(input, power_of_ten, remainder); - } else { - quotient = UnsafeNumericCast(input / power_of_ten); - remainder = UnsafeNumericCast(input % power_of_ten); - } - if (remainder < 0) { - remainder = UnsafeNumericCast(-remainder); - } - T half = UnsafeNumericCast(power_of_ten / 2); - if (remainder > half || (remainder == half && ROUND_POLICY::RoundsAway(quotient))) { - quotient = UnsafeNumericCast(input < 0 ? quotient - 1 : quotient + 1); - } - return quotient; -} - struct RoundHalfAwayFromZero { - static constexpr const char *Name = "ROUND"; + static constexpr DecimalRounding ROUNDING = DecimalRounding::HALF_AWAY_FROM_ZERO; static double Nearest(double value) { return RoundToNearestAwayFromZero(value); } - template - static bool RoundsAway(T) { - return true; - } }; struct RoundHalfToEven { - static constexpr const char *Name = "ROUND_EVEN"; + static constexpr DecimalRounding ROUNDING = DecimalRounding::HALF_TO_EVEN; static double Nearest(double value) { return RoundToNearestEven(value); } - template - static bool RoundsAway(T quotient) { - return quotient % 2 != 0; - } }; //! The error of the rounded product, computed with Dekker's algorithm because fma is not exact on every platform @@ -1060,29 +1054,6 @@ struct RoundOperator { } }; -struct RoundDecimalOperator { - template - 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 - // in case of a tie we round away from zero - // i.e. -10.5 -> -11, 10.5 -> 11 - // we implement this by adding (positive) or subtracting (negative) 0.5 - // and then flooring the number - // e.g. 10.5 + 0.5 = 11, floor(11) = 11 - // 10.4 + 0.5 = 10.9, floor(10.9) = 10 - UnaryExecutor::Execute(input.data[0], result, [&](T input) { - if (input < 0) { - input -= addition; - } else { - input += addition; - } - return UnsafeNumericCast(input / power_of_ten); - }); - } -}; - template struct RoundIntegerOperator { template @@ -1095,30 +1066,23 @@ struct RoundIntegerOperator { return 0; } const auto power_of_ten = Hugeint::POWERS_OF_TEN[-precision]; - const auto half = power_of_ten / 2; hugeint_t wide_input = 0; if constexpr (std::is_same::value) { wide_input = input; } else { wide_input = Hugeint::Convert(input); } - auto rounded = wide_input / power_of_ten; - const auto remainder = wide_input % power_of_ten; - if (remainder > half || (remainder == half && ROUND_POLICY::RoundsAway(rounded))) { - rounded = Hugeint::Add(rounded, 1); - } else if (remainder < -half || (remainder == -half && ROUND_POLICY::RoundsAway(rounded))) { - rounded = Hugeint::Subtract(rounded, 1); - } + auto rounded = DecimalHelper::RoundDroppedDigits(wide_input, power_of_ten); if (rounded == 0) { return 0; } hugeint_t rounded_value = 0; if (!Hugeint::TryMultiply(rounded, power_of_ten, rounded_value)) { - throw OutOfRangeException("Overflow in %s of integer", ROUND_POLICY::Name); + throw OutOfRangeException("Overflow in %s of integer", DecimalRoundingName(ROUND_POLICY::ROUNDING)); } TR result; if (!TryCast::Operation(rounded_value, result)) { - throw OutOfRangeException("Overflow in %s of integer", ROUND_POLICY::Name); + throw OutOfRangeException("Overflow in %s of integer", DecimalRoundingName(ROUND_POLICY::ROUNDING)); } return result; } @@ -1126,52 +1090,6 @@ struct RoundIntegerOperator { } // namespace -template -struct DecimalRoundNegativePrecisionOperator { - template - static void Operation(DataChunk &input, ExpressionState &state, Vector &result) { - auto &func_expr = state.expr.Cast(); - 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: every value rounds to zero, NULL stays NULL - UnaryExecutor::Execute(input.data[0], result, [](T) { return T(0); }); - return; - } - T divide_power_of_ten = - UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[-info.target_scale + source_scale]); - T multiply_power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[-info.target_scale]); - const bool check_overflow = info.check_overflow; - - UnaryExecutor::Execute(input.data[0], result, [&](T input) { - auto rounded = - UnsafeNumericCast(RoundDivide(input, divide_power_of_ten) * multiply_power_of_ten); - if (check_overflow) { - if constexpr (std::is_same_v) { - if (rounded <= -Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_DECIMAL] || - rounded >= Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_DECIMAL]) { - throw OutOfRangeException("Overflow in %s of DECIMAL(38)", ROUND_POLICY::Name); - } - } - } - return rounded; - }); - } -}; - -template -struct DecimalRoundPositivePrecisionOperator { - template - static void Operation(DataChunk &input, ExpressionState &state, Vector &result) { - auto &func_expr = state.expr.Cast(); - auto &info = func_expr.BindInfo()->Cast(); - auto source_scale = DecimalType::GetScale(func_expr.GetChildren()[0]->GetReturnType()); - T power_of_ten = UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[source_scale - info.target_scale]); - UnaryExecutor::Execute(input.data[0], result, - [&](T input) { return RoundDivide(input, power_of_ten); }); - } -}; - ScalarFunctionSet RoundFun::GetFunctions() { ScalarFunctionSet round; for (auto &type : LogicalType::Numeric()) { @@ -1192,13 +1110,15 @@ ScalarFunctionSet RoundFun::GetFunctions() { ScalarFunction::BinaryFunction>; break; case LogicalTypeId::DECIMAL: - resolve_func = GenericRoundFunctionDecimalResolveTypes; + resolve_func = + GenericRoundFunctionDecimalResolveTypes>; bind_prec_func = - BindDecimalRoundPrecision, - DecimalRoundPositivePrecisionOperator, true>; - resolve_prec_func = - DecimalRoundPrecisionResolveTypes, - DecimalRoundPositivePrecisionOperator, true>; + BindDecimalRoundPrecision, + DecimalRoundPositivePrecisionOperator, + true>; + resolve_prec_func = DecimalRoundPrecisionResolveTypes< + DecimalRoundNegativePrecisionOperator, + DecimalRoundPositivePrecisionOperator, true>; break; case LogicalTypeId::TINYINT: round_func = ScalarFunction::NopFunction; @@ -1272,11 +1192,13 @@ ScalarFunctionSet RoundEvenFun::GetFunctions() { ScalarFunction::BinaryFunction>; break; case LogicalTypeId::DECIMAL: - bind_prec_func = BindDecimalRoundPrecision, - DecimalRoundPositivePrecisionOperator, true>; + bind_prec_func = + BindDecimalRoundPrecision, + DecimalRoundPositivePrecisionOperator, true>; resolve_prec_func = - DecimalRoundPrecisionResolveTypes, - DecimalRoundPositivePrecisionOperator, true>; + DecimalRoundPrecisionResolveTypes, + DecimalRoundPositivePrecisionOperator, + true>; break; case LogicalTypeId::TINYINT: round_prec_func = diff --git a/src/duckdb/extension/json/json_functions/json_transform.cpp b/src/duckdb/extension/json/json_functions/json_transform.cpp index 62792a0bd..0c1d1a2f7 100644 --- a/src/duckdb/extension/json/json_functions/json_transform.cpp +++ b/src/duckdb/extension/json/json_functions/json_transform.cpp @@ -37,16 +37,19 @@ JSONTransformOptions::JSONTransformOptions(bool strict_cast_p, bool error_duplic } //! Forward declaration for recursion -static LogicalType StructureStringToType(yyjson_val *val, ClientContext &context); +static LogicalType StructureStringToType(yyjson_val *val, ClientContext &context, + const DecimalWidthLimit &decimal_width_limit); -static LogicalType StructureStringToTypeArray(yyjson_val *arr, ClientContext &context) { +static LogicalType StructureStringToTypeArray(yyjson_val *arr, ClientContext &context, + const DecimalWidthLimit &decimal_width_limit) { if (yyjson_arr_size(arr) != 1) { throw BinderException("Too many values in array of JSON structure"); } - return LogicalType::LIST(StructureStringToType(yyjson_arr_get_first(arr), context)); + return LogicalType::LIST(StructureStringToType(yyjson_arr_get_first(arr), context, decimal_width_limit)); } -static LogicalType StructureToTypeObject(yyjson_val *obj, ClientContext &context) { +static LogicalType StructureToTypeObject(yyjson_val *obj, ClientContext &context, + const DecimalWidthLimit &decimal_width_limit) { // STRUCT field names are case-insensitive identifier_set_t names; child_list_t child_types; @@ -61,7 +64,7 @@ static LogicalType StructureToTypeObject(yyjson_val *obj, ClientContext &context if (!names.insert(Identifier(key_str)).second) { JSONCommon::ThrowValFormatError("Duplicate keys in object in JSON structure: %s", val); } - child_types.emplace_back(key_str, StructureStringToType(val, context)); + child_types.emplace_back(key_str, StructureStringToType(val, context, decimal_width_limit)); } D_ASSERT(yyjson_obj_size(obj) == names.size()); if (child_types.empty()) { @@ -70,15 +73,17 @@ static LogicalType StructureToTypeObject(yyjson_val *obj, ClientContext &context return LogicalType::STRUCT(child_types); } -static LogicalType StructureStringToType(yyjson_val *val, ClientContext &context) { +// the type names of the structure are bound within the decimal width limit of the bind +static LogicalType StructureStringToType(yyjson_val *val, ClientContext &context, + const DecimalWidthLimit &decimal_width_limit) { switch (yyjson_get_tag(val)) { case YYJSON_TYPE_ARR | YYJSON_SUBTYPE_NONE: - return StructureStringToTypeArray(val, context); + return StructureStringToTypeArray(val, context, decimal_width_limit); case YYJSON_TYPE_OBJ | YYJSON_SUBTYPE_NONE: - return StructureToTypeObject(val, context); + return StructureToTypeObject(val, context, decimal_width_limit); case YYJSON_TYPE_STR | YYJSON_SUBTYPE_NOESC: case YYJSON_TYPE_STR | YYJSON_SUBTYPE_NONE: - return TransformStringToLogicalType(unsafe_yyjson_get_str(val), context); + return TransformStringToLogicalType(unsafe_yyjson_get_str(val), context, &decimal_width_limit); default: throw BinderException("invalid JSON structure"); } @@ -100,7 +105,8 @@ static unique_ptr JSONTransformBind(BindScalarFunctionInput &input auto structure_string = json_structure_val->GetValueUnsafe(); JSONAllocator json_allocator(Allocator::DefaultAllocator()); auto doc = JSONCommon::ReadDocument(structure_string, JSONCommon::READ_FLAG, json_allocator.GetYYAlc()); - bound_function.SetReturnType(StructureStringToType(doc->root, context)); + const auto decimal_width_limit = input.GetDecimalWidthLimit(); + bound_function.SetReturnType(StructureStringToType(doc->root, context, decimal_width_limit)); } return make_uniq(bound_function.GetReturnType()); } @@ -155,14 +161,16 @@ static inline bool GetValueNumerical(yyjson_val *val, T &result, JSONTransformOp } template -static inline bool GetValueDecimal(yyjson_val *val, T &result, uint32_t w, uint32_t s, JSONTransformOptions &options) { +static inline bool GetValueDecimal(yyjson_val *val, T &result, Vector &vector, 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)) { case YYJSON_TYPE_STR | YYJSON_SUBTYPE_NOESC: case YYJSON_TYPE_STR | YYJSON_SUBTYPE_NONE: case YYJSON_TYPE_RAW | YYJSON_SUBTYPE_NONE: - success = OP::template Operation(GetString(val), result, options.parameters, w, s); + success = + VectorDecimalCast::Operation(GetString(val), result, vector, options.parameters, w, s); break; case YYJSON_TYPE_ARR | YYJSON_SUBTYPE_NONE: case YYJSON_TYPE_OBJ | YYJSON_SUBTYPE_NONE: @@ -170,16 +178,20 @@ static inline bool GetValueDecimal(yyjson_val *val, T &result, uint32_t w, uint3 break; case YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE: case YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE: - success = OP::template Operation(unsafe_yyjson_get_bool(val), result, options.parameters, w, s); + success = VectorDecimalCast::Operation(unsafe_yyjson_get_bool(val), result, vector, + options.parameters, w, s); break; case YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT: - success = OP::template Operation(unsafe_yyjson_get_uint(val), result, options.parameters, w, s); + success = VectorDecimalCast::Operation(unsafe_yyjson_get_uint(val), result, vector, + options.parameters, w, s); break; case YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT: - success = OP::template Operation(unsafe_yyjson_get_sint(val), result, options.parameters, w, s); + success = VectorDecimalCast::Operation(unsafe_yyjson_get_sint(val), result, vector, + options.parameters, w, s); break; case YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL: - success = OP::template Operation(unsafe_yyjson_get_real(val), result, options.parameters, w, s); + success = VectorDecimalCast::Operation(unsafe_yyjson_get_real(val), result, vector, + options.parameters, w, s); break; default: throw InternalException("Unknown yyjson tag in GetValueString"); @@ -262,7 +274,7 @@ static bool TransformDecimal(yyjson_val *vals[], Vector &result, const idx_t cou const auto &val = vals[i]; if (!val || unsafe_yyjson_is_null(val)) { validity.SetInvalid(i); - } else if (!GetValueDecimal(val, data[i], width, scale, options)) { + } else if (!GetValueDecimal(val, data[i], result, width, scale, options)) { validity.SetInvalid(i); if (success && options.strict_cast) { options.object_index = i; @@ -1176,6 +1188,8 @@ bool JSONTransform::Transform(yyjson_val *vals[], yyjson_alc *alc, Vector &resul return TransformDecimal(vals, result, count, width, scale, options); case PhysicalType::INT128: return TransformDecimal(vals, result, count, width, scale, options); + case PhysicalType::VARCHAR: + return TransformDecimal(vals, result, count, width, scale, options); default: throw InternalException("Unimplemented physical type for decimal"); } diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index 1643f1205..73c973458 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -1322,6 +1322,9 @@ static unique_ptr CreateDecimalReader(const ParquetReader &reader, return make_uniq>>(reader, schema); case PhysicalType::INT128: return make_uniq>>(reader, schema); + case PhysicalType::VARCHAR: + // a wide decimal (a BIGNUM blob) backed by an integer column + return ParquetDecimalUtils::CreateReader(reader, schema); default: throw NotImplementedException("Unimplemented internal type for CreateDecimalReader"); } diff --git a/src/duckdb/extension/parquet/column_writer.cpp b/src/duckdb/extension/parquet/column_writer.cpp index 3358b96a7..3bf31c8e8 100644 --- a/src/duckdb/extension/parquet/column_writer.cpp +++ b/src/duckdb/extension/parquet/column_writer.cpp @@ -1,4 +1,5 @@ #include "column_writer.hpp" +#include "duckdb/common/types/decimal.hpp" #include #include @@ -553,6 +554,9 @@ unique_ptr ColumnWriter::CreateWriterRecursive(ClientContext &cont return make_uniq>(writer, std::move(schema), path_in_schema); case PhysicalType::INT64: return make_uniq>(writer, std::move(schema), path_in_schema); + case PhysicalType::VARCHAR: + // wide decimal stored as a BIGNUM blob + return make_uniq(writer, std::move(schema), path_in_schema); default: return make_uniq(writer, std::move(schema), path_in_schema); } diff --git a/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp b/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp index 9a73c2b9a..00ffcfa34 100644 --- a/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/delta_length_byte_array_decoder.cpp @@ -1,5 +1,6 @@ #include "decoder/delta_length_byte_array_decoder.hpp" +#include #include #include @@ -8,6 +9,7 @@ #include "parquet_reader.hpp" #include "reader/string_column_reader.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/common/helper.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/types/string_type.hpp" @@ -22,9 +24,13 @@ DeltaLengthByteArrayDecoder::DeltaLengthByteArrayDecoder(ColumnReader &reader) } void DeltaLengthByteArrayDecoder::InitializePage() { - if (reader.Type().InternalType() != PhysicalType::VARCHAR) { + auto &type = reader.Type(); + if (type.InternalType() != PhysicalType::VARCHAR) { throw std::runtime_error("Delta Length Byte Array encoding is only supported for string/blob data"); } + // only VARCHAR and BLOB columns are read by a StringColumnReader; a wide DECIMAL shares the physical type + decode_to_plain = type.id() != LogicalTypeId::VARCHAR && type.id() != LogicalTypeId::BLOB; + // read the binary packed lengths auto &block = *reader.block; auto &buffer_manager = reader.reader.buffer_manager; @@ -42,6 +48,26 @@ void DeltaLengthByteArrayDecoder::InitializePage() { block.Available(total_string_length); length_idx = 0; + if (decode_to_plain) { + DecodeToPlain(block, total_string_length); + } +} + +//! Rewrite the page into the plain BYTE_ARRAY layout ([4-byte length][data] repeated) and consume it from the block +void DeltaLengthByteArrayDecoder::DecodeToPlain(ResizeableBuffer &block, idx_t total_string_length) { + auto &allocator = reader.reader.allocator; + const auto length_data = reinterpret_cast(length_buffer.GetCurrentLoc()); + plain_data = make_shared_ptr(); + plain_data->Resize(allocator, total_string_length + byte_array_count * sizeof(uint32_t)); + auto output = plain_data->GetCurrentLoc(); + for (idx_t i = 0; i < byte_array_count; i++) { + const auto len = length_data[i]; + Store(len, output); + output += sizeof(uint32_t); + memcpy(output, block.GetCurrentLoc(), len); + output += len; + block.UnsafeInc(len); + } } bool IsContinuationByte(uint8_t b) { @@ -50,6 +76,10 @@ bool IsContinuationByte(uint8_t b) { void DeltaLengthByteArrayDecoder::Read(shared_ptr &block_ref, uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset) { + if (decode_to_plain) { + reader.Plain(plain_data, defines, read_count, result_offset, result); + return; + } if (defines) { ReadInternal(block_ref, defines, read_count, result, result_offset); } else { @@ -126,6 +156,10 @@ void DeltaLengthByteArrayDecoder::ReadInternal(shared_ptr &blo } void DeltaLengthByteArrayDecoder::Skip(uint8_t *defines, idx_t skip_count) { + if (decode_to_plain) { + reader.PlainSkip(*plain_data, defines, skip_count); + return; + } if (defines) { SkipInternal(defines, skip_count); } else { diff --git a/src/duckdb/extension/parquet/include/decoder/delta_length_byte_array_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/delta_length_byte_array_decoder.hpp index d3d64def2..9d40dc20a 100644 --- a/src/duckdb/extension/parquet/include/decoder/delta_length_byte_array_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/delta_length_byte_array_decoder.hpp @@ -38,12 +38,17 @@ class DeltaLengthByteArrayDecoder { idx_t result_offset); template void SkipInternal(uint8_t *defines, idx_t skip_count); + void DecodeToPlain(ResizeableBuffer &block, idx_t total_string_length); private: ColumnReader &reader; ResizeableBuffer &length_buffer; idx_t byte_array_count = 0; idx_t length_idx; + //! Readers of other VARCHAR-backed types (wide DECIMAL) are not string readers: their pages are decoded into the + //! plain BYTE_ARRAY layout and read through the reader's own Plain path + bool decode_to_plain = false; + shared_ptr plain_data; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp b/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp index fa6c3d756..2ecc01366 100644 --- a/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp +++ b/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp @@ -8,6 +8,8 @@ #pragma once +#include "duckdb/common/bignum.hpp" + #include "column_reader.hpp" namespace duckdb { @@ -52,6 +54,13 @@ class ParquetDecimalUtils { static unique_ptr CreateReader(const ParquetReader &reader, const ParquetColumnSchema &schema); + //! Converts a big-endian two's complement Parquet decimal into the BIGNUM blob of a wide decimal + static string ReadWideDecimalValue(const_data_ptr_t pointer, idx_t size); + //! The number of bytes a FIXED_LEN_BYTE_ARRAY needs to hold decimals of the given width + static idx_t WideDecimalByteLength(uint32_t width); + //! Writes the BIGNUM blob of a wide decimal as a big-endian two's complement value of byte_length bytes + static void WriteWideDecimal(const bignum_t &value, idx_t byte_length, data_ptr_t result); + private: [[noreturn]] static void ThrowInvalidDecimalEncoding(); }; diff --git a/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp b/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp index 603756ab2..8186b7f0b 100644 --- a/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp +++ b/src/duckdb/extension/parquet/include/reader/decimal_column_reader.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/types/decimal_helper.hpp" #include #include "column_reader.hpp" @@ -54,6 +55,136 @@ struct DecimalParquetValueConversion { } }; +//! Wide decimals are BIGNUM blobs, the two's complement bytes are converted into the vector being filled +class WideDecimalColumnReader; + +template +struct WideDecimalParquetValueConversion { + template + static bignum_t PlainRead(ByteBuffer &plain_data, ColumnReader &reader); + + template + static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { + uint32_t decimal_len = FIXED_LENGTH ? reader.Schema().type_length : plain_data.Read(); + plain_data.Inc(decimal_len); + } + + static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { + return false; + } + + static idx_t PlainConstantSize() { + return 0; + } +}; + +//! INT32/INT64-backed Parquet decimals read into a wide decimal: a file that declares a width above 38 for a column +//! stored as an integer +template +struct WideDecimalFromIntegerConversion { + template + static bignum_t PlainRead(ByteBuffer &plain_data, ColumnReader &reader); + + template + static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { + if (CHECKED) { + plain_data.Inc(sizeof(PARQUET_TYPE)); + } else { + plain_data.UnsafeInc(sizeof(PARQUET_TYPE)); + } + } + + static bool PlainAvailable(const ByteBuffer &plain_data, const idx_t count) { + return plain_data.CheckAvailable(count * sizeof(PARQUET_TYPE)); + } + + static idx_t PlainConstantSize() { + return sizeof(PARQUET_TYPE); + } +}; + +class WideDecimalColumnReader : public ColumnReader { +public: + static constexpr const PhysicalType TYPE = PhysicalType::VARCHAR; + +public: + WideDecimalColumnReader(const ParquetReader &reader, const ParquetColumnSchema &schema) + : ColumnReader(reader, schema) { + } + + //! The vector the plain values are currently read into, so the conversion can allocate the blobs in it + Vector *current_result = nullptr; + +public: + void Plain(ByteBuffer &plain_data, uint8_t *defines, idx_t num_values, idx_t result_offset, + Vector &result) override { + current_result = &result; + switch (Schema().parquet_type) { + case duckdb_parquet::Type::INT32: + PlainTemplated>(plain_data, defines, num_values, + result_offset, result); + break; + case duckdb_parquet::Type::INT64: + PlainTemplated>(plain_data, defines, num_values, + result_offset, result); + break; + case duckdb_parquet::Type::FIXED_LEN_BYTE_ARRAY: + PlainTemplated>(plain_data, defines, num_values, + result_offset, result); + break; + default: + PlainTemplated>(plain_data, defines, num_values, + result_offset, result); + break; + } + current_result = nullptr; + } + + void PlainSkip(ByteBuffer &plain_data, uint8_t *defines, idx_t num_values) override { + switch (Schema().parquet_type) { + case duckdb_parquet::Type::INT32: + PlainSkipTemplated>(plain_data, defines, num_values); + break; + case duckdb_parquet::Type::INT64: + PlainSkipTemplated>(plain_data, defines, num_values); + break; + case duckdb_parquet::Type::FIXED_LEN_BYTE_ARRAY: + PlainSkipTemplated>(plain_data, defines, num_values); + break; + default: + PlainSkipTemplated>(plain_data, defines, num_values); + break; + } + } +}; + +template +template +bignum_t WideDecimalFromIntegerConversion::PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { + auto value = CHECKED ? plain_data.Read() : plain_data.UnsafeRead(); + auto blob = DecimalHelper::FromInteger(hugeint_t(value)); + auto &wide_reader = reader.Cast(); + D_ASSERT(wide_reader.current_result); + return bignum_t(StringVector::AddStringOrBlob(*wide_reader.current_result, blob.data(), blob.size())); +} + +template +template +bignum_t WideDecimalParquetValueConversion::PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { + idx_t byte_len; + if (FIXED_LENGTH) { + byte_len = reader.Schema().type_length; + } else { + byte_len = plain_data.Read(); + } + plain_data.Available(byte_len); + auto blob = ParquetDecimalUtils::ReadWideDecimalValue(const_data_ptr_cast(plain_data.GetCurrentLoc()), byte_len); + plain_data.Inc(byte_len); + auto &wide_reader = reader.Cast(); + D_ASSERT(wide_reader.current_result); + return bignum_t(StringVector::AddStringOrBlob(*wide_reader.current_result, blob.data(), blob.size())); +} + template class DecimalColumnReader : public TemplatedColumnReader 38, stored as BIGNUM blobs) as fixed-length big-endian two's complement values +class WideDecimalColumnWriter : public PrimitiveColumnWriter { +public: + WideDecimalColumnWriter(ParquetWriter &writer, ParquetColumnSchema &&column_schema, + vector schema_path_p); + ~WideDecimalColumnWriter() override = default; + + //! The byte length of every value, derived from the width of the decimal + idx_t byte_length; + +public: + unique_ptr InitializeStatsState() override; + void WriteVector(WriteStream &temp_writer, ColumnWriterStatistics *stats_p, ColumnWriterPageState *page_state, + Vector &input_column, idx_t chunk_start, idx_t chunk_end) override; + idx_t GetRowSize(const Vector &vector, const idx_t index, const PrimitiveColumnWriterState &state) const override; +}; + } // namespace duckdb diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 0d1801dd7..4d578eaa8 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -1,4 +1,5 @@ #include "parquet_reader.hpp" +#include "duckdb/common/types/decimal.hpp" #include #include @@ -583,8 +584,13 @@ LogicalType ParquetReader::DeriveLogicalType(const SchemaElement &s_ele, const P throw IOException("Invalid DECIMAL precision %d and scale %d", s_ele.precision, s_ele.scale); } schema.type_scale = NumericCast(s_ele.scale); - if (s_ele.precision > DecimalType::MaxWidth()) { + if (s_ele.precision > Decimal::MAX_WIDTH_INT128) { + // precisions above 38 become wide (BIGNUM-backed) decimals, other physical types fall back to DOUBLE schema.type_info = ParquetExtraTypeInfo::DECIMAL_BYTE_ARRAY; + if (s_ele.type == Type::BYTE_ARRAY || s_ele.type == Type::FIXED_LEN_BYTE_ARRAY) { + return LogicalType::DECIMAL(NumericCast(s_ele.precision), + NumericCast(s_ele.scale)); + } return LogicalType::DOUBLE; } switch (s_ele.type) { diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 8d5d419b6..7722ee143 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -1,5 +1,7 @@ #include "parquet_statistics.hpp" +#include "duckdb/common/bignum.hpp" + #include #include #include @@ -13,6 +15,7 @@ #include "reader/variant_column_reader.hpp" #include "zstd/common/xxhash.hpp" #include "duckdb/common/types/blob.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/time.hpp" #include "duckdb/common/types/uuid.hpp" #include "duckdb/common/types/value.hpp" @@ -90,6 +93,27 @@ unique_ptr ParquetStatisticsUtils::CreateNumericStats(const Logi return stats.ToUnique(); } +//! Decimals wider than 38 digits are BIGNUM blobs with min/max bounds, which are cut when the values are long +static unique_ptr CreateWideDecimalStats(const LogicalType &type, const ParquetColumnSchema &schema_ele, + const duckdb_parquet::Statistics &parquet_stats) { + auto stats = BignumStats::CreateUnknown(type); + Value min; + Value max; + if (parquet_stats.__isset.min_value) { + min = ParquetStatisticsUtils::ConvertValue(type, schema_ele, parquet_stats.min_value); + } else if (parquet_stats.__isset.min) { + min = ParquetStatisticsUtils::ConvertValue(type, schema_ele, parquet_stats.min); + } + if (parquet_stats.__isset.max_value) { + max = ParquetStatisticsUtils::ConvertValue(type, schema_ele, parquet_stats.max_value); + } else if (parquet_stats.__isset.max) { + max = ParquetStatisticsUtils::ConvertValue(type, schema_ele, parquet_stats.max); + } + BignumStats::SetMin(stats, min); + BignumStats::SetMax(stats, max); + return stats.ToUnique(); +} + static unique_ptr CreateFloatingPointStats(const LogicalType &type, const ParquetColumnSchema &schema_ele, const duckdb_parquet::Statistics &parquet_stats) { @@ -234,6 +258,15 @@ Value ParquetStatisticsUtils::ConvertValueInternal(const LogicalType &type, cons return ParquetDecimalStatsValue( ParquetDecimalUtils::ReadDecimalValue(stats_data, stats.size(), schema_ele), width, scale); + case PhysicalType::VARCHAR: { + // wide decimal stored as a BIGNUM blob + auto blob = ParquetDecimalUtils::ReadWideDecimalValue(stats_data, stats.size()); + bignum_t value {string_t(blob)}; + if (!DecimalHelper::FitsWidth(value, width)) { + return Value(); + } + return Value::DECIMAL(value, width, scale); + } default: throw InvalidInputException("Unsupported internal type for decimal"); } @@ -522,9 +555,13 @@ unique_ptr ParquetStatisticsUtils::TransformParquetStatistics( case LogicalTypeId::TIMESTAMP_SEC: case LogicalTypeId::TIMESTAMP_MS: case LogicalTypeId::TIMESTAMP_NS: - case LogicalTypeId::DECIMAL: case LogicalTypeId::UUID: return CreateNumericStats(type, schema, parquet_stats); + case LogicalTypeId::DECIMAL: + if (type.InternalType() == PhysicalType::VARCHAR) { + return CreateWideDecimalStats(type, schema, parquet_stats); + } + return CreateNumericStats(type, schema, parquet_stats); case LogicalTypeId::FLOAT: case LogicalTypeId::DOUBLE: if (CanHaveNaN(parquet_stats, can_have_nan)) { diff --git a/src/duckdb/extension/parquet/parquet_writer.cpp b/src/duckdb/extension/parquet/parquet_writer.cpp index 23e2a9623..8e40d653f 100644 --- a/src/duckdb/extension/parquet/parquet_writer.cpp +++ b/src/duckdb/extension/parquet/parquet_writer.cpp @@ -1,4 +1,6 @@ #include "parquet_writer.hpp" +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/decimal.hpp" #include #include @@ -201,6 +203,10 @@ bool ParquetWriter::TryGetParquetType(const LogicalType &duckdb_type, optional_p case PhysicalType::INT128: parquet_type = Type::FIXED_LEN_BYTE_ARRAY; break; + case PhysicalType::VARCHAR: + // wide decimals are written as big-endian two's complement bytes + parquet_type = Type::FIXED_LEN_BYTE_ARRAY; + break; default: throw InternalException("Unsupported internal decimal type"); } @@ -354,6 +360,10 @@ void ParquetWriter::SetSchemaProperties(const LogicalType &duckdb_type, duckdb_p schema_ele.logicalType.__isset.UUID = true; break; case LogicalTypeId::DECIMAL: + if (DecimalType::GetWidth(duckdb_type) > idx_t(NumericLimits::Maximum())) { + throw NotImplementedException("Parquet DECIMAL precision is a 32-bit integer, %s cannot be written", + duckdb_type.ToString()); + } schema_ele.converted_type = ConvertedType::DECIMAL; schema_ele.precision = NumericCast(DecimalType::GetWidth(duckdb_type)); schema_ele.scale = NumericCast(DecimalType::GetScale(duckdb_type)); @@ -363,6 +373,11 @@ void ParquetWriter::SetSchemaProperties(const LogicalType &duckdb_type, duckdb_p if (duckdb_type.InternalType() == PhysicalType::INT128) { schema_ele.type_length = 16; schema_ele.__isset.type_length = true; + } else if (duckdb_type.InternalType() == PhysicalType::VARCHAR) { + // wide decimal + schema_ele.type_length = + NumericCast(ParquetDecimalUtils::WideDecimalByteLength(DecimalType::GetWidth(duckdb_type))); + schema_ele.__isset.type_length = true; } schema_ele.__isset.logicalType = true; schema_ele.logicalType.__isset.DECIMAL = true; @@ -1147,6 +1162,40 @@ struct UUIDStatsUnifier : public BaseStringStatsUnifier { return result; } }; +//! Wide decimal statistics are the big-endian two's complement bytes of the FIXED_LEN_BYTE_ARRAY column; they are +//! compared as BIGNUM blobs, whose byte order is the numeric order +struct WideDecimalStatsUnifier : public ColumnStatsUnifier { + WideDecimalStatsUnifier(uint32_t width, uint32_t scale) : width(width), scale(scale) { + } + + uint32_t width; + uint32_t scale; + + static string Decode(const string &stats) { + return ParquetDecimalUtils::ReadWideDecimalValue(const_data_ptr_cast(stats.data()), stats.size()); + } + + string StatsToString(const string &stats) override { + if (stats.empty()) { + return string(); + } + auto blob = Decode(stats); + return Value::DECIMAL(bignum_t(string_t(blob)), width, scale).ToString(); + } + + void UnifyMinMax(const string &new_min, const string &new_max) override { + // the byte order of the BIGNUM blobs is their numeric order + if (!min_is_set || LessThan::Operation(string_t(Decode(new_min)), string_t(Decode(global_min)))) { + global_min = new_min; + min_is_set = true; + } + if (!max_is_set || GreaterThan::Operation(string_t(Decode(new_max)), string_t(Decode(global_max)))) { + global_max = new_max; + max_is_set = true; + } + } +}; + struct NullStatsUnifier : public ColumnStatsUnifier { void UnifyMinMax(const string &new_min, const string &new_max) override { } @@ -1208,6 +1257,9 @@ static unique_ptr GetBaseStatsUnifier(const LogicalType &typ return make_uniq>(width, scale); case PhysicalType::INT128: return make_uniq>(width, scale); + case PhysicalType::VARCHAR: + // wide decimal stored as a BIGNUM blob + return make_uniq(width, scale); default: return make_uniq(); } diff --git a/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp b/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp index 751b9906b..4962ee148 100644 --- a/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp +++ b/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp @@ -1,4 +1,7 @@ #include "reader/decimal_column_reader.hpp" +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include #include @@ -31,6 +34,9 @@ static unique_ptr CreateDecimalReaderInternal(const ParquetReader return make_uniq>(reader, schema); case PhysicalType::DOUBLE: return make_uniq>(reader, schema); + case PhysicalType::VARCHAR: + // wide decimal stored as a BIGNUM blob + return make_uniq(reader, schema); default: throw InternalException("Unrecognized type for Decimal"); } @@ -74,4 +80,18 @@ unique_ptr ParquetDecimalUtils::CreateReader(const ParquetReader & } } +string ParquetDecimalUtils::ReadWideDecimalValue(const_data_ptr_t pointer, idx_t size) { + // Parquet decimals are big-endian two's complement + return DecimalHelper::FromTwosComplement(pointer, size, true); +} + +idx_t ParquetDecimalUtils::WideDecimalByteLength(uint32_t width) { + // a decimal of "width" digits needs log2(10^width) bits plus a sign bit + return static_cast(std::ceil((static_cast(width) * 3.3219280948873626 + 1) / 8.0)); +} + +void ParquetDecimalUtils::WriteWideDecimal(const bignum_t &value, idx_t byte_length, data_ptr_t result) { + DecimalHelper::ToTwosComplement(value, result, byte_length, true); +} + } // namespace duckdb diff --git a/src/duckdb/extension/parquet/writer/decimal_column_writer.cpp b/src/duckdb/extension/parquet/writer/decimal_column_writer.cpp index c5fa0fb0f..64049e22c 100644 --- a/src/duckdb/extension/parquet/writer/decimal_column_writer.cpp +++ b/src/duckdb/extension/parquet/writer/decimal_column_writer.cpp @@ -1,4 +1,7 @@ #include "writer/decimal_column_writer.hpp" +#include "parquet_decimal_utils.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/string_type.hpp" #include #include @@ -129,4 +132,86 @@ idx_t FixedDecimalColumnWriter::GetRowSize(const Vector &vector, const idx_t ind return sizeof(hugeint_t); } +//===--------------------------------------------------------------------===// +// Wide decimals +//===--------------------------------------------------------------------===// +//! The BIGNUM encoding orders like the numeric value, so min/max can be tracked on the blobs themselves +class WideDecimalStatistics : public ColumnWriterStatistics { +public: + explicit WideDecimalStatistics(idx_t byte_length) : byte_length(byte_length) { + } + + idx_t byte_length; + bool has_stats = false; + string min; + string max; + +public: + string GetStats(const string &blob) { + string result(byte_length, '\0'); + ParquetDecimalUtils::WriteWideDecimal(bignum_t(string_t(blob)), byte_length, data_ptr_cast(&result[0])); + return result; + } + bool HasStats() override { + return has_stats; + } + void Update(const bignum_t &val) { + if (!has_stats) { + min = val.data.GetString(); + max = val.data.GetString(); + has_stats = true; + return; + } + if (LessThan::Operation(val.data, string_t(min))) { + min = val.data.GetString(); + } + if (GreaterThan::Operation(val.data, string_t(max))) { + max = val.data.GetString(); + } + } + string GetMin() override { + return GetMinValue(); + } + string GetMax() override { + return GetMaxValue(); + } + string GetMinValue() override { + return HasStats() ? GetStats(min) : string(); + } + string GetMaxValue() override { + return HasStats() ? GetStats(max) : string(); + } +}; + +WideDecimalColumnWriter::WideDecimalColumnWriter(ParquetWriter &writer, ParquetColumnSchema &&column_schema, + vector schema_path_p) + : PrimitiveColumnWriter(writer, std::move(column_schema), std::move(schema_path_p)), + byte_length(ParquetDecimalUtils::WideDecimalByteLength(DecimalType::GetWidth(Schema().type))) { +} + +unique_ptr WideDecimalColumnWriter::InitializeStatsState() { + return make_uniq(byte_length); +} + +void WideDecimalColumnWriter::WriteVector(WriteStream &temp_writer, ColumnWriterStatistics *stats_p, + ColumnWriterPageState *page_state, Vector &input_column, idx_t chunk_start, + idx_t chunk_end) { + auto &mask = FlatVector::ValidityMutable(input_column); + auto *ptr = FlatVector::GetData(input_column); + auto &stats = stats_p->Cast(); + vector temp_buffer(byte_length); + for (idx_t r = chunk_start; r < chunk_end; r++) { + if (mask.RowIsValid(r)) { + stats.Update(ptr[r]); + ParquetDecimalUtils::WriteWideDecimal(ptr[r], byte_length, temp_buffer.data()); + temp_writer.WriteData(temp_buffer.data(), byte_length); + } + } +} + +idx_t WideDecimalColumnWriter::GetRowSize(const Vector &vector, const idx_t index, + const PrimitiveColumnWriterState &state) const { + return byte_length; +} + } // namespace duckdb diff --git a/src/duckdb/extension/parquet/writer/variant/analyze_variant.cpp b/src/duckdb/extension/parquet/writer/variant/analyze_variant.cpp index 07647c231..843f39613 100644 --- a/src/duckdb/extension/parquet/writer/variant/analyze_variant.cpp +++ b/src/duckdb/extension/parquet/writer/variant/analyze_variant.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include #include #include @@ -131,7 +132,8 @@ static void CheckPrimitive(const VariantAnalyzeData &state, ShredAnalysisState & } if (VARIANT_TYPE == VariantLogicalType::DECIMAL) { D_ASSERT(count); - if (!state.decimal_consistent) { + if (!state.decimal_consistent || state.decimal_width > Decimal::MAX_WIDTH_INT128) { + // the Parquet VARIANT specification holds decimals of at most 38 digits: wider ones stay in the value return; } result.highest_count = count; diff --git a/src/duckdb/extension/parquet/writer/variant/convert_variant.cpp b/src/duckdb/extension/parquet/writer/variant/convert_variant.cpp index 5093274cd..e9dcf596b 100644 --- a/src/duckdb/extension/parquet/writer/variant/convert_variant.cpp +++ b/src/duckdb/extension/parquet/writer/variant/convert_variant.cpp @@ -10,6 +10,7 @@ #include "duckdb/common/exception/binder_exception.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/types.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/data_chunk.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" @@ -157,7 +158,9 @@ static unique_ptr BindTransform(BindScalarFunctionInput &input) { expr_return_type); } auto type_str = input.GetNonNullConstant(1); - auto shredded_type = TransformStringToLogicalType(type_str.GetValue(), context); + // the shredding type is bound within the decimal width limit of the bind + const auto decimal_width_limit = input.GetDecimalWidthLimit(); + auto shredded_type = TransformStringToLogicalType(type_str.GetValue(), context, &decimal_width_limit); bound_function.SetReturnType(VariantColumnWriter::GetParquetVariantType(shredded_type)); } else { bound_function.SetReturnType(VariantColumnWriter::GetParquetVariantType()); diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index dfbb229df..e325c4292 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-alpha55910"; + descriptor->api_version = "v2.1.0-alpha55959"; 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-alpha55910"; + descriptor->api_version = "v2.1.0-alpha55959"; 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-alpha55910"; + descriptor->api_version = "v2.1.0-alpha55959"; 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-alpha55910"; + descriptor->api_version = "v2.1.0-alpha55959"; 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 28be08e76..cc8cb4151 100644 --- a/src/duckdb/src/catalog/catalog.cpp +++ b/src/duckdb/src/catalog/catalog.cpp @@ -127,6 +127,7 @@ Catalog &Catalog::GetCatalog(ClientContext &context, const Identifier &catalog_n // Schema //===--------------------------------------------------------------------===// optional_ptr Catalog::CreateSchema(ClientContext &context, CreateSchemaInfo &info) { + CheckNestedSchemaSupport(info.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); auto supports_create_schema = SupportsCreateSchema(info); if (supports_create_schema.HasError()) { supports_create_schema.Throw(); @@ -134,6 +135,28 @@ optional_ptr Catalog::CreateSchema(ClientContext &context, CreateS return CreateSchema(GetCatalogTransaction(context), info); } +void Catalog::CheckNestedSchemaSupport(const QualifiedName &name, CatalogType type) const { + if (SupportsNestedSchemas()) { + return; + } + auto &path = name.Path(); + auto end = path.size(); + if (type != CatalogType::SCHEMA_ENTRY && end > 0) { + end--; + } + idx_t schema_count = 0; + for (idx_t i = end > 1 ? 1 : 0; i < end; i++) { + if (!path[i].empty() && ++schema_count > 1) { + while (path[end - 1].empty()) { + end--; + } + auto schema_path = + QualifiedName::FromPath(vector(path.begin() + 1, path.begin() + NumericCast(end))); + throw BinderException("Catalog %s does not support nested schemas: %s", GetName(), schema_path.ToString()); + } + } +} + CatalogTransaction Catalog::GetCatalogTransaction(ClientContext &context) { return CatalogTransaction(*this, context); } @@ -438,6 +461,7 @@ struct CatalogLookup { void Catalog::DropEntry(ClientContext &context, DropInfo &info) { if (info.type == CatalogType::SCHEMA_ENTRY) { // DROP SCHEMA + CheckNestedSchemaSupport(info.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); DropSchema(context, info); return; } @@ -483,6 +507,7 @@ optional_ptr Catalog::GetSchema(CatalogTransaction transacti optional_ptr Catalog::GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup, OnEntryNotFound if_not_found) { + CheckNestedSchemaSupport(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); return LookupSchema(GetCatalogTransaction(context), schema_lookup, if_not_found); } @@ -582,6 +607,7 @@ optional_ptr Catalog::LookupSchemaPath(CatalogTransaction transaction, const EntryLookupInfo &schema_lookup, OnEntryNotFound if_not_found, const std::function(const EntryLookupInfo &)> &lookup_root) { + CheckNestedSchemaSupport(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); auto &path = schema_lookup.GetQualifiedName().Path(); optional_ptr schema; // Bound schema lookups lead with the catalog; bare lookups contain just the schema name. @@ -643,6 +669,7 @@ SchemaCatalogEntry &Catalog::GetSchema(ClientContext &context, const Identifier } SchemaCatalogEntry &Catalog::GetSchema(CatalogTransaction transaction, const EntryLookupInfo &schema_lookup) { + CheckNestedSchemaSupport(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); return *LookupSchema(transaction, schema_lookup, OnEntryNotFound::THROW_EXCEPTION); } @@ -1011,6 +1038,11 @@ CatalogException Catalog::CreateMissingEntryException(CatalogEntryRetriever &ret return CatalogException::MissingEntry(lookup_info, did_you_mean); } +CatalogEntryLookup Catalog::TryLookupEntry(CatalogTransaction transaction, const EntryLookupInfo &lookup_info) { + CheckNestedSchemaSupport(lookup_info.GetQualifiedName(), lookup_info.GetCatalogType()); + return TryLookupEntryInternal(transaction, lookup_info); +} + CatalogEntryLookup Catalog::TryLookupEntryInternal(CatalogTransaction transaction, const EntryLookupInfo &lookup_info) { if (lookup_info.GetAtClause() && !SupportsTimeTravel()) { return {nullptr, nullptr, ErrorData(BinderException("Catalog type does not support time travel"))}; @@ -1043,7 +1075,7 @@ CatalogEntryLookup Catalog::TryLookupEntry(CatalogEntryRetriever &retriever, con auto entries = GetCatalogEntries(retriever, GetName(), Identifier::InvalidSchema()); for (auto &entry : entries) { auto transaction = GetCatalogTransaction(context); - auto result = TryLookupEntryInternal( + auto result = TryLookupEntry( transaction, EntryLookupInfo(lookup_info, QualifiedName::FromCatalogSchema(GetName(), entry.GetSchemaPath(), lookup_info.GetEntryIdentifier()))); @@ -1056,7 +1088,7 @@ CatalogEntryLookup Catalog::TryLookupEntry(CatalogEntryRetriever &retriever, con } } else { auto transaction = GetCatalogTransaction(context); - auto result = TryLookupEntryInternal(transaction, lookup_info); + auto result = TryLookupEntry(transaction, lookup_info); if (result.Found()) { return result; } @@ -1184,7 +1216,7 @@ CatalogEntryLookup Catalog::TryLookupEntry(CatalogEntryRetriever &retriever, con CatalogEntryLookup result; for (auto &lookup : lookups) { auto transaction = lookup.catalog.GetCatalogTransaction(context); - result = lookup.catalog.TryLookupEntryInternal(transaction, lookup.lookup_info); + result = lookup.catalog.TryLookupEntry(transaction, lookup.lookup_info); if (result.Found()) { break; } @@ -1303,7 +1335,7 @@ CatalogEntryLookup Catalog::TryLookupDefaultTable(CatalogEntryRetriever &retriev EntryLookupInfo info(CatalogType::TABLE_ENTRY, QualifiedName(catalog_by_name->GetName(), table_schema, table_name), at_clause, context); - return catalog_by_name->TryLookupEntryInternal(transaction, info); + return catalog_by_name->TryLookupEntry(transaction, info); } return {nullptr, nullptr, ErrorData()}; @@ -1325,7 +1357,7 @@ CatalogEntryLookup Catalog::TryLookupDefaultSchema(CatalogEntryRetriever &retrie auto transaction = catalog_entry->GetCatalogTransaction(retriever.GetContext()); EntryLookupInfo default_schema_lookup( lookup_info, QualifiedName(catalog_entry->GetName(), *default_schema, lookup_info.GetEntryIdentifier())); - auto result = catalog_entry->TryLookupEntryInternal(transaction, default_schema_lookup); + auto result = catalog_entry->TryLookupEntry(transaction, default_schema_lookup); if (result.Found() || result.error.HasError()) { return result; } diff --git a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp index 4125e4421..ceecad0c2 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/enum_util.hpp" #include "duckdb/common/exception/transaction_exception.hpp" #include "duckdb/common/index_map.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/execution/index/art/art.hpp" @@ -51,83 +52,10 @@ IndexStorageInfo GetIndexInfo(const IndexConstraintType type, const bool v1_0_0_ } static void CheckTypeIsSupported(const LogicalType &logical_type, AttachedDatabase &db) { - TypeVisitor::Contains(logical_type, [&](const LogicalType &type) { - if (type.IsAggregateState()) { - const auto storage_version = db.GetStorageManager().GetStorageVersion(); - - if (storage_version < StorageVersion::V2_0_0) { - auto required = GetStorageVersionName(StorageVersion::V2_0_0, false); - auto current = GetStorageVersionName(storage_version, false); - - throw InvalidInputException("Aggregate state columns are not supported in storage versions prior to %s " - "(database %s is using storage version %s)", - required, db.GetName(), current); - } - return false; - } - switch (type.id()) { - case LogicalTypeId::TYPE: { - throw InvalidInputException("A table cannot be created with a 'TYPE' column"); - } break; - case LogicalTypeId::STRUCT: { - const auto storage_version = db.GetStorageManager().GetStorageVersion(); - - if (storage_version < StorageVersion::V2_0_0 && StructType::GetChildCount(type) == 0) { - auto required = GetStorageVersionName(StorageVersion::V2_0_0, false); - auto current = GetStorageVersionName(storage_version, false); - - throw InvalidInputException("Empty STRUCT columns are not supported in storage versions prior to %s " - "(database %s is using storage version %s)", - required, db.GetName(), current); - } - } break; - case LogicalTypeId::TUPLE: { - // TUPLEs are stored as unnamed STRUCTs on disk, which older engines reject - gate creation to v2.0.0+ - // existing unnamed STRUCTs (deserialized as TUPLE while loading an older file) must stay attachable - const auto storage_version = db.GetStorageManager().GetStorageVersion(); - - if (storage_version < StorageVersion::V2_0_0 && db.GetStorageManager().IsLoaded()) { - auto required = GetStorageVersionName(StorageVersion::V2_0_0, false); - auto current = GetStorageVersionName(storage_version, false); - - throw InvalidInputException("TUPLE columns are not supported in storage versions prior to %s " - "(database %s is using storage version %s)", - required, db.GetName(), current); - } - } break; - case LogicalTypeId::VARIANT: { - const auto storage_version = db.GetStorageManager().GetStorageVersion(); - - if (storage_version < Variant::VERSION_ADDED) { - auto required = GetStorageVersionName(Variant::VERSION_ADDED, false); - auto current = GetStorageVersionName(storage_version, false); - - throw InvalidInputException("VARIANT columns are not supported in storage versions prior to %s " - "(database %s is using storage version %s)", - required, db.GetName(), current); - } - } break; - case LogicalTypeId::GEOMETRY: { - const auto storage_version = db.GetStorageManager().GetStorageVersion(); - - if (GeoType::HasCRS(type) && storage_version < Geometry::VERSION_ADDED) { - auto required = GetStorageVersionName(Geometry::VERSION_ADDED, false); - auto current = GetStorageVersionName(storage_version, false); - - // TODO: Turn this into a hard error - auto &logger = Logger::Get(db.GetDatabase()); - logger.WriteLog(DefaultLogType::NAME, LogLevel::LOG_WARNING, - "GEOMETRY columns with coordinate reference system identifiers are not supported in " - "storage versions prior " - "to %s (database %s is using storage version %s). CRS will not be persisted.", - required, db.GetName(), current); - } - } break; - default: - break; - } - return false; - }); + if (TypeVisitor::Contains(logical_type, LogicalTypeId::TYPE)) { + throw InvalidInputException("A table cannot be created with a 'TYPE' column"); + } + db.GetStorageManager().CheckTypeIsSupported(logical_type); } static void SetAlterDependencies(ClientContext &context, BoundCreateTableInfo &info, AlterInfo &alter_info) { @@ -174,6 +102,23 @@ DuckTableEntry::DuckTableEntry(Catalog &catalog, SchemaCatalogEntry &schema, Bou return; } + // the default, generated and check expressions are written to the catalog, as are the generated column types + auto &storage_manager = catalog.GetAttached().GetStorageManager(); + for (auto &col_def : columns.Logical()) { + if (col_def.Generated()) { + storage_manager.CheckDecimalWidthIsSupported(col_def.Type()); + storage_manager.CheckExpressionDecimalsAreSupported(col_def.GeneratedExpression()); + } + if (col_def.HasDefaultValue()) { + storage_manager.CheckExpressionDecimalsAreSupported(col_def.DefaultValue()); + } + } + for (auto &constraint : constraints) { + if (constraint->type == ConstraintType::CHECK) { + storage_manager.CheckExpressionDecimalsAreSupported(*constraint->Cast().expression); + } + } + // create the physical storage vector column_defs; for (auto &col_def : columns.Physical()) { diff --git a/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp index de51aa530..835c3c9c2 100644 --- a/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp @@ -101,9 +101,10 @@ unique_ptr TableCatalogEntry::GetInfo() const { // carry the full (possibly nested) schema path: [catalog, schema_path..., name] result->SetQualifiedName(schema.GetQualifiedName(name)); result->columns = GetColumns().Copy(); - result->constraints.reserve(constraints.size()); + auto &table_constraints = GetConstraints(); + result->constraints.reserve(table_constraints.size()); result->dependencies = dependencies; - std::for_each(constraints.begin(), constraints.end(), + std::for_each(table_constraints.begin(), table_constraints.end(), [&result](const unique_ptr &c) { result->constraints.emplace_back(c->Copy()); }); result->temporary = temporary; result->internal = internal; @@ -311,7 +312,7 @@ void TableCatalogEntry::BindUpdateConstraints(Binder &binder, LogicalGet &get, L // suppose we have a constraint CHECK(i + j < 10); now we need both i and j to check the constraint // if we are only updating one of the two columns we add the other one to the UPDATE set // with a "useless" update (i.e. i=i) so we can verify that the CHECK constraint is not violated - auto bound_constraints = binder.BindConstraints(constraints, name, GetColumns()); + auto bound_constraints = binder.BindConstraints(GetConstraints(), name, GetColumns()); for (auto &constraint : bound_constraints) { if (constraint->type == ConstraintType::CHECK) { auto &check = constraint->Cast(); diff --git a/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp index d6b0b9367..a3c1d870f 100644 --- a/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp @@ -9,6 +9,8 @@ #include "duckdb/common/limits.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/main/attached_database.hpp" +#include "duckdb/storage/storage_manager.hpp" namespace duckdb { @@ -45,6 +47,23 @@ ViewCatalogEntry::ViewCatalogEntry(Catalog &catalog, SchemaCatalogEntry &schema, Initialize(info); } +//! Whether the column types of a view can be stored in its database. A view with a wide DECIMAL result in a database +//! written before wide decimals is stored without types, like a view that was never bound, so that older engines read +//! it and bind it by their rules. +static bool CanStoreViewTypes(const Catalog &catalog, const vector &types) { + auto &db = catalog.GetAttached(); + if (!db.HasStorageManager()) { + return true; + } + auto &storage_manager = db.GetStorageManager(); + for (auto &type : types) { + if (!storage_manager.GetUnsupportedDecimalWidthReason(type).empty()) { + return false; + } + } + return true; +} + unique_ptr ViewCatalogEntry::GetInfo() const { auto result = make_uniq(); result->SetQualifiedName(schema.GetQualifiedName(name)); @@ -53,7 +72,7 @@ unique_ptr ViewCatalogEntry::GetInfo() const { result->aliases = aliases; result->security_type = security_type; auto view_columns = GetColumnInfo(); - if (view_columns) { + if (view_columns && CanStoreViewTypes(ParentCatalog(), view_columns->types)) { result->names = view_columns->names; result->types = view_columns->types; } diff --git a/src/duckdb/src/catalog/catalog_search_path.cpp b/src/duckdb/src/catalog/catalog_search_path.cpp index a5117c56a..0e24488c0 100644 --- a/src/duckdb/src/catalog/catalog_search_path.cpp +++ b/src/duckdb/src/catalog/catalog_search_path.cpp @@ -11,6 +11,7 @@ #include "duckdb/main/extension_callback_manager.hpp" #include "duckdb/common/exception/parser_exception.hpp" +#include "duckdb/parser/qualified_name.hpp" namespace duckdb { @@ -35,6 +36,10 @@ vector CatalogSearchEntry::GetSchemaPath() const { return result; } +string CatalogSearchEntry::GetSchemaName() const { + return IsNested() ? QualifiedName::FromPath(GetSchemaPath()).ToString() : schema.GetIdentifierName(); +} + string CatalogSearchEntry::ToString() const { string result; if (!catalog.empty()) { @@ -68,8 +73,7 @@ string CatalogSearchEntry::ListToString(const vector &input) } CatalogSearchEntry CatalogSearchEntry::ParseInternal(const string &input, idx_t &idx) { - string catalog; - string schema; + vector components; string entry; bool finished = false; normal: @@ -95,16 +99,7 @@ CatalogSearchEntry CatalogSearchEntry::ParseInternal(const string &input, idx_t if (entry.empty()) { throw ParserException("Unexpected dot - empty CatalogSearchEntry"); } - if (schema.empty()) { - // if we parse one entry it is the schema - schema = std::move(entry); - } else if (catalog.empty()) { - // if we parse two entries it is [catalog.schema] - catalog = std::move(schema); - schema = std::move(entry); - } else { - throw ParserException("Too many dots - expected [schema] or [catalog.schema] for CatalogSearchEntry"); - } + components.emplace_back(std::move(entry)); entry = ""; idx++; if (finished) { @@ -112,10 +107,12 @@ CatalogSearchEntry CatalogSearchEntry::ParseInternal(const string &input, idx_t } goto normal; final: - if (schema.empty()) { - throw ParserException("Unexpected end of entry - empty CatalogSearchEntry"); + if (components.size() == 1) { + return CatalogSearchEntry(Identifier(), std::move(components[0])); } - return CatalogSearchEntry(Identifier(std::move(catalog)), Identifier(std::move(schema))); + auto catalog = std::move(components[0]); + components.erase(components.begin()); + return FromSchemaPath(std::move(catalog), std::move(components)); } CatalogSearchEntry CatalogSearchEntry::Parse(const string &input) { @@ -169,20 +166,43 @@ void CatalogSearchPath::Set(vector new_paths, CatalogSetPath if (set_type == CatalogSetPathType::SET_SCHEMA && new_paths.size() != 1) { throw CatalogException("%s can set only 1 schema. This has %d", GetSetName(set_type), new_paths.size()); } - for (auto &path : new_paths) { + for (idx_t path_idx = 0; path_idx < new_paths.size(); path_idx++) { + auto &path = new_paths[path_idx]; if (set_type == CatalogSetPathType::SET_DIRECTLY) { if (path.GetCatalog().empty() || path.GetSchema().empty()) { throw InternalException("SET_WITHOUT_VERIFICATION requires a fully qualified set path"); } continue; } - auto schema_entry = - Catalog::GetSchema(context, path.GetCatalog(), path.GetSchema(), OnEntryNotFound::RETURN_NULL); + auto catalog_name = path.GetCatalog(); + auto schema_path = path.GetSchemaPath(); + if (!catalog_name.empty() && !Catalog::GetCatalogEntry(context, catalog_name)) { + schema_path.insert(schema_path.begin(), catalog_name); + catalog_name = Identifier(); + } + auto lookup_catalog = catalog_name.empty() ? GetDefaultCatalog(schema_path[0]) : catalog_name; + if (lookup_catalog.empty()) { + lookup_catalog = DatabaseManager::TryGetDefaultDatabase(context); + } + optional_ptr schema_entry; + if (!lookup_catalog.empty()) { + schema_entry = Catalog::GetSchema(context, lookup_catalog, schema_path, OnEntryNotFound::RETURN_NULL); + } if (schema_entry) { - // we are setting a schema - update the catalog and schema - if (path.GetCatalog().empty()) { - path.SetCatalog(GetDefault().GetCatalog()); + if (catalog_name.empty()) { + catalog_name = GetDefault().GetCatalog(); + // Keep shorthand only when the new default catalog still resolves it to the same schema. + auto default_catalog = path_idx == 0 || new_paths[0].GetCatalog().empty() + ? DatabaseManager::TryGetDefaultDatabase(context) + : new_paths[0].GetCatalog(); + auto &resolved_catalog = schema_entry->ParentCatalog(); + if (!resolved_catalog.IsSystemCatalog() && + (!catalog_name.empty() || resolved_catalog.GetName() != default_catalog)) { + catalog_name = resolved_catalog.GetName(); + } } + path = CatalogSearchEntry::FromSchemaPath(std::move(catalog_name), std::move(schema_path), + path.DefaultSchemaPrecedence()); continue; } // only schema supplied - check if this is a catalog instead @@ -200,15 +220,6 @@ void CatalogSearchPath::Set(vector new_paths, CatalogSetPath } } } - if (!path.GetCatalog().empty()) { - // "a.b" can also name a nested schema - give a clearer error in that case - vector nested_path {path.GetCatalog(), path.GetSchema()}; - if (Catalog::GetSchema(context, Identifier(), nested_path, OnEntryNotFound::RETURN_NULL)) { - throw NotImplementedException("%s: \"%s\" is a nested schema - nested schemas cannot be used in the " - "search path", - GetSetName(set_type), path.ToString()); - } - } throw CatalogException("%s: No catalog + schema named \"%s\" found.", GetSetName(set_type), path.ToString()); } if (set_type == CatalogSetPathType::SET_SCHEMA) { @@ -389,7 +400,7 @@ void CatalogSearchPath::SetPathsInternal(vector new_paths) { bool CatalogSearchPath::SchemaInSearchPath(ClientContext &context, const Identifier &catalog_name, const Identifier &schema_name) const { for (auto &path : paths) { - if (path.GetSchema() != schema_name || path.IsNested()) { + if (Identifier(path.GetSchemaName()) != schema_name) { continue; } if (path.GetCatalog() == catalog_name) { diff --git a/src/duckdb/src/catalog/default/default_types.cpp b/src/duckdb/src/catalog/default/default_types.cpp index 4e45d7bce..abe90a6f0 100644 --- a/src/duckdb/src/catalog/default/default_types.cpp +++ b/src/duckdb/src/catalog/default/default_types.cpp @@ -51,13 +51,18 @@ LogicalType BindDecimalType(BindLogicalTypeInput &input) { 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", - Decimal::MAX_WIDTH_DECIMAL); + if (width < 1) { + throw BinderException(input.GetLocation(0), "DECIMAL type width must be at least 1"); } if (scale > width) { throw BinderException(input.GetLocation(1), "DECIMAL type scale cannot be greater than width"); } + const auto limit = input.GetDecimalWidthLimit(); + if (width > limit.width) { + throw BinderException(input.GetLocation(0), + "DECIMAL type width %u exceeds the maximum DECIMAL width of %u (%s)", width, limit.width, + limit.hint); + } return LogicalType::DECIMAL(width, scale); } @@ -65,8 +70,8 @@ void RegisterDecimalConstructors(TypeConstructorSet &set) { set.AddFunction(TypeConstructor(TypeConstructor::Signature(), BindDefaultDecimalType)); auto signature = TypeConstructor::Signature(); - signature.AddParameter("width", LogicalType::UTINYINT); - signature.AddParameter("scale", LogicalType::UTINYINT, Value::UTINYINT(0)); + signature.AddParameter("width", LogicalType::UINTEGER); + signature.AddParameter("scale", LogicalType::UINTEGER, Value::UINTEGER(0)); set.AddFunction(TypeConstructor(std::move(signature), BindDecimalType)); } diff --git a/src/duckdb/src/catalog/similar_catalog_entry.cpp b/src/duckdb/src/catalog/similar_catalog_entry.cpp index 918216ded..801c68665 100644 --- a/src/duckdb/src/catalog/similar_catalog_entry.cpp +++ b/src/duckdb/src/catalog/similar_catalog_entry.cpp @@ -6,6 +6,9 @@ namespace duckdb { string SimilarCatalogEntry::GetQualifiedName(bool qualify_catalog, bool qualify_schema) const { D_ASSERT(Found()); + if (schema->GetParentSchema()) { + return schema->GetQualifiedName(Identifier(name)).ToString(); + } string result; if (qualify_catalog) { result += schema->catalog.GetName().GetIdentifierName(); diff --git a/src/duckdb/src/common/arrow/arrow_appender.cpp b/src/duckdb/src/common/arrow/arrow_appender.cpp index 33ca0a92b..badb0debc 100644 --- a/src/duckdb/src/common/arrow/arrow_appender.cpp +++ b/src/duckdb/src/common/arrow/arrow_appender.cpp @@ -10,9 +10,34 @@ #include "duckdb/common/arrow/appender/list.hpp" #include "duckdb/function/table/arrow/arrow_duck_schema.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/common/types/decimal_helper.hpp" namespace duckdb { +//! A 32-byte little-endian two's complement Arrow decimal256 value +struct ArrowDecimal256 { + uint64_t words[4]; +}; + +//! Converts the BIGNUM blob of a wide decimal into an Arrow decimal256 +struct ArrowWideDecimalConverter { + template + static TGT Operation(SRC input) { + TGT result; + DecimalHelper::ToTwosComplement(input, data_ptr_cast(&result), sizeof(TGT), false); + return result; + } + + static bool SkipNulls() { + return true; + } + + template + static void SetNull(TGT &value) { + memset(&value, 0, sizeof(TGT)); + } +}; + //===--------------------------------------------------------------------===// // ArrowAppender //===--------------------------------------------------------------------===// @@ -251,6 +276,11 @@ static void InitializeFunctionPointers(ArrowAppendData &append_data, const Logic case PhysicalType::INT128: InitializeAppenderForType>(append_data); break; + case PhysicalType::VARCHAR: + // wide decimals become Arrow decimal256 (the schema conversion rejects widths above 76 digits) + InitializeAppenderForType>( + append_data); + break; default: throw InternalException("Unsupported internal decimal type"); } diff --git a/src/duckdb/src/common/arrow/arrow_converter.cpp b/src/duckdb/src/common/arrow/arrow_converter.cpp index 1188752e2..c535c2b74 100644 --- a/src/duckdb/src/common/arrow/arrow_converter.cpp +++ b/src/duckdb/src/common/arrow/arrow_converter.cpp @@ -242,8 +242,22 @@ void SetArrowFormat(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child, co child.format = "tin"; break; case LogicalTypeId::DECIMAL: { - uint32_t width, scale, bit_width; - if (options.arrow_output_version <= ArrowFormatVersion::V1_4) { + uint32_t width, scale; + idx_t bit_width; + if (type.InternalType() == PhysicalType::VARCHAR) { + // wide decimals become Arrow decimal256 (format version 1.1), which holds up to 76 digits + if (options.arrow_output_version < ArrowFormatVersion::V1_1) { + throw NotImplementedException("Cannot convert %s to Arrow format version 1.0: decimals wider than 38 " + "digits require decimal256, SET arrow_output_version to 1.1 or later", + type.ToString()); + } + if (DecimalType::GetWidth(type) > 76) { + throw NotImplementedException( + "Cannot convert %s to Arrow: Arrow decimals support at most 76 digits (decimal256)", + type.ToString()); + } + bit_width = 256; + } else if (options.arrow_output_version <= ArrowFormatVersion::V1_4) { // Before version 1.4 all decimals were int128 bit_width = 128; } else { diff --git a/src/duckdb/src/common/bignum.cpp b/src/duckdb/src/common/bignum.cpp index db441855b..b2ad96404 100644 --- a/src/duckdb/src/common/bignum.cpp +++ b/src/duckdb/src/common/bignum.cpp @@ -496,11 +496,7 @@ constexpr bignum_twodigit_t DIGIT_MASK = BASE - 1; constexpr idx_t INTERRUPT_CHECK_INTERVAL = idx_t(1) << 20; void AccountWork(BignumArithmeticState &state, idx_t work) { - state.work_since_interrupt_check += work; - if (state.work_since_interrupt_check >= INTERRUPT_CHECK_INTERVAL) { - state.work_since_interrupt_check = 0; - state.context.InterruptCheck(); - } + state.AccountWork(work); } void TrimMagnitude(bignum_magnitude_t &digits) { @@ -897,6 +893,36 @@ void DivModMagnitudes(BignumArithmeticState &state, const bignum_magnitude_t &di } // namespace +BignumArithmeticState::BignumArithmeticState(optional_ptr client_context) + : context(client_context ? &client_context->GetContext() : nullptr) { +} + +void BignumArithmeticState::AccountWork(idx_t work) { + if (!context) { + return; + } + work_since_interrupt_check += work; + if (work_since_interrupt_check >= INTERRUPT_CHECK_INTERVAL) { + work_since_interrupt_check = 0; + // the calls are already a millisecond of work apart, so the deadline is read on every one of them + auto client_context = context->TryGetClientContext(); + if (client_context) { + client_context->BlockingInterruptCheck(); + } + } +} + +void BignumIntermediate::MultiplyMagnitudes(BignumArithmeticState &state, const unsafe_vector &lhs, + const unsafe_vector &rhs, + unsafe_vector &result) { + if (lhs.empty() || rhs.empty()) { + result.clear(); + return; + } + duckdb::MultiplyMagnitudes(state, lhs, rhs, result); + TrimMagnitude(result); +} + string_t BignumIntermediate::Multiply(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, const BignumIntermediate &rhs) { const bool is_result_negative = lhs.is_negative != rhs.is_negative; @@ -940,4 +966,22 @@ bool BignumIntermediate::TryDivMod(StringHeap &heap, BignumArithmeticState &stat return true; } +bool BignumIntermediate::TryDivMod(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, + const BignumIntermediate &rhs, string_t "ient_result, + string_t &remainder_result) { + auto &lhs_digits = state.lhs_digits; + auto &rhs_digits = state.rhs_digits; + auto "ient = state.result_digits; + auto &remainder = state.remainder_digits; + GetMagnitude(lhs, lhs_digits); + GetMagnitude(rhs, rhs_digits); + if (rhs_digits.empty()) { + return false; + } + DivModMagnitudes(state, lhs_digits, rhs_digits, quotient, remainder, true); + quotient_result = WriteMagnitude(heap, quotient, lhs.is_negative != rhs.is_negative); + remainder_result = WriteMagnitude(heap, remainder, lhs.is_negative); + return true; +} + } // namespace duckdb diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 41a812a93..6de99a027 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -110,6 +110,7 @@ #include "duckdb/common/types/column/partitioned_column_data.hpp" #include "duckdb/common/types/conflict_manager.hpp" #include "duckdb/common/types/date.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/geometry.hpp" #include "duckdb/common/types/geometry_crs.hpp" #include "duckdb/common/types/hyperloglog.hpp" @@ -1976,6 +1977,27 @@ DecimalBitWidth EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetDecimalBitWidthValues(), 4, "DecimalBitWidth", value)); } +const StringUtil::EnumStringLiteral *GetDecimalRoundingValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(DecimalRounding::TRUNCATE), "TRUNCATE" }, + { static_cast(DecimalRounding::FLOOR), "FLOOR" }, + { static_cast(DecimalRounding::CEIL), "CEIL" }, + { static_cast(DecimalRounding::HALF_AWAY_FROM_ZERO), "HALF_AWAY_FROM_ZERO" }, + { static_cast(DecimalRounding::HALF_TO_EVEN), "HALF_TO_EVEN" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(DecimalRounding value) { + return StringUtil::EnumToString(GetDecimalRoundingValues(), 5, "DecimalRounding", static_cast(value)); +} + +template<> +DecimalRounding EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetDecimalRoundingValues(), 5, "DecimalRounding", value)); +} + const StringUtil::EnumStringLiteral *GetDefaultOrderByNullTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(DefaultOrderByNullType::INVALID), "INVALID" }, @@ -6626,19 +6648,20 @@ const StringUtil::EnumStringLiteral *GetStatisticsTypeValues() { { static_cast(StatisticsType::BASE_STATS), "BASE_STATS" }, { static_cast(StatisticsType::ARRAY_STATS), "ARRAY_STATS" }, { static_cast(StatisticsType::GEOMETRY_STATS), "GEOMETRY_STATS" }, - { static_cast(StatisticsType::VARIANT_STATS), "VARIANT_STATS" } + { static_cast(StatisticsType::VARIANT_STATS), "VARIANT_STATS" }, + { static_cast(StatisticsType::BIGNUM_STATS), "BIGNUM_STATS" } }; return values; } template<> const char* EnumUtil::ToChars(StatisticsType value) { - return StringUtil::EnumToString(GetStatisticsTypeValues(), 8, "StatisticsType", static_cast(value)); + return StringUtil::EnumToString(GetStatisticsTypeValues(), 9, "StatisticsType", static_cast(value)); } template<> StatisticsType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetStatisticsTypeValues(), 8, "StatisticsType", value)); + return static_cast(StringUtil::StringToEnum(GetStatisticsTypeValues(), 9, "StatisticsType", value)); } const StringUtil::EnumStringLiteral *GetStatsInfoValues() { diff --git a/src/duckdb/src/common/operator/cast_operators.cpp b/src/duckdb/src/common/operator/cast_operators.cpp index 1345e9a66..44096199d 100644 --- a/src/duckdb/src/common/operator/cast_operators.cpp +++ b/src/duckdb/src/common/operator/cast_operators.cpp @@ -25,6 +25,8 @@ #include "duckdb/common/types.hpp" #include "fast_float/fast_float.h" #include "duckdb/common/types/bit.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/operator/integer_cast_operator.hpp" #include "duckdb/common/operator/double_cast_operator.hpp" #include "duckdb/planner/expression.hpp" @@ -2516,6 +2518,11 @@ string_t StringCastFromDecimal::Operation(hugeint_t input, uint32_t width, uint3 return DecimalToString::Format(input, width, scale, heap); } +template <> +string_t StringCastFromDecimal::Operation(bignum_t input, uint32_t width, uint32_t scale, StringHeap &heap) { + return heap.AddString(Decimal::ToString(input, width, scale)); +} + //===--------------------------------------------------------------------===// // Decimal Casts //===--------------------------------------------------------------------===// @@ -3426,4 +3433,373 @@ bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParamete return TryCastDecimalToFloatingPoint(input, result, width, scale); } +//===--------------------------------------------------------------------===// +// Decimal Casts of the bignum_t tier (width > 38), and BIGNUM as a decimal with scale 0 +//===--------------------------------------------------------------------===// +//! The BIGNUM blob of an integer +static string IntegerToBignumBlob(hugeint_t value) { + return DecimalHelper::FromInteger(value); +} + +static string IntegerToBignumBlob(uhugeint_t value) { + return DecimalHelper::FromInteger(value); +} + +static string IntegerToBignumBlob(bool value) { + return DecimalHelper::FromInteger(hugeint_t(value ? 1 : 0)); +} + +template +static string IntegerToBignumBlob(SRC value) { + return DecimalHelper::FromInteger(Hugeint::Convert(value)); +} + +//! Scales an integer to the bignum_t tier, false if it does not fit the width +template +static bool TryCastIntegerToBignumDecimal(SRC input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale) { + auto unscaled = IntegerToBignumBlob(input); + string blob; + if (!DecimalHelper::TryRescale(bignum_t(string_t(unscaled)), 0, width, scale, blob, + DefaultCasts::WideDecimalCastContext(parameters))) { + string error = StringUtil::Format("Could not cast value %s to DECIMAL(%d,%d)", + ConvertToString::Operation(input), width, scale); + HandleCastError::AssignError(error, parameters); + return false; + } + result = DecimalHelper::Store(result_vector, blob); + return true; +} + +//! Scales a BIGNUM to a fixed-size decimal tier, false if it does not fit the width +template +static bool TryCastBignumToDecimal(bignum_t input, DST &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + string blob; + hugeint_t value; + if (!DecimalHelper::TryRescale(input, 0, width, scale, blob, + DefaultCasts::WideDecimalCastContext(parameters)) || + !DecimalHelper::TryToHugeint(bignum_t(string_t(blob)), value)) { + string error = StringUtil::Format("Could not cast value %s to DECIMAL(%d,%d)", Bignum::BignumToVarchar(input), + width, scale); + HandleCastError::AssignError(error, parameters); + return false; + } + result = Cast::Operation(value); + return true; +} + +template +static bool TryCastDoubleToBignumDecimal(SRC input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + string blob; + if (!DecimalHelper::TryFromDouble(static_cast(input), width, scale, blob, + DefaultCasts::WideDecimalCastContext(parameters))) { + string error = StringUtil::Format("Could not cast value %f to DECIMAL(%d,%d)", input, width, scale); + HandleCastError::AssignError(error, parameters); + return false; + } + result = DecimalHelper::Store(result_vector, blob); + return true; +} + +template +static bool TryCastStringToBignumDecimal(string_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale) { + string blob; + if (!DecimalHelper::TryParse(input.GetData(), input.GetSize(), width, scale, blob, decimal_separator, + DefaultCasts::WideDecimalCastContext(parameters))) { + string error = StringUtil::Format("Could not convert string \"%s\" to DECIMAL(%d,%d)", input.GetString(), + (int)width, (int)scale); + HandleCastError::AssignError(error, parameters); + return false; + } + result = DecimalHelper::Store(result_vector, blob); + return true; +} + +//! Rounds a decimal of the bignum_t tier to an integer +static string RoundBignumDecimal(bignum_t input, uint32_t scale, optional_ptr context = nullptr) { + return DecimalHelper::Rescale(input, scale, 0, context); +} + +template +static bool TryCastBignumDecimalToNumeric(bignum_t input, DST &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + auto rounded = RoundBignumDecimal(input, scale, DefaultCasts::WideDecimalCastContext(parameters)); + bool strict = false; + if (!Bignum::BignumToInt(bignum_t(string_t(rounded)), result, strict)) { + string error = StringUtil::Format("Failed to cast decimal value %s to type %s", + DecimalHelper::ToString(input, width, scale), GetTypeId()); + HandleCastError::AssignError(error, parameters); + return false; + } + return true; +} + +template +static bool TryCastBignumDecimalToFloatingPoint(bignum_t input, DST &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + auto context = DefaultCasts::WideDecimalCastContext(parameters); + if (!DecimalHelper::TryToFloating(input, scale, result, context)) { + string error = + StringUtil::Format("Casting value \"%s\" to type %s failed: value is out of range!", + DecimalHelper::ToString(input, width, scale, context), GetTypeId()); + HandleCastError::AssignError(error, parameters); + return false; + } + return true; +} + +//! A fixed-size decimal rounds to an integer BIGNUM +template +static bool CastDecimalToBignum(SRC input, bignum_t &result, Vector &result_vector, uint32_t scale) { + auto unscaled = IntegerToBignumBlob(hugeint_t(input)); + result = DecimalHelper::Store(result_vector, RoundBignumDecimal(bignum_t(string_t(unscaled)), scale)); + return true; +} + +// Decimal -> bignum_t +template <> +bool TryCastToDecimal::Operation(bool input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(int8_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(int16_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(int32_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(int64_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(hugeint_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(uhugeint_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(uint8_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(uint16_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(uint32_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(uint64_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastIntegerToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(float input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastDoubleToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(double input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastDoubleToBignumDecimal(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(string_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return TryCastStringToBignumDecimal<'.'>(input, result, result_vector, parameters, width, scale); +} + +template <> +bool TryCastToDecimalCommaSeparated::Operation(string_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale) { + return TryCastStringToBignumDecimal<','>(input, result, result_vector, parameters, width, scale); +} + +// BIGNUM -> Decimal +template <> +bool TryCastToDecimal::Operation(bignum_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumToDecimal(input, result, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(bignum_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumToDecimal(input, result, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(bignum_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumToDecimal(input, result, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(bignum_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumToDecimal(input, result, parameters, width, scale); +} + +template <> +bool TryCastToDecimal::Operation(bignum_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + string blob; + if (!DecimalHelper::TryRescale(input, 0, width, scale, blob, + DefaultCasts::WideDecimalCastContext(parameters))) { + string error = StringUtil::Format("Could not cast value %s to DECIMAL(%d,%d)", Bignum::BignumToVarchar(input), + width, scale); + HandleCastError::AssignError(error, parameters); + return false; + } + result = DecimalHelper::Store(result_vector, blob); + return true; +} + +// bignum_t -> Numeric +template <> +bool TryCastFromDecimal::Operation(bignum_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + result = !DecimalHelper::IsZero(input); + return true; +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToNumeric(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToFloatingPoint(input, result, parameters, width, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale) { + return TryCastBignumDecimalToFloatingPoint(input, result, parameters, width, scale); +} + +// Decimal -> BIGNUM +template <> +bool TryCastFromDecimal::Operation(int16_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return CastDecimalToBignum(input, result, result_vector, scale); +} + +template <> +bool TryCastFromDecimal::Operation(int32_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return CastDecimalToBignum(input, result, result_vector, scale); +} + +template <> +bool TryCastFromDecimal::Operation(int64_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return CastDecimalToBignum(input, result, result_vector, scale); +} + +template <> +bool TryCastFromDecimal::Operation(hugeint_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + return CastDecimalToBignum(input, result, result_vector, scale); +} + +template <> +bool TryCastFromDecimal::Operation(bignum_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + result = DecimalHelper::Store(result_vector, RoundBignumDecimal(input, scale)); + return true; +} + } // namespace duckdb diff --git a/src/duckdb/src/common/types.cpp b/src/duckdb/src/common/types.cpp index dada262ca..1ff8f3619 100644 --- a/src/duckdb/src/common/types.cpp +++ b/src/duckdb/src/common/types.cpp @@ -156,17 +156,18 @@ static bool TryGetPhysicalType(LogicalTypeId id, const LogicalTypeInfo &info, Ph break; } auto width = info.Cast().width; - if (width <= Decimal::MAX_WIDTH_INT16) { + if (Decimal::IsWide(width)) { + // wide decimals hold their unscaled value as a BIGNUM blob + result = PhysicalType::VARCHAR; + } else if (width <= Decimal::MAX_WIDTH_INT16) { result = PhysicalType::INT16; } else if (width <= Decimal::MAX_WIDTH_INT32) { result = PhysicalType::INT32; } else if (width <= Decimal::MAX_WIDTH_INT64) { result = PhysicalType::INT64; - } else if (width <= Decimal::MAX_WIDTH_INT128) { - result = PhysicalType::INT128; } else { - throw InternalException("Decimal has a width of %d which is bigger than the maximum supported width of %d", - width, DecimalType::MaxWidth()); + D_ASSERT(width <= Decimal::MAX_WIDTH_INT128); + result = PhysicalType::INT128; } return true; } @@ -747,8 +748,9 @@ LogicalTypeId TransformStringToLogicalTypeId(const string &str) { return type; } -LogicalType TransformStringToLogicalType(const string &str, ClientContext &context) { - return TypeManager::Get(context).ParseLogicalType(str, context); +LogicalType TransformStringToLogicalType(const string &str, ClientContext &context, + optional_ptr decimal_width_limit) { + return TypeManager::Get(context).ParseLogicalType(str, context, decimal_width_limit); } bool LogicalType::IsIntegral() const { @@ -891,9 +893,7 @@ bool LogicalType::IsComplete() const { return type.GetTypeInfo().Cast().child_types.empty(); case LogicalTypeInfoType::DECIMAL_TYPE_INFO: { // A well-formed decimal is not incomplete - auto is_well_formed = DecimalType::GetWidth(type) >= 1 && - DecimalType::GetWidth(type) <= Decimal::MAX_WIDTH_DECIMAL && - DecimalType::GetScale(type) <= DecimalType::GetWidth(type); + auto is_well_formed = Decimal::IsValidWidthScale(DecimalType::GetWidth(type), DecimalType::GetScale(type)); return !is_well_formed; } default: @@ -1009,13 +1009,14 @@ bool LogicalType::GetDecimalProperties(uint32_t &width, uint32_t &scale) const { } //! Grows Decimal width/scale when appropriate -static LogicalType DecimalSizeCheck(const LogicalType &left, const LogicalType &right) { +static LogicalType DecimalSizeCheck(const LogicalTypeResolver &logical_type_resolver, const LogicalType &left, + const LogicalType &right) { D_ASSERT(left.id() == LogicalTypeId::DECIMAL || right.id() == LogicalTypeId::DECIMAL); D_ASSERT(left.id() != right.id()); //! Make sure the 'right' is the DECIMAL type if (left.id() == LogicalTypeId::DECIMAL) { - return DecimalSizeCheck(right, left); + return DecimalSizeCheck(logical_type_resolver, right, left); } auto width = DecimalType::GetWidth(right); auto scale = DecimalType::GetScale(right); @@ -1029,12 +1030,13 @@ static LogicalType DecimalSizeCheck(const LogicalType &left, const LogicalType & D_ASSERT(other_scale == 0); const auto effective_width = width - scale; if (other_width > effective_width) { - uint32_t new_width = other_width + scale; + idx_t new_width = idx_t(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(); + const idx_t width_limit = logical_type_resolver.GetDecimalWidthLimit().ResultWidth(width); + if (new_width > width_limit) { + new_width = width_limit; } - return LogicalType::DECIMAL(new_width, scale); + return LogicalType::DECIMAL(NumericCast(new_width), scale); } return right; } @@ -1087,14 +1089,16 @@ LogicalType LogicalType::NormalizeType(const LogicalType &type) { static bool TryGetMaxLogicalTypeInternal(LogicalTypeResolver &logical_type_resolver, const LogicalType &left, const LogicalType &right, LogicalType &result); +static LogicalType ForceMaxLogicalTypeInternal(optional_ptr context, const LogicalType &left, + const LogicalType &right, + optional_ptr decimal_width_limit); class ForceLogicalTypeResolver : public LogicalTypeResolver { public: using LogicalTypeResolver::LogicalTypeResolver; bool Operation(const LogicalType &left, const LogicalType &right, LogicalType &result) override { - result = context ? LogicalType::ForceMaxLogicalType(*context, left, right) - : LogicalType::DefaultForceMaxLogicalType(left, right); + result = ForceMaxLogicalTypeInternal(context, left, right, decimal_width_limit); return true; } }; @@ -1127,7 +1131,7 @@ static bool TryCombineViaImplicitCast(LogicalTypeResolver &logical_type_resolver //! Prefer VARIANT always result = left; } else { - result = DecimalSizeCheck(left, right); + result = DecimalSizeCheck(logical_type_resolver, left, right); } } else { result = right; @@ -1142,7 +1146,7 @@ static bool TryCombineViaImplicitCast(LogicalTypeResolver &logical_type_resolver //! Prefer VARIANT always result = right; } else { - result = DecimalSizeCheck(right, left); + result = DecimalSizeCheck(logical_type_resolver, right, left); } } else { result = left; @@ -1199,13 +1203,25 @@ static bool TryGetMaxLogicalTypeInternal(LogicalTypeResolver &logical_type_resol return true; } -bool LogicalType::TryGetMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, - LogicalType &result) { +static bool TryGetMaxLogicalTypeChecked(ClientContext &context, const LogicalType &left, const LogicalType &right, + LogicalType &result, + optional_ptr decimal_width_limit) { if (Settings::Get(context)) { - result = LogicalType::ForceMaxLogicalType(context, left, right); + result = ForceMaxLogicalTypeInternal(&context, left, right, decimal_width_limit); return true; } - return TryGetMaxLogicalTypeUnchecked(context, left, right, result); + TryGetLogicalTypeResolver logical_type_resolver(&context, decimal_width_limit); + return TryGetMaxLogicalTypeInternal(logical_type_resolver, left, right, result); +} + +bool LogicalType::TryGetMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, + LogicalType &result) { + return TryGetMaxLogicalTypeChecked(context, left, right, result, nullptr); +} + +bool LogicalType::TryGetMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, + LogicalType &result, const DecimalWidthLimit &decimal_width_limit) { + return TryGetMaxLogicalTypeChecked(context, left, right, result, &decimal_width_limit); } bool LogicalType::TryGetMaxLogicalTypeUnchecked(ClientContext &context, const LogicalType &left, @@ -1323,9 +1339,10 @@ static idx_t GetLogicalTypeScore(const LogicalType &type) { } static LogicalType ForceMaxLogicalTypeInternal(optional_ptr context, const LogicalType &left, - const LogicalType &right) { + const LogicalType &right, + optional_ptr decimal_width_limit) { LogicalType result; - ForceLogicalTypeResolver logical_type_resolver(context); + ForceLogicalTypeResolver logical_type_resolver(context, decimal_width_limit); if (TryGetMaxLogicalTypeInternal(logical_type_resolver, left, right, result)) { return result; } @@ -1341,28 +1358,42 @@ static LogicalType ForceMaxLogicalTypeInternal(optional_ptr conte LogicalType LogicalType::ForceMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right) { - return ForceMaxLogicalTypeInternal(&context, left, right); + return ForceMaxLogicalTypeInternal(&context, left, right, nullptr); +} + +LogicalType LogicalType::ForceMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, + const DecimalWidthLimit &decimal_width_limit) { + return ForceMaxLogicalTypeInternal(&context, left, right, &decimal_width_limit); } LogicalType LogicalType::DefaultForceMaxLogicalType(const LogicalType &left, const LogicalType &right) { - return ForceMaxLogicalTypeInternal(nullptr, left, right); + return ForceMaxLogicalTypeInternal(nullptr, left, right, nullptr); } -LogicalType LogicalType::MaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right) { +static LogicalType MaxLogicalTypeChecked(ClientContext &context, const LogicalType &left, const LogicalType &right, + optional_ptr decimal_width_limit) { LogicalType result; - if (!TryGetMaxLogicalType(context, left, right, result)) { + if (!TryGetMaxLogicalTypeChecked(context, left, right, result, decimal_width_limit)) { throw NotImplementedException("Cannot combine types %s and %s - an explicit cast is required", left.ToString(), right.ToString()); } return result; } +LogicalType LogicalType::MaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right) { + return MaxLogicalTypeChecked(context, left, right, nullptr); +} + +LogicalType LogicalType::MaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, + const DecimalWidthLimit &decimal_width_limit) { + return MaxLogicalTypeChecked(context, left, right, &decimal_width_limit); +} + void LogicalType::Verify() const { #ifdef DEBUG switch (id()) { case LogicalTypeId::DECIMAL: - D_ASSERT(DecimalType::GetWidth(*this) >= 1 && DecimalType::GetWidth(*this) <= Decimal::MAX_WIDTH_DECIMAL); - D_ASSERT(DecimalType::GetScale(*this) <= DecimalType::GetWidth(*this)); + D_ASSERT(Decimal::IsValidWidthScale(DecimalType::GetWidth(*this), DecimalType::GetScale(*this))); break; case LogicalTypeId::STRUCT: { // verify child types @@ -1582,7 +1613,7 @@ uint32_t DecimalType::GetScale(const LogicalType &type) { } uint32_t DecimalType::MaxWidth() { - return DecimalWidth::max; + return NumericLimits::Maximum(); } static constexpr idx_t DecimalTypeInfoIndex(idx_t width, idx_t scale) { @@ -1590,16 +1621,17 @@ static constexpr idx_t DecimalTypeInfoIndex(idx_t width, idx_t scale) { } LogicalType LogicalType::DECIMAL(uint32_t width, uint32_t scale) { + // width 0 and scale > width stay constructible and are reported by IsComplete D_ASSERT(width >= scale); - if (!Decimal::IsValidWidthScale(width, scale)) { + // the shared infos cover the fixed-size tiers: wide decimals have too many widths to share, and are rare + if (!Decimal::IsValidWidthScale(width, scale) || Decimal::IsWide(width)) { return LogicalType(LogicalTypeId::DECIMAL, make_uniq(width, scale)); } - static constexpr idx_t TYPE_COUNT = - DecimalTypeInfoIndex(Decimal::MAX_WIDTH_DECIMAL, Decimal::MAX_WIDTH_DECIMAL) + 1; + static constexpr idx_t TYPE_COUNT = DecimalTypeInfoIndex(Decimal::MAX_WIDTH_INT128, Decimal::MAX_WIDTH_INT128) + 1; static const auto decimal_types = []() { // Finish allocation before immortalizing any info so failed initialization releases partial allocations. array, TYPE_COUNT> infos; - for (uint32_t width = 1; width <= Decimal::MAX_WIDTH_DECIMAL; width++) { + for (uint32_t width = 1; width <= Decimal::MAX_WIDTH_INT128; width++) { for (uint32_t scale = 0; scale <= width; scale++) { infos[DecimalTypeInfoIndex(width, scale)] = make_uniq(width, scale); } diff --git a/src/duckdb/src/common/types/bignum.cpp b/src/duckdb/src/common/types/bignum.cpp index 467ab7007..717c37f87 100644 --- a/src/duckdb/src/common/types/bignum.cpp +++ b/src/duckdb/src/common/types/bignum.cpp @@ -161,8 +161,15 @@ static inline uint64_t BignumCastParseDigits(const char *digits, idx_t count) { return value; } -//! Converts decimal digits to base 2^64 limbs, least significant first, without a zero top limb -static void BignumCastDecimalToBinary(const char *digits, idx_t count, unsafe_vector &limbs) { +static void TrimLimbs(unsafe_vector &limbs) { + while (!limbs.empty() && limbs.back() == 0) { + limbs.pop_back(); + } +} + +//! Converts decimal digits to base 2^64 limbs, least significant first, without a zero top limb (quadratic) +static void BignumCastDecimalToBinaryShort(BignumArithmeticState &state, const char *digits, idx_t count, + unsafe_vector &limbs) { limbs.clear(); // the first chunk takes the digits that remain after cutting Bignum::DECIMAL_SHIFT digits at a time from // the end @@ -171,6 +178,7 @@ static void BignumCastDecimalToBinary(const char *digits, idx_t count, unsafe_ve chunk_size = Bignum::DECIMAL_SHIFT; } for (idx_t pos = 0; pos < count; pos += chunk_size, chunk_size = Bignum::DECIMAL_SHIFT) { + state.AccountWork(limbs.size() + chunk_size); const uint64_t chunk = BignumCastParseDigits(digits + pos, chunk_size); // limbs = limbs * 10^chunk_size + chunk const uint64_t multiplier = BIGNUM_CAST_POWERS_OF_TEN[chunk_size]; @@ -184,6 +192,84 @@ static void BignumCastDecimalToBinary(const char *digits, idx_t count, unsafe_ve } } +//! Below this number of decimal digits, a string is converted to limbs chunk by chunk +static constexpr idx_t PARSE_THRESHOLD = 1024; + +//! Splits base 2^64 limbs into the digits of the multiplication kernels, which are halves of a limb without a 128-bit +//! integer type (see BignumLimb) +static void BignumCastLimbsToDigits(const unsafe_vector &limbs, unsafe_vector &digits) { + digits.clear(); + for (auto limb : limbs) { + for (idx_t shift = 0; shift < 64; shift += BignumLimb::DIGIT_BITS) { + digits.push_back(static_cast(limb >> shift)); + } + } + while (!digits.empty() && digits.back() == 0) { + digits.pop_back(); + } +} + +//! Packs the digits of the multiplication kernels into base 2^64 limbs +static void BignumCastDigitsToLimbs(const unsafe_vector &digits, unsafe_vector &limbs) { + constexpr idx_t DIGITS_PER_LIMB = 64 / BignumLimb::DIGIT_BITS; + limbs.assign((digits.size() + DIGITS_PER_LIMB - 1) / DIGITS_PER_LIMB, 0); + for (idx_t i = 0; i < digits.size(); i++) { + limbs[i / DIGITS_PER_LIMB] |= static_cast(digits[i]) + << (BignumLimb::DIGIT_BITS * (i % DIGITS_PER_LIMB)); + } + TrimLimbs(limbs); +} + +//! result = a * b for magnitudes in base 2^64 limbs, through the Karatsuba multiplication of the BIGNUM arithmetic +static void BignumCastMultiplyLimbs(BignumArithmeticState &state, const unsafe_vector &a, + const unsafe_vector &b, unsafe_vector &result) { + BignumCastLimbsToDigits(a, state.lhs_digits); + BignumCastLimbsToDigits(b, state.rhs_digits); + BignumIntermediate::MultiplyMagnitudes(state, state.lhs_digits, state.rhs_digits, state.result_digits); + BignumCastDigitsToLimbs(state.result_digits, result); +} + +//! Converts decimal digits to base 2^64 limbs by divide and conquer: the digits are high * 10^n + low with +//! n = DECIMAL_SHIFT * 2^k the largest such count below the digit count, powers[k] holds 10^(DECIMAL_SHIFT * 2^k) +static void BignumCastDecimalToBinary(BignumArithmeticState &state, const char *digits, idx_t count, + vector> &powers, unsafe_vector &limbs) { + if (count <= PARSE_THRESHOLD) { + BignumCastDecimalToBinaryShort(state, digits, count, limbs); + return; + } + idx_t k = 0; + idx_t low_count = Bignum::DECIMAL_SHIFT; + while (2 * low_count < count) { + low_count *= 2; + k++; + } + unsafe_vector high; + unsafe_vector low; + BignumCastDecimalToBinary(state, digits, count - low_count, powers, high); + BignumCastDecimalToBinary(state, digits + count - low_count, low_count, powers, low); + if (powers.empty()) { + powers.push_back({Bignum::DECIMAL_BASE}); + } + while (powers.size() <= k) { + unsafe_vector square; + BignumCastMultiplyLimbs(state, powers.back(), powers.back(), square); + powers.push_back(std::move(square)); + } + BignumCastMultiplyLimbs(state, high, powers[k], limbs); + // limbs += low, with room for the carry + limbs.resize(MaxValue(limbs.size(), low.size()) + 1, 0); + uint64_t carry = 0; + for (idx_t i = 0; i < limbs.size(); i++) { + const uint64_t addend = i < low.size() ? low[i] : 0; + const uint64_t sum = limbs[i] + addend; + const uint64_t sum_with_carry = sum + carry; + carry = (sum < addend || sum_with_carry < sum) ? 1 : 0; + limbs[i] = sum_with_carry; + } + D_ASSERT(carry == 0); + TrimLimbs(limbs); +} + //! Adds one to a magnitude in base 2^64 limbs static void BignumCastIncrement(unsafe_vector &limbs) { for (auto &limb : limbs) { @@ -219,22 +305,24 @@ static void BignumCastWriteBlob(char *blob, const unsafe_vector &limbs } } -//! Converts the integer digits of a VARCHAR into base 2^64 limbs, rounded up if requested +//! Converts the integer digits of a VARCHAR into the base 2^64 limbs of the scratch, rounded up if requested static void BignumCastVarcharToLimbs(const string_t &value, idx_t start_pos, idx_t end_pos, bool should_round_up, - unsafe_vector &limbs) { - BignumCastDecimalToBinary(value.GetData() + start_pos, end_pos - start_pos, limbs); + BignumCastScratch &scratch) { + BignumCastDecimalToBinary(scratch.state, value.GetData() + start_pos, end_pos - start_pos, scratch.powers_of_ten, + scratch.binary); if (should_round_up) { - BignumCastIncrement(limbs); + BignumCastIncrement(scratch.binary); } } string Bignum::EncodeVarcharBignum(const string_t &value, idx_t start_pos, idx_t end_pos, bool is_negative, - bool is_zero, bool should_round_up) { + bool is_zero, bool should_round_up, optional_ptr context) { if (is_zero || (start_pos == end_pos && !should_round_up)) { return InitializeBignumZero(); } - unsafe_vector limbs; - BignumCastVarcharToLimbs(value, start_pos, end_pos, should_round_up, limbs); + BignumCastScratch scratch(context); + BignumCastVarcharToLimbs(value, start_pos, end_pos, should_round_up, scratch); + auto &limbs = scratch.binary; const idx_t data_bytes = BignumCastMagnitudeBytes(limbs); string result(BIGNUM_HEADER_SIZE + data_bytes, '\0'); BignumCastWriteBlob(&result[0], limbs, data_bytes, is_negative); @@ -252,8 +340,8 @@ bool Bignum::TryVarcharToBignum(const string_t &value, bignum_t &result_value, V result_value = InitializeBignumZero(result); return true; } + BignumCastVarcharToLimbs(value, start_pos, end_pos, should_round_up, scratch); auto &limbs = scratch.binary; - BignumCastVarcharToLimbs(value, start_pos, end_pos, should_round_up, limbs); const idx_t data_bytes = BignumCastMagnitudeBytes(limbs); result_value = bignum_t(StringVector::EmptyString(result, BIGNUM_HEADER_SIZE + data_bytes)); BignumCastWriteBlob(result_value.data.GetDataWriteable(), limbs, data_bytes, is_negative); @@ -342,8 +430,9 @@ bool Bignum::VarcharFormatting(const string_t &value, idx_t &start_pos, idx_t &e return true; } -string Bignum::EncodeBignum(const string_t &value, idx_t start_pos, idx_t end_pos, bool is_negative, bool is_zero) { - return EncodeVarcharBignum(value, start_pos, end_pos, is_negative, is_zero, false); +string Bignum::EncodeBignum(const string_t &value, idx_t start_pos, idx_t end_pos, bool is_negative, bool is_zero, + optional_ptr context) { + return EncodeVarcharBignum(value, start_pos, end_pos, is_negative, is_zero, false, context); } void Bignum::GetByteArray(vector &byte_array, bool &is_negative, const string_t &blob) { @@ -413,12 +502,6 @@ static inline uint64_t BignumCastDivRemDecimalBase(uint64_t high, uint64_t low, return q1; } -static void TrimLimbs(unsafe_vector &limbs) { - while (!limbs.empty() && limbs.back() == 0) { - limbs.pop_back(); - } -} - // Adds the decimal limbs of b, shifted by "shift" limbs, to a static void AddDecimalLimbs(unsafe_vector &a, const uint64_t *b, idx_t b_size, idx_t shift) { while (b_size > 0 && b[b_size - 1] == 0) { @@ -467,7 +550,8 @@ static void SubtractDecimalLimbs(unsafe_vector &a, const unsafe_vector } // Multiplies two numbers in decimal limbs using Karatsuba multiplication -static unsafe_vector MultiplyDecimalLimbs(const uint64_t *a, idx_t a_size, const uint64_t *b, idx_t b_size) { +static unsafe_vector MultiplyDecimalLimbs(BignumArithmeticState &state, const uint64_t *a, idx_t a_size, + const uint64_t *b, idx_t b_size) { if (a_size < b_size) { std::swap(a, b); std::swap(a_size, b_size); @@ -478,6 +562,7 @@ static unsafe_vector MultiplyDecimalLimbs(const uint64_t *a, idx_t a_s } result.resize(a_size + b_size, 0); if (b_size < KARATSUBA_THRESHOLD) { + state.AccountWork(a_size * b_size); for (idx_t i = 0; i < b_size; i++) { uint64_t carry = 0; for (idx_t j = 0; j < a_size; j++) { @@ -496,7 +581,7 @@ static unsafe_vector MultiplyDecimalLimbs(const uint64_t *a, idx_t a_s if (2 * b_size <= a_size) { // unbalanced: multiply b with chunks of a for (idx_t offset = 0; offset < a_size; offset += b_size) { - auto part = MultiplyDecimalLimbs(a + offset, MinValue(b_size, a_size - offset), b, b_size); + auto part = MultiplyDecimalLimbs(state, a + offset, MinValue(b_size, a_size - offset), b, b_size); AddDecimalLimbs(result, part.data(), part.size(), offset); } TrimLimbs(result); @@ -504,14 +589,14 @@ static unsafe_vector MultiplyDecimalLimbs(const uint64_t *a, idx_t a_s } // a = a1 * BASE^m + a0, b = b1 * BASE^m + b0 idx_t m = a_size / 2; - auto z0 = MultiplyDecimalLimbs(a, m, b, m); - auto z2 = MultiplyDecimalLimbs(a + m, a_size - m, b + m, b_size - m); + auto z0 = MultiplyDecimalLimbs(state, a, m, b, m); + auto z2 = MultiplyDecimalLimbs(state, a + m, a_size - m, b + m, b_size - m); unsafe_vector a_sum(a, a + m); AddDecimalLimbs(a_sum, a + m, a_size - m, 0); unsafe_vector b_sum(b, b + m); AddDecimalLimbs(b_sum, b + m, b_size - m, 0); // z1 = (a0 + a1) * (b0 + b1) - z0 - z2 - auto z1 = MultiplyDecimalLimbs(a_sum.data(), a_sum.size(), b_sum.data(), b_sum.size()); + auto z1 = MultiplyDecimalLimbs(state, a_sum.data(), a_sum.size(), b_sum.data(), b_sum.size()); SubtractDecimalLimbs(z1, z0); SubtractDecimalLimbs(z1, z2); AddDecimalLimbs(result, z0.data(), z0.size(), 0); @@ -523,13 +608,14 @@ static unsafe_vector MultiplyDecimalLimbs(const uint64_t *a, idx_t a_s // Converts binary limbs (base 2^64) to decimal limbs (base 10^19), both little-endian // powers[k] holds 2^(64 * 2^k) in decimal limbs -static void BinaryToDecimalLimbs(const uint64_t *binary, idx_t size, vector> &powers, - unsafe_vector &digits) { +static void BinaryToDecimalLimbs(BignumArithmeticState &state, const uint64_t *binary, idx_t size, + vector> &powers, unsafe_vector &digits) { digits.clear(); if (size <= CONVERSION_THRESHOLD) { // typos:ignore-next-line // Following CPython and Knuth (TAOCP, Volume 2 (3rd edn), section 4.4, Method 1b). for (idx_t i = size; i > 0; i--) { + state.AccountWork(digits.size() + 1); uint64_t hi = binary[i - 1]; for (idx_t j = 0; j < digits.size(); j++) { // digits[j] * 2^64 + hi, divided by 10^19 @@ -551,18 +637,18 @@ static void BinaryToDecimalLimbs(const uint64_t *binary, idx_t size, vector low; unsafe_vector high; - BinaryToDecimalLimbs(binary, m, powers, low); - BinaryToDecimalLimbs(binary + m, size - m, powers, high); + BinaryToDecimalLimbs(state, binary, m, powers, low); + BinaryToDecimalLimbs(state, binary + m, size - m, powers, high); if (powers.empty()) { // 2^64 in decimal limbs powers.push_back({8446744073709551616ULL, 1ULL}); } while (powers.size() <= k) { auto &last = powers.back(); - powers.push_back(MultiplyDecimalLimbs(last.data(), last.size(), last.data(), last.size())); + powers.push_back(MultiplyDecimalLimbs(state, last.data(), last.size(), last.data(), last.size())); } auto &power = powers[k]; - digits = MultiplyDecimalLimbs(high.data(), high.size(), power.data(), power.size()); + digits = MultiplyDecimalLimbs(state, high.data(), high.size(), power.data(), power.size()); AddDecimalLimbs(digits, low.data(), low.size(), 0); TrimLimbs(digits); } @@ -625,12 +711,12 @@ static void BignumCastWriteDecimal(char *end, const unsafe_vector &dig //! Converts a BIGNUM to decimal limbs, returns the length of its decimal representation including the sign static idx_t BignumCastToDecimal(const bignum_t &blob, BignumCastScratch &scratch, bool &is_negative) { BignumCastLoadMagnitude(blob, is_negative, scratch.binary); - BinaryToDecimalLimbs(scratch.binary.data(), scratch.binary.size(), scratch.powers, scratch.decimal); + BinaryToDecimalLimbs(scratch.state, scratch.binary.data(), scratch.binary.size(), scratch.powers, scratch.decimal); return BignumCastDecimalLength(scratch.decimal) + (is_negative ? 1 : 0); } -string Bignum::BignumToVarchar(const bignum_t &blob) { - BignumCastScratch scratch; +string Bignum::BignumToVarchar(const bignum_t &blob, optional_ptr context) { + BignumCastScratch scratch(context); bool is_negative; const idx_t length = BignumCastToDecimal(blob, scratch, is_negative); string result(length, '\0'); @@ -648,13 +734,13 @@ string_t Bignum::BignumToVarchar(const bignum_t &blob, Vector &result, BignumCas return target; } -string Bignum::VarcharToBignum(const string_t &value) { +string Bignum::VarcharToBignum(const string_t &value, optional_ptr context) { idx_t start_pos, end_pos; bool is_negative, is_zero, should_round_up; if (!VarcharFormatting(value, start_pos, end_pos, is_negative, is_zero, should_round_up)) { throw ConversionException("Could not convert string \'%s\' to Bignum", value.GetString()); } - return EncodeVarcharBignum(value, start_pos, end_pos, is_negative, is_zero, should_round_up); + return EncodeVarcharBignum(value, start_pos, end_pos, is_negative, is_zero, should_round_up, context); } //! Returns 2^exponent as a double, for 0 <= exponent <= 1023 diff --git a/src/duckdb/src/common/types/bignum_decimal.cpp b/src/duckdb/src/common/types/bignum_decimal.cpp new file mode 100644 index 000000000..d7cc63316 --- /dev/null +++ b/src/duckdb/src/common/types/bignum_decimal.cpp @@ -0,0 +1,755 @@ +#include "duckdb/common/limits.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" +#include "duckdb/main/context.hpp" + +#include "duckdb/common/array.hpp" +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/common/once_flag.hpp" +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/string_heap.hpp" +#include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/types/vector.hpp" + +#include + +namespace duckdb { + +namespace { + +//! A BIGNUM blob that owns its bytes together with an intermediate pointing into it +struct OwnedBignum { + explicit OwnedBignum(string blob_p) : blob(std::move(blob_p)), value(string_t(blob)), intermediate(value) { + } + OwnedBignum(const OwnedBignum &) = delete; + OwnedBignum &operator=(const OwnedBignum &) = delete; + + string blob; + bignum_t value; + BignumIntermediate intermediate; +}; + +//! An intermediate over a blob that lives elsewhere (the blob must stay alive as long as the intermediate is used). The +//! bignum_t is kept as a member: the intermediate points into it when the blob is short enough to be stored inline. +struct BorrowedBignum { + explicit BorrowedBignum(const bignum_t &value_p) : value(value_p), intermediate(value) { + } + explicit BorrowedBignum(const string &blob) : BorrowedBignum(bignum_t(string_t(blob))) { + } + BorrowedBignum(const BorrowedBignum &) = delete; + BorrowedBignum &operator=(const BorrowedBignum &) = delete; + + bignum_t value; + BignumIntermediate intermediate; +}; + +void IncrementDigits(string &digits) { + int carry = 1; + for (idx_t i = digits.size(); i > 0 && carry; i--) { + auto digit = digits[i - 1] - '0' + carry; + digits[i - 1] = static_cast('0' + digit % 10); + carry = digit / 10; + } + if (carry) { + digits.insert(digits.begin(), '1'); + } +} + +//! Skips an underscore between two digits, returns false if no digit follows the underscore +bool SkipDigitSeparator(const char *data, idx_t size, idx_t &pos) { + if (pos < size && data[pos] == '_') { + pos++; + return pos < size && StringUtil::CharacterIsDigit(data[pos]); + } + return true; +} + +//! Appends the digits at pos to digits, allowing underscores between digits, returns false on a stray underscore +bool ReadDigits(const char *data, idx_t size, idx_t &pos, string &digits) { + while (pos < size && StringUtil::CharacterIsDigit(data[pos])) { + digits.push_back(data[pos++]); + if (!SkipDigitSeparator(data, size, pos)) { + return false; + } + } + return true; +} + +//! The decimal digits of a non-negative integer given as little-endian 32-bit limbs +string LimbsToDecimal(vector limbs) { + string digits; + while (!limbs.empty()) { + uint64_t remainder = 0; + for (idx_t i = limbs.size(); i > 0; i--) { + const uint64_t current = (remainder << 32) | limbs[i - 1]; + limbs[i - 1] = static_cast(current / 1000000000); + remainder = current % 1000000000; + } + while (!limbs.empty() && limbs.back() == 0) { + limbs.pop_back(); + } + auto chunk = to_string(remainder); + if (!limbs.empty()) { + chunk.insert(0, 9 - chunk.size(), '0'); + } + digits.insert(0, chunk); + } + return digits.empty() ? "0" : digits; +} + +//! The decimal digits of mantissa * 2^shift +string IntegerDigits(uint64_t mantissa, idx_t shift) { + vector limbs(shift / 32, 0); + limbs.push_back(static_cast(mantissa)); + limbs.push_back(static_cast(mantissa >> 32)); + limbs.push_back(0); + const auto offset = static_cast(shift % 32); + if (offset != 0) { + for (idx_t i = limbs.size(); i > 0; i--) { + limbs[i - 1] = (limbs[i - 1] << offset) | (i > 1 ? limbs[i - 2] >> (32 - offset) : 0); + } + } + return LimbsToDecimal(std::move(limbs)); +} + +//! The first max_digits decimal digits of fraction / 2^bits, preceded by the decimal point (empty for zero) +string FractionDigits(uint64_t fraction, idx_t bits, idx_t max_digits) { + vector limbs((bits + 31) / 32, 0); + limbs[0] = static_cast(fraction); + if (limbs.size() > 1) { + limbs[1] = static_cast(fraction >> 32); + } + const auto top_bits = static_cast(bits % 32 == 0 ? 32 : bits % 32); + string digits; + bool non_zero = fraction != 0; + while (non_zero && digits.size() < max_digits) { + // multiply by ten, the digit is everything that overflows the fraction bits + uint64_t carry = 0; + non_zero = false; + for (auto &limb : limbs) { + const uint64_t current = uint64_t(limb) * 10 + carry; + limb = static_cast(current); + carry = current >> 32; + } + uint32_t digit; + if (top_bits == 32) { + digit = static_cast(carry); + } else { + digit = (static_cast(carry) << (32 - top_bits)) | (limbs.back() >> top_bits); + limbs.back() &= (uint32_t(1) << top_bits) - 1; + } + for (auto limb : limbs) { + non_zero = non_zero || limb != 0; + } + digits.push_back(static_cast('0' + digit)); + } + return digits.empty() ? "" : "." + digits; +} + +//! The number of significant bits of the magnitude of a value +idx_t MagnitudeBits(const BignumIntermediate &value) { + const idx_t start = value.GetStartDataPos(); + if (start >= value.size) { + return 0; + } + idx_t top_bits = 0; + for (auto byte = value.GetAbsoluteByte(NumericCast(start)); byte != 0; byte >>= 1) { + top_bits++; + } + return (value.size - start - 1) * 8 + top_bits; +} + +bool FitsWidthInternal(const BignumIntermediate &value, uint32_t width) { + // 10^width has floor(width * log2(10)) + 1 bits: a value with clearly fewer bits fits and one with clearly more + // does not, only a bit length near the boundary compares against the power itself (the margin covers the + // rounding of the logarithm), so the power is only ever built for values of about the width itself + const auto power_bits = static_cast(static_cast(width) * 3.3219280948873623478703194L); + const auto bits = MagnitudeBits(value); + if (bits + 1 < power_bits) { + return true; + } + if (bits > power_bits + 2) { + return false; + } + const auto power = DecimalHelper::PowerOfTen(width); + BorrowedBignum limit(power); + return value.IsAbsoluteBigger(limit.intermediate) == SMALLER; +} + +//! The BIGNUM blob of a magnitude given as little-endian bignum_digit_t digits +string MagnitudeToBlob(const unsafe_vector &digits) { + idx_t top = digits.size(); + while (top > 0 && digits[top - 1] == 0) { + top--; + } + if (top == 0) { + return Bignum::InitializeBignumZero(); + } + idx_t top_bytes = 0; + for (auto digit = digits[top - 1]; digit != 0; digit >>= 8) { + top_bytes++; + } + const idx_t byte_count = (top - 1) * BignumLimb::DIGIT_BYTES + top_bytes; + if (byte_count > Bignum::MAX_DATA_SIZE) { + throw OutOfRangeException("A power of %llu bytes does not fit a BIGNUM, which holds at most %llu bytes", + byte_count, idx_t(Bignum::MAX_DATA_SIZE)); + } + vector bytes(byte_count); + for (idx_t i = 0; i < byte_count; i++) { + // byte i is the i-th most significant byte + const idx_t from_lsb = byte_count - 1 - i; + bytes[i] = static_cast(digits[from_lsb / BignumLimb::DIGIT_BYTES] >> + (8 * (from_lsb % BignumLimb::DIGIT_BYTES))); + } + return Bignum::FromByteArray(bytes.data(), byte_count, false); +} + +//! 10^exponent as a BIGNUM blob, by binary exponentiation +string ComputePowerOfTen(idx_t exponent, optional_ptr context) { + BignumArithmeticState state(context); + unsafe_vector result; + result.push_back(1); + unsafe_vector base; + base.push_back(10); + unsafe_vector product; + while (exponent > 0) { + if (exponent & 1) { + BignumIntermediate::MultiplyMagnitudes(state, result, base, product); + std::swap(result, product); + } + exponent >>= 1; + if (exponent > 0) { + BignumIntermediate::MultiplyMagnitudes(state, base, base, product); + std::swap(base, product); + } + } + return MagnitudeToBlob(result); +} + +//! The small constants are built once; their blobs outlive the intermediates that point into them +const OwnedBignum &BignumConstant(int32_t value) { + static const OwnedBignum TWO(Bignum::VarcharToBignum(string_t("2"))); + static const OwnedBignum ONE(Bignum::VarcharToBignum(string_t("1"))); + static const OwnedBignum MINUS_ONE(Bignum::VarcharToBignum(string_t("-1"))); + switch (value) { + case 2: + return TWO; + case 1: + return ONE; + default: + D_ASSERT(value == -1); + return MINUS_ONE; + } +} + +//! Whether the magnitude of a value is odd +bool IsOdd(const BignumIntermediate &value) { + return value.GetAbsoluteByte(NumericCast(value.size) - 1) & 1; +} + +} // namespace + +string DecimalHelper::PowerOfTen(idx_t exponent, optional_ptr context) { + // the powers of everyday widths are computed once and read without locking afterwards + static constexpr idx_t CACHED_POWERS = 512; + static array small_powers; + static array small_flags; + if (exponent < CACHED_POWERS) { + CallOnce(small_flags[exponent], [&]() { small_powers[exponent] = ComputePowerOfTen(exponent, context); }); + return small_powers[exponent]; + } + // wider powers are kept in a cache bounded by its total size + static constexpr idx_t MAX_CACHED_POWER_BYTES = 16ULL * 1024 * 1024; + static mutex wide_lock; + static unordered_map wide_powers; + static idx_t wide_power_bytes = 0; + { + lock_guard guard(wide_lock); + auto entry = wide_powers.find(exponent); + if (entry != wide_powers.end()) { + return entry->second; + } + } + // computed outside the lock, so that a long computation does not block the other threads + auto power = ComputePowerOfTen(exponent, context); + lock_guard guard(wide_lock); + if (wide_power_bytes + power.size() > MAX_CACHED_POWER_BYTES) { + wide_powers.clear(); + wide_power_bytes = 0; + } + if (wide_powers.emplace(exponent, power).second) { + wide_power_bytes += power.size(); + } + return power; +} + +string DecimalHelper::PowerOfTwo(idx_t exponent) { + // big-endian: the top byte holds the single set bit, followed by exponent / 8 zero bytes + vector bytes(exponent / 8 + 1, 0); + bytes[0] = static_cast(1 << (exponent % 8)); + return Bignum::FromByteArray(bytes.data(), bytes.size(), false); +} + +bool DecimalHelper::FitsWidth(const bignum_t &value, uint32_t width) { + BorrowedBignum borrowed(value); + return FitsWidthInternal(borrowed.intermediate, width); +} + +bool DecimalHelper::FitsWidth(const BignumIntermediate &value, uint32_t width) { + return FitsWidthInternal(value, width); +} + +bool DecimalHelper::IsNegative(const bignum_t &value) { + return (value.data.GetData()[0] & 0x80) == 0; +} + +bool DecimalHelper::IsZero(const bignum_t &value) { + return value.data.GetSize() == Bignum::BIGNUM_HEADER_SIZE + 1 && !IsNegative(value) && + value.data.GetData()[Bignum::BIGNUM_HEADER_SIZE] == 0; +} + +//! The unscaled value formatted with the given scale, with at least one digit before the decimal point +static string FormatScaled(const bignum_t &value, uint32_t scale, optional_ptr context) { + auto digits = Bignum::BignumToVarchar(value, context); + if (scale == 0) { + return digits; + } + bool negative = false; + if (!digits.empty() && digits[0] == '-') { + negative = true; + digits.erase(digits.begin()); + } + // make sure there is at least one digit in front of the decimal point + if (digits.size() <= scale) { + digits.insert(digits.begin(), scale + 1 - digits.size(), '0'); + } + digits.insert(digits.begin() + static_cast(digits.size() - scale), '.'); + if (negative) { + digits.insert(digits.begin(), '-'); + } + return digits; +} + +string DecimalHelper::ToString(const bignum_t &value, uint32_t width, uint32_t scale, + optional_ptr context) { + auto result = FormatScaled(value, scale, context); + if (width == scale && scale > 0) { + // like the fixed-size decimals, a decimal without integer digits prints no leading zero: .100, -.100 + auto point = result.find('.'); + D_ASSERT(point != string::npos && point > 0 && result[point - 1] == '0'); + result.erase(point - 1, 1); + } + return result; +} + +bool DecimalHelper::TryParse(const char *data, idx_t size, uint32_t width, uint32_t scale, string &result, + char decimal_separator, optional_ptr context) { + idx_t pos = 0; + // skip surrounding whitespace + while (pos < size && StringUtil::CharacterIsSpace(data[pos])) { + pos++; + } + while (size > pos && StringUtil::CharacterIsSpace(data[size - 1])) { + size--; + } + if (pos >= size) { + return false; + } + bool negative = false; + if (data[pos] == '-' || data[pos] == '+') { + negative = data[pos] == '-'; + pos++; + } + string digits; + if (!ReadDigits(data, size, pos, digits)) { + return false; + } + const idx_t integer_digits = digits.size(); + if (pos < size && data[pos] == decimal_separator) { + pos++; + if (!ReadDigits(data, size, pos, digits)) { + return false; + } + } + if (digits.empty()) { + return false; + } + int64_t exponent = 0; + if (pos < size && (data[pos] == 'e' || data[pos] == 'E')) { + pos++; + bool exponent_negative = false; + if (pos < size && (data[pos] == '-' || data[pos] == '+')) { + exponent_negative = data[pos] == '-'; + pos++; + } + string exponent_digits; + if (!ReadDigits(data, size, pos, exponent_digits) || exponent_digits.empty()) { + return false; + } + for (auto c : exponent_digits) { + exponent = exponent * 10 + (c - '0'); + if (exponent > NumericLimits::Maximum()) { + // the fixed-size decimals parse the exponent as a 32-bit integer + return false; + } + } + if (exponent_negative) { + exponent = -exponent; + } + } + if (pos != size) { + return false; + } + // the unscaled value keeps "integer_digits + exponent + scale" digits, the next digit rounds half away from zero + const int64_t keep = static_cast(integer_digits) + exponent + scale; + string unscaled; + bool round_up = false; + if (keep >= 0) { + const auto keep_count = static_cast(keep); + if (keep_count > idx_t(width) + digits.size() + 1) { + // far more digits than the width allows, unless every digit is zero + for (auto c : digits) { + if (c != '0') { + return false; + } + } + unscaled = "0"; + } else { + unscaled = digits.substr(0, MinValue(keep_count, digits.size())); + if (keep_count > digits.size()) { + unscaled.append(keep_count - digits.size(), '0'); + } else if (keep_count < digits.size()) { + round_up = digits[keep_count] >= '5'; + } + } + } + // strip leading zeros + idx_t first_non_zero = 0; + while (first_non_zero < unscaled.size() && unscaled[first_non_zero] == '0') { + first_non_zero++; + } + unscaled.erase(0, first_non_zero); + if (round_up) { + IncrementDigits(unscaled); + } + if (unscaled.size() > width) { + return false; + } + if (unscaled.empty()) { + unscaled = "0"; + negative = false; + } + if (negative) { + unscaled.insert(unscaled.begin(), '-'); + } + result = Bignum::VarcharToBignum(string_t(unscaled), context); + return true; +} + +string DecimalHelper::Rescale(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, + optional_ptr context) { + if (target_scale == source_scale) { + return value.data.GetString(); + } + BorrowedBignum source(value); + StringHeap heap; + BignumArithmeticState state(context); + if (target_scale > source_scale) { + const auto power = PowerOfTen(target_scale - source_scale, context); + BorrowedBignum factor(power); + return BignumIntermediate::Multiply(heap, state, source.intermediate, factor.intermediate).GetString(); + } + // scaling down divides by the power of ten and rounds half away from zero + const auto power = PowerOfTen(source_scale - target_scale, context); + BorrowedBignum divisor(power); + string_t quotient; + string_t remainder; + if (!BignumIntermediate::TryDivMod(heap, state, source.intermediate, divisor.intermediate, quotient, remainder)) { + throw InternalException("DecimalHelper::Rescale: division by a power of ten failed"); + } + const bignum_t remainder_bignum(remainder); + BorrowedBignum remainder_value(remainder_bignum); + auto twice_remainder = + BignumIntermediate::Multiply(heap, state, remainder_value.intermediate, BignumConstant(2).intermediate); + const bignum_t twice_remainder_bignum(twice_remainder); + BorrowedBignum twice_remainder_value(twice_remainder_bignum); + if (twice_remainder_value.intermediate.IsAbsoluteBigger(divisor.intermediate) != SMALLER) { + // |remainder| >= divisor / 2 rounds away from zero + auto &one = BignumConstant(source.intermediate.is_negative ? -1 : 1); + const bignum_t quotient_bignum(quotient); + BorrowedBignum quotient_value(quotient_bignum); + quotient = BignumIntermediate::Add(heap, quotient_value.intermediate, one.intermediate); + } + return quotient.GetString(); +} + +bool DecimalHelper::TryRescale(const bignum_t &value, uint32_t source_scale, uint32_t target_width, + uint32_t target_scale, string &result, optional_ptr context) { + auto rescaled = Rescale(value, source_scale, target_scale, context); + if (!FitsWidth(bignum_t(string_t(rescaled)), target_width)) { + return false; + } + result = std::move(rescaled); + return true; +} + +DecimalHelper::RoundState::RoundState(Vector &result, Context &context) + : heap(StringVector::GetStringHeap(result)), state(context) { +} + +bignum_t DecimalHelper::Store(Vector &result, const string &owned) { + return bignum_t(StringVector::AddStringOrBlob(result, owned.data(), owned.size())); +} + +bool DecimalHelper::TryRound(const bignum_t &value, idx_t drop_digits, idx_t restore_digits, + DecimalRounding rounding, uint32_t width, RoundState &round_state, + bignum_t &result) { + auto &heap = round_state.heap; + auto &state = round_state.state; + BorrowedBignum source(value); + string_t rounded = value.data; + if (drop_digits > 0) { + const auto power = PowerOfTen(drop_digits, Context::TryGetClientContext(state.context)); + BorrowedBignum divisor(power); + string_t quotient; + string_t remainder; + if (!BignumIntermediate::TryDivMod(heap, state, source.intermediate, divisor.intermediate, quotient, + remainder)) { + throw InternalException("DecimalHelper::TryRound: division by a power of ten failed"); + } + // the remainder has the sign of the value: the quotient is truncated towards zero + const bool negative = source.intermediate.is_negative; + int32_t adjustment = 0; + if (!IsZero(bignum_t(remainder))) { + switch (rounding) { + case DecimalRounding::TRUNCATE: + break; + case DecimalRounding::FLOOR: + adjustment = negative ? -1 : 0; + break; + case DecimalRounding::CEIL: + adjustment = negative ? 0 : 1; + break; + default: { + const bignum_t remainder_bignum(remainder); + BorrowedBignum remainder_value(remainder_bignum); + auto twice_remainder = BignumIntermediate::Multiply(heap, state, remainder_value.intermediate, + BignumConstant(2).intermediate); + const bignum_t twice_remainder_bignum(twice_remainder); + BorrowedBignum twice_remainder_value(twice_remainder_bignum); + const bignum_t quotient_bignum(quotient); + BorrowedBignum quotient_value(quotient_bignum); + auto comparison = twice_remainder_value.intermediate.IsAbsoluteBigger(divisor.intermediate); + // above the half the value rounds away from zero, on the half the rounding mode decides + const bool away = comparison == GREATER || + (comparison == EQUAL && (rounding == DecimalRounding::HALF_AWAY_FROM_ZERO || + IsOdd(quotient_value.intermediate))); + adjustment = away ? (negative ? -1 : 1) : 0; + break; + } + } + } + rounded = quotient; + if (adjustment != 0) { + const bignum_t quotient_bignum(quotient); + BorrowedBignum quotient_value(quotient_bignum); + rounded = + BignumIntermediate::Add(heap, quotient_value.intermediate, BignumConstant(adjustment).intermediate); + } + } + if (restore_digits > 0) { + const bignum_t rounded_bignum(rounded); + BorrowedBignum rounded_value(rounded_bignum); + const auto power = PowerOfTen(restore_digits, Context::TryGetClientContext(state.context)); + BorrowedBignum factor(power); + rounded = BignumIntermediate::Multiply(heap, state, rounded_value.intermediate, factor.intermediate); + } + if (!FitsWidth(bignum_t(rounded), width)) { + return false; + } + result = bignum_t(rounded); + return true; +} + +string DecimalHelper::FromInteger(uhugeint_t value) { + uint8_t bytes[16]; + idx_t size = 0; + for (idx_t i = 0; i < 16; i++) { + // big-endian, the most significant byte first + auto shift = (15 - i) * 8; + uint8_t byte = static_cast((shift >= 64 ? value.upper >> (shift - 64) : value.lower >> shift) & 0xFF); + if (size == 0 && byte == 0 && i < 15) { + continue; + } + bytes[size++] = byte; + } + return Bignum::FromByteArray(bytes, size, false); +} + +string DecimalHelper::FromInteger(hugeint_t value) { + if (value.upper >= 0) { + return FromInteger(uhugeint_t(static_cast(value.upper), value.lower)); + } + // the magnitude of the minimum hugeint (2^127) fits a uhugeint, so negate in uhugeint two's complement space + uhugeint_t bits(static_cast(value.upper), value.lower); + uhugeint_t magnitude = ~bits + uhugeint_t(1); + auto blob = FromInteger(magnitude); + // complementing the header and data bytes flips the sign + for (auto &c : blob) { + c = static_cast(~c); + } + return blob; +} + +bool DecimalHelper::TryToUhugeint(const bignum_t &value, uhugeint_t &result) { + bool strict = false; + return Bignum::BignumToInt(value, result, strict); +} + +bool DecimalHelper::TryToHugeint(const bignum_t &value, hugeint_t &result) { + bool strict = false; + return Bignum::BignumToInt(value, result, strict); +} + +template +static bool TryToFloatingInternal(const bignum_t &value, uint32_t scale, T &result, + optional_ptr context) { + // the decimal text parses directly into the target type, so the value is rounded once + auto text = FormatScaled(value, scale, context); + if (!TryCast::Operation(string_t(text), result, false)) { + throw InternalException("Could not convert wide decimal '%s' to a floating point number", text); + } + // an overflowing text parses to infinity + return std::isfinite(result); +} + +bool DecimalHelper::TryToFloating(const bignum_t &value, uint32_t scale, float &result, + optional_ptr context) { + return TryToFloatingInternal(value, scale, result, context); +} + +bool DecimalHelper::TryToFloating(const bignum_t &value, uint32_t scale, double &result, + optional_ptr context) { + return TryToFloatingInternal(value, scale, result, context); +} + +double DecimalHelper::ToDouble(const bignum_t &value, uint32_t scale, optional_ptr context) { + double result; + TryToFloating(value, scale, result, context); + return result; +} + +string DecimalHelper::FromTwosComplement(const_data_ptr_t data, idx_t size, bool big_endian) { + if (size == 0) { + return Bignum::InitializeBignumZero(); + } + // normalize to big-endian magnitude bytes + vector magnitude(size); + for (idx_t i = 0; i < size; i++) { + magnitude[i] = big_endian ? data[i] : data[size - 1 - i]; + } + const bool negative = (magnitude[0] & 0x80) != 0; + if (negative) { + // the magnitude of a negative two's complement number is the complement of every byte plus one + for (idx_t i = 0; i < size; i++) { + magnitude[i] = static_cast(~magnitude[i]); + } + for (idx_t i = size; i > 0; i--) { + if (++magnitude[i - 1] != 0) { + break; + } + } + } + // strip leading zero bytes + idx_t start = 0; + while (start + 1 < size && magnitude[start] == 0) { + start++; + } + if (size - start == 1 && magnitude[start] == 0) { + return Bignum::InitializeBignumZero(); + } + return Bignum::FromByteArray(magnitude.data() + start, size - start, negative); +} + +void DecimalHelper::ToTwosComplement(const bignum_t &value, data_ptr_t result, idx_t size, bool big_endian) { + BorrowedBignum borrowed(value); + auto &intermediate = borrowed.intermediate; + const idx_t start = intermediate.GetStartDataPos(); + const idx_t magnitude_bytes = intermediate.size - start; + if (magnitude_bytes > size) { + throw OutOfRangeException("Decimal value does not fit in %d bytes", size); + } + // big-endian magnitude, right-aligned + vector bytes(size, 0); + for (idx_t i = 0; i < magnitude_bytes; i++) { + bytes[size - magnitude_bytes + i] = intermediate.GetAbsoluteByte(static_cast(start + i)); + } + if (intermediate.is_negative) { + // two's complement negation complements every byte and adds one + for (idx_t i = 0; i < size; i++) { + bytes[i] = static_cast(~bytes[i]); + } + for (idx_t i = size; i > 0; i--) { + if (++bytes[i - 1] != 0) { + break; + } + } + // the only negative number whose magnitude has the top bit set is -2^(8 * size - 1) + if (magnitude_bytes == size && (bytes[0] & 0x80) == 0) { + throw OutOfRangeException("Decimal value does not fit in %d bytes", size); + } + } else if (magnitude_bytes == size && (bytes[0] & 0x80) != 0) { + throw OutOfRangeException("Decimal value does not fit in %d bytes", size); + } + for (idx_t i = 0; i < size; i++) { + result[i] = big_endian ? bytes[i] : bytes[size - 1 - i]; + } +} + +bool DecimalHelper::TryFromDouble(double value, uint32_t width, uint32_t scale, string &result, + optional_ptr context) { + if (!std::isfinite(value)) { + return false; + } + // |value| = mantissa * 2^shift with an integer mantissa of at most 53 bits + int exponent; + const double fraction = std::frexp(std::fabs(value), &exponent); + const auto mantissa = static_cast(std::ldexp(fraction, 53)); + const int shift = exponent - 53; + string text = value < 0 ? "-" : ""; + if (shift >= 0) { + text += IntegerDigits(mantissa, static_cast(shift)); + } else { + const auto fraction_bits = static_cast(-shift); + if (fraction_bits >= 64) { + text += "0"; + text += FractionDigits(mantissa, fraction_bits, idx_t(scale) + 1); + } else { + text += to_string(mantissa >> fraction_bits); + text += FractionDigits(mantissa & ((uint64_t(1) << fraction_bits) - 1), fraction_bits, idx_t(scale) + 1); + } + } + return TryParse(text.c_str(), text.size(), width, scale, result, '.', context); +} + +string DecimalHelper::FromDouble(double value) { + D_ASSERT(std::isfinite(value) && std::trunc(value) == value); + int exponent; + const double fraction = std::frexp(std::fabs(value), &exponent); + const auto mantissa = static_cast(std::ldexp(fraction, 53)); + const int shift = exponent - 53; + string text = value < 0 ? "-" : ""; + if (shift >= 0) { + text += IntegerDigits(mantissa, static_cast(shift)); + } else { + // an integral value below 2^53 keeps no fraction bits + text += to_string(-shift >= 64 ? 0 : mantissa >> static_cast(-shift)); + } + return Bignum::VarcharToBignum(string_t(text)); +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/types/decimal.cpp b/src/duckdb/src/common/types/decimal.cpp index 4f75fb80a..f1249eb80 100644 --- a/src/duckdb/src/common/types/decimal.cpp +++ b/src/duckdb/src/common/types/decimal.cpp @@ -1,9 +1,63 @@ #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/operator/decimal_cast_operators.hpp" #include "duckdb/common/types/cast_helpers.hpp" +#include "duckdb/common/types/decimal_helper.hpp" +#include "duckdb/common/limits.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/function/cast/default_casts.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/settings.hpp" namespace duckdb { constexpr uint32_t Decimal::MAX_WIDTH_DECIMAL; +constexpr uint32_t Decimal::DEFAULT_MAX_WIDTH; + +DecimalWidthLimit::DecimalWidthLimit(uint32_t width_p, const char *hint_p) : width(width_p), hint(hint_p) { + D_ASSERT(width >= Decimal::MAX_WIDTH_INT128); +} + +DecimalWidthLimit DecimalWidthLimit::FromSetting(optional_ptr context) { + const char *hint = "SET max_decimal_width to allow wider decimals"; + if (!context) { + return DecimalWidthLimit(NumericLimits::Maximum(), hint); + } + const idx_t max_width = Settings::Get(*context); + const auto width = NumericCast( + MinValue(MaxValue(max_width, Decimal::MAX_WIDTH_INT128), NumericLimits::Maximum())); + return DecimalWidthLimit(width, hint); +} + +DecimalWidthLimit DecimalWidthLimit::FromReturnType(const LogicalType &return_type) { + uint32_t width = Decimal::MAX_WIDTH_INT128; + TypeVisitor::Contains(return_type, [&](const LogicalType &type) { + if (type.IsAggregateState()) { + width = NumericLimits::Maximum(); + return true; + } + if (type.id() == LogicalTypeId::DECIMAL) { + width = MaxValue(width, DecimalType::GetWidth(type)); + } + return false; + }); + return DecimalWidthLimit(width, "a deserialized function is rebound within the width of its result"); +} + +uint32_t DecimalWidthLimit::ResultWidth(uint32_t max_input_width) const { + return MaxValue(width, max_input_width); +} + +uint32_t DecimalWidthLimit::CheckedWidth(idx_t result_width, uint32_t max_input_width, const string &operation) const { + if (result_width > NumericLimits::Maximum()) { + throw OutOfRangeException("%s needs a DECIMAL of %llu digits, the width of a DECIMAL is at most %u", operation, + result_width, NumericLimits::Maximum()); + } + if (result_width > ResultWidth(max_input_width)) { + throw OutOfRangeException("%s needs a DECIMAL of %llu digits, the maximum DECIMAL width is %u (%s)", operation, + result_width, width, hint); + } + return NumericCast(result_width); +} template string TemplatedDecimalToString(SIGNED value, uint32_t width, uint32_t scale) { @@ -32,4 +86,47 @@ string Decimal::ToString(hugeint_t value, uint32_t width, uint32_t scale) { return string(data.get(), UnsafeNumericCast(len)); } +string Decimal::ToString(bignum_t value, uint32_t width, uint32_t scale, optional_ptr context) { + return DecimalHelper::ToString(value, width, scale, context); +} + +//===--------------------------------------------------------------------===// +// DecimalHelper of the fixed-size tiers: the conversions that run through the cast operators +//===--------------------------------------------------------------------===// +template +bool FixedSizeDecimalHelper::TryParse(const char *data, idx_t size, uint32_t width, + uint32_t scale, T &result, char decimal_separator, + optional_ptr context) { + if (decimal_separator == ',') { + return TryDecimalStringCast(data, size, result, width, scale); + } + return TryDecimalStringCast(data, size, result, width, scale); +} + +template +bool FixedSizeDecimalHelper::TryToFloating(T value, uint32_t scale, float &result, + optional_ptr context) { + CastParameters parameters; + return TryCastFromDecimal::Operation(value, result, parameters, MAX_WIDTH, scale); +} + +template +bool FixedSizeDecimalHelper::TryToFloating(T value, uint32_t scale, double &result, + optional_ptr context) { + CastParameters parameters; + return TryCastFromDecimal::Operation(value, result, parameters, MAX_WIDTH, scale); +} + +template +bool FixedSizeDecimalHelper::TryFromDouble(double value, uint32_t width, uint32_t scale, + T &result, optional_ptr context) { + CastParameters parameters; + return TryCastToDecimal::Operation(value, result, parameters, width, scale); +} + +template struct FixedSizeDecimalHelper; +template struct FixedSizeDecimalHelper; +template struct FixedSizeDecimalHelper; +template struct FixedSizeDecimalHelper; + } // namespace duckdb diff --git a/src/duckdb/src/common/types/type_manager.cpp b/src/duckdb/src/common/types/type_manager.cpp index 8d5880e82..f0a8deb4d 100644 --- a/src/duckdb/src/common/types/type_manager.cpp +++ b/src/duckdb/src/common/types/type_manager.cpp @@ -87,7 +87,8 @@ static LogicalType TransformStringToUnboundType(const string &str, ClientContext // This has to be called with a level of indirection (through "parse_function") in order to avoid being included in // extensions that statically link the core DuckDB library. -static LogicalType ParseLogicalTypeInternal(const string &type_str, ClientContext &context) { +static LogicalType ParseLogicalTypeInternal(const string &type_str, ClientContext &context, + optional_ptr decimal_width_limit) { auto type = TransformStringToUnboundType(type_str, context); if (type.IsUnbound()) { if (!context.transaction.HasActiveTransaction()) { @@ -95,13 +96,15 @@ static LogicalType ParseLogicalTypeInternal(const string &type_str, ClientContex "Context does not have a transaction active, try running ClientContext::BindLogicalType instead"); } auto binder = Binder::CreateBinder(context, nullptr); + binder->SetDecimalWidthLimit(decimal_width_limit); binder->BindLogicalType(type); } return type; } -LogicalType TypeManager::ParseLogicalType(const string &type_str, ClientContext &context) const { - return parse_function(type_str, context); +LogicalType TypeManager::ParseLogicalType(const string &type_str, ClientContext &context, + optional_ptr decimal_width_limit) const { + return parse_function(type_str, context, decimal_width_limit); } LogicalType TypeManager::ParseLogicalType(const string &type_str) const { diff --git a/src/duckdb/src/common/types/value.cpp b/src/duckdb/src/common/types/value.cpp index 91532a68b..7e845344c 100644 --- a/src/duckdb/src/common/types/value.cpp +++ b/src/duckdb/src/common/types/value.cpp @@ -27,6 +27,7 @@ #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/main/error_manager.hpp" #include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/binary_serializer.hpp" @@ -310,6 +311,11 @@ Value Value::MinimumValue(const LogicalType &type) { return Value::DECIMAL(int64_t(-NumericHelper::POWERS_OF_TEN[width] + 1), width, scale); case PhysicalType::INT128: return Value::DECIMAL(-Hugeint::POWERS_OF_TEN[width] + 1, width, scale); + case PhysicalType::VARCHAR: { + // the minimum wide decimal is -(10^width - 1) + auto blob = Bignum::VarcharToBignum(string_t("-" + string(width, '9'))); + return Value::DECIMAL(bignum_t(string_t(blob)), width, scale); + } default: throw InternalException("Unknown decimal type"); } @@ -408,6 +414,11 @@ Value Value::MaximumValue(const LogicalType &type) { return Value::DECIMAL(int64_t(NumericHelper::POWERS_OF_TEN[width] - 1), width, scale); case PhysicalType::INT128: return Value::DECIMAL(Hugeint::POWERS_OF_TEN[width] - 1, width, scale); + case PhysicalType::VARCHAR: { + // the maximum wide decimal is 10^width - 1 + auto blob = Bignum::VarcharToBignum(string_t(string(width, '9'))); + return Value::DECIMAL(bignum_t(string_t(blob)), width, scale); + } default: throw InternalException("Unknown decimal type"); } @@ -646,6 +657,9 @@ Value Value::DECIMAL(int64_t value, uint32_t width, uint32_t scale) { case PhysicalType::INT64: result.value_.bigint = value; break; + case PhysicalType::VARCHAR: + // the unscaled value of a wide decimal is a BIGNUM blob + return Value::DECIMAL(hugeint_t(value), width, scale); default: result.value_.hugeint = value; break; @@ -656,6 +670,11 @@ Value Value::DECIMAL(int64_t value, uint32_t width, uint32_t scale) { } Value Value::DECIMAL(hugeint_t value, uint32_t width, uint32_t scale) { + if (Decimal::IsWide(width)) { + // the unscaled value of a wide decimal is a BIGNUM blob + auto blob = DecimalHelper::FromInteger(value); + return Value::DECIMAL(bignum_t(string_t(blob)), width, scale); + } D_ASSERT(width >= Decimal::MAX_WIDTH_INT64 && width <= Decimal::MAX_WIDTH_INT128); Value result(LogicalType::DECIMAL(width, scale)); result.value_.hugeint = value; @@ -663,6 +682,28 @@ Value Value::DECIMAL(hugeint_t value, uint32_t width, uint32_t scale) { return result; } +Value Value::DECIMAL(bignum_t value, uint32_t width, uint32_t scale) { + if (!Decimal::IsWide(width)) { + // the fixed-size tiers hold the unscaled value as the integer of their width + hugeint_t unscaled; + if (!DecimalHelper::TryToHugeint(value, unscaled)) { + throw InternalException("Value::DECIMAL: the BIGNUM does not fit a DECIMAL(%d,%d)", width, scale); + } + if (width > Decimal::MAX_WIDTH_INT64) { + return Value::DECIMAL(unscaled, width, scale); + } + int64_t narrow; + if (!Hugeint::TryCast(unscaled, narrow)) { + throw InternalException("Value::DECIMAL: the BIGNUM does not fit a DECIMAL(%d,%d)", width, scale); + } + return Value::DECIMAL(narrow, width, scale); + } + Value result(LogicalType::DECIMAL(width, scale)); + result.is_null = false; + result.value_info_ = make_shared_ptr(value.data.GetString()); + return result; +} + Value Value::FLOAT(float value) { Value result(LogicalType::FLOAT); result.value_.float_ = value; @@ -1794,6 +1835,12 @@ string Value::ToSQLString() const { case LogicalTypeId::MAP: case LogicalTypeId::UNION: return NestedToSQLString(*this, [](const Value &child) { return child.ToSQLString(); }); + case LogicalTypeId::DECIMAL: + // a bare literal would be reparsed as DOUBLE or BIGNUM and lose precision, so emit an explicit cast + if (type_.InternalType() == PhysicalType::VARCHAR) { + return "'" + ToString() + "'::" + type_.ToString(); + } + return ToString(); case LogicalTypeId::FLOAT: if (!FloatIsFinite(FloatValue::Get(*this)) || (FloatValue::Get(*this) == 0 && std::signbit(FloatValue::Get(*this)))) { @@ -2408,23 +2455,15 @@ static bool ValueIsValidShallow(const Value &value) { const auto width = DecimalType::GetWidth(type); switch (type.InternalType()) { case PhysicalType::INT16: + return DecimalHelper::FitsWidth(value.GetValueUnsafe(), width); case PhysicalType::INT32: - case PhysicalType::INT64: { - int64_t decimal_value; - if (type.InternalType() == PhysicalType::INT16) { - decimal_value = value.GetValueUnsafe(); - } else if (type.InternalType() == PhysicalType::INT32) { - decimal_value = value.GetValueUnsafe(); - } else { - decimal_value = value.GetValueUnsafe(); - } - return decimal_value > -NumericHelper::POWERS_OF_TEN[width] && - decimal_value < NumericHelper::POWERS_OF_TEN[width]; - } - case PhysicalType::INT128: { - const auto decimal_value = value.GetValueUnsafe(); - return decimal_value > -Hugeint::POWERS_OF_TEN[width] && decimal_value < Hugeint::POWERS_OF_TEN[width]; - } + return DecimalHelper::FitsWidth(value.GetValueUnsafe(), width); + case PhysicalType::INT64: + return DecimalHelper::FitsWidth(value.GetValueUnsafe(), width); + case PhysicalType::INT128: + return DecimalHelper::FitsWidth(value.GetValueUnsafe(), width); + case PhysicalType::VARCHAR: + return DecimalHelper::FitsWidth(value.GetValueUnsafe(), width); default: throw InternalException("Invalid physical type for DECIMAL"); } 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 68fc16a73..6fc4f4e4f 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp @@ -288,8 +288,9 @@ static idx_t AnalyzePrimitiveValueData(const UnifiedVariantVectorData &variant, } else if (decimal_data.width <= 38) { total_size += sizeof(uhugeint_t); } else { - throw InvalidInputException("Can't convert VARIANT DECIMAL(%d, %d) to Parquet VARIANT", decimal_data.width, - decimal_data.scale); + throw InvalidInputException("Can't convert VARIANT DECIMAL(%d, %d) to Parquet VARIANT: the Parquet VARIANT " + "specification holds decimals of at most 38 digits", + decimal_data.width, decimal_data.scale); } break; } @@ -590,8 +591,9 @@ static void WritePrimitiveValueData(const UnifiedVariantVectorData &variant, idx auto decimal_data = VariantUtils::DecodeDecimalData(variant, row, values_index); if (decimal_data.width > 38) { - throw InvalidInputException("Can't convert VARIANT DECIMAL(%d, %d) to Parquet VARIANT", decimal_data.width, - decimal_data.scale); + throw InvalidInputException("Can't convert VARIANT DECIMAL(%d, %d) to Parquet VARIANT: the Parquet VARIANT " + "specification holds decimals of at most 38 digits", + decimal_data.width, decimal_data.scale); } else if (decimal_data.width <= 4) { // DuckDB uses INT16 to store small decimals, but parquet only supports DECIMAL4 at minimum, so here we // promote to INT32. 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 95a443da9..4f0667d78 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp @@ -561,6 +561,10 @@ string_t ParquetVariantNode::GetString() const { return string_t(string_data, size); } +string_t ParquetVariantNode::GetWideDecimal() const { + throw InternalException("Parquet VARIANT decimals have at most 38 digits"); +} + VariantDecimalProperties ParquetVariantNode::GetDecimalProperties() const { if (kind == Kind::SHREDDED) { uint32_t width; @@ -572,9 +576,9 @@ VariantDecimalProperties ParquetVariantNode::GetDecimalProperties() const { auto value_metadata = VariantValueMetadata::FromHeaderByte(binary[0]); auto payload = binary + 1; uint8_t scale = LoadChecked(payload, binary_end); - if (scale > Decimal::MAX_WIDTH_DECIMAL) { + if (scale > Decimal::MAX_WIDTH_INT128) { throw IOException("Corrupted VARIANT 'value' buffer, decimal scale %d exceeds the maximum of %d", scale, - Decimal::MAX_WIDTH_DECIMAL); + Decimal::MAX_WIDTH_INT128); } auto value_data = payload + sizeof(uint8_t); uint32_t width; @@ -591,12 +595,12 @@ VariantDecimalProperties ParquetVariantNode::GetDecimalProperties() const { hugeint_t value; value.lower = Load(value_data); value.upper = Load(value_data + sizeof(uint64_t)); - auto &limit = Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_DECIMAL]; + auto &limit = Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_INT128]; if (value >= limit || value <= -limit) { throw IOException("Corrupted VARIANT 'value' buffer, DECIMAL16 value exceeds the maximum width of %d", - Decimal::MAX_WIDTH_DECIMAL); + Decimal::MAX_WIDTH_INT128); } - width = Decimal::MAX_WIDTH_DECIMAL; + width = Decimal::MAX_WIDTH_INT128; break; } } diff --git a/src/duckdb/src/common/types/variant/variant_comparison.cpp b/src/duckdb/src/common/types/variant/variant_comparison.cpp index 71d2f03b9..f55f82e96 100644 --- a/src/duckdb/src/common/types/variant/variant_comparison.cpp +++ b/src/duckdb/src/common/types/variant/variant_comparison.cpp @@ -179,6 +179,14 @@ VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNo const auto decimal_data = node.GetDecimal(); hugeint_t unscaled; switch (decimal_data.GetPhysicalType()) { + case PhysicalType::VARCHAR: { + // the BIGNUM blob of a decimal wider than 38 digits + const auto decimal_string = Bignum::BignumToVarchar(bignum_t(node.GetWideDecimal())); + const bool negative = !decimal_string.empty() && decimal_string[0] == '-'; + const idx_t offset = negative ? 1 : 0; + return BuildNumberKey(negative, decimal_string.data() + offset, decimal_string.size() - offset, + decimal_data.scale); + } case PhysicalType::INT16: unscaled = hugeint_t(Load(decimal_data.value_ptr)); break; diff --git a/src/duckdb/src/common/types/variant/variant_iterator.cpp b/src/duckdb/src/common/types/variant/variant_iterator.cpp index b89ddf043..9c57c8cfe 100644 --- a/src/duckdb/src/common/types/variant/variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/variant_iterator.cpp @@ -428,6 +428,18 @@ string_t VariantNode::GetString() const { return content.unified.GetData()[content.unified.sel->get_index(shredded_index)]; } +string_t VariantNode::GetWideDecimal() const { + if (kind == Kind::UNSHREDDED) { + auto &blob = state->unshredded.GetBlob(row); + auto decimal = DecodeDecimalData(blob, state->unshredded.GetByteOffset(row, value_index)); + D_ASSERT(decimal.GetPhysicalType() == PhysicalType::VARCHAR); + auto data = const_data_ptr_cast(blob.GetData()); + return DecodeStringData(blob, NumericCast(decimal.value_ptr - data)); + } + D_ASSERT(kind == Kind::SHREDDED); + return GetString(); +} + VariantDecimalData VariantNode::GetDecimal() const { if (kind == Kind::UNSHREDDED) { return DecodeDecimalData(state->unshredded.GetBlob(row), state->unshredded.GetByteOffset(row, value_index)); diff --git a/src/duckdb/src/common/vector/flat_vector.cpp b/src/duckdb/src/common/vector/flat_vector.cpp index 8af80b39b..e0ce3f7d0 100644 --- a/src/duckdb/src/common/vector/flat_vector.cpp +++ b/src/duckdb/src/common/vector/flat_vector.cpp @@ -443,8 +443,11 @@ Value StandardVectorBuffer::GetValue(const LogicalType &type, idx_t index) const return Value::DECIMAL(reinterpret_cast(data_ptr)[index], width, scale); case PhysicalType::INT128: return Value::DECIMAL(reinterpret_cast(data_ptr)[index], width, scale); + case PhysicalType::VARCHAR: + // the unscaled value of a wide decimal is a BIGNUM blob + return Value::DECIMAL(reinterpret_cast(data_ptr)[index], width, scale); default: - throw InternalException("Physical type '%s' has a width bigger than 38, which is not supported", + throw InternalException("Unimplemented physical type '%s' for DECIMAL", TypeIdToString(type.InternalType())); } } diff --git a/src/duckdb/src/execution/expression_executor.cpp b/src/duckdb/src/execution/expression_executor.cpp index 6aa9b0ce7..f5fe765a0 100644 --- a/src/duckdb/src/execution/expression_executor.cpp +++ b/src/duckdb/src/execution/expression_executor.cpp @@ -1,5 +1,6 @@ #include "duckdb/execution/expression_executor.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/context.hpp" #include "duckdb/main/database.hpp" @@ -217,13 +218,17 @@ void ExpressionExecutor::Verify(const Expression &expr, Vector &vector, idx_t co Vector::DebugTransformToDictionary(vector); } if (debug_vector_verification == DebugVectorVerification::VARIANT_VECTOR) { - // LAMBDA is not a value - its slot only holds a placeholder, so there is nothing to round-trip + // LAMBDA is not a value - its slot only holds a placeholder, so there is nothing to round-trip; + // VARIANT holds decimals of at most 38 digits if (TypeVisitor::Contains(vector.GetType(), [](const LogicalType &type) { if (type.IsJSONType() || type.id() == LogicalTypeId::VARIANT || type.id() == LogicalTypeId::UNION || type.id() == LogicalTypeId::ENUM || type.id() == LogicalTypeId::TYPE || type.id() == LogicalTypeId::TUPLE || type.id() == LogicalTypeId::LAMBDA) { return true; } + if (type.id() == LogicalTypeId::DECIMAL && DecimalType::GetWidth(type) > Decimal::MAX_WIDTH_INT128) { + return true; + } return false; })) { return; diff --git a/src/duckdb/src/execution/index/unbound_index.cpp b/src/duckdb/src/execution/index/unbound_index.cpp index 567fc5955..e479bed25 100644 --- a/src/duckdb/src/execution/index/unbound_index.cpp +++ b/src/duckdb/src/execution/index/unbound_index.cpp @@ -65,8 +65,12 @@ IndexCheckpointResult UnboundIndex::Checkpoint(PartialBlockManager &, StorageVer return {storage_info, nullptr}; } -unique_ptr UnboundIndex::Bind(IndexBinder &binder, const vector &physical_column_types) { - auto bound_index = binder.BindIndex(*this); +unique_ptr UnboundIndex::Bind(IndexBinder &binder, const vector &physical_column_types, + bool skip_mismatched_keys) { + auto bound_index = binder.BindIndex(*this, skip_mismatched_keys); + if (!bound_index) { + return nullptr; + } // 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. 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 7b18e03e8..300b05880 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 @@ -1,4 +1,6 @@ #include "duckdb/execution/operator/csv_scanner/string_value_scanner.hpp" +#include "duckdb/common/types/decimal_helper.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" @@ -244,6 +246,18 @@ void FullLinePosition::SanitizeError(string &value) { value = {char_array.begin(), char_array.end() - 1}; } +//! Parses a decimal of the tier into the target slot of the vector, with the separator of the CSV +template +static bool ParseDecimal(const char *value_ptr, idx_t size, const ParseTypeInfo &parse_type, char decimal_separator, + Vector &vector, T &target) { + typename DecimalHelper::OWNED parsed; + if (!DecimalHelper::TryParse(value_ptr, size, parse_type.width, parse_type.scale, parsed, decimal_separator)) { + return false; + } + target = DecimalHelper::Store(vector, parsed); + return true; +} + void StringValueResult::AddValueToVector(const char *value_ptr, idx_t size, bool allocate) { if (HandleTooManyColumnsError(value_ptr, size)) { return; @@ -431,62 +445,37 @@ void StringValueResult::AddValueToVector(const char *value_ptr, idx_t size, bool break; } case LogicalTypeId::DECIMAL: { - if (decimal_separator == ',') { - switch (parse_types[chunk_col_id].internal_type) { - case PhysicalType::INT16: - success = TryDecimalStringCast( - value_ptr, size, static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - case PhysicalType::INT32: - success = TryDecimalStringCast( - value_ptr, size, static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - case PhysicalType::INT64: - success = TryDecimalStringCast( - value_ptr, size, static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - case PhysicalType::INT128: - success = TryDecimalStringCast( - value_ptr, size, static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - default: - throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " + - TypeIdToString(parse_types[chunk_col_id].internal_type)); - } - - } else if (decimal_separator == '.') { - switch (parse_types[chunk_col_id].internal_type) { - case PhysicalType::INT16: - success = TryDecimalStringCast(value_ptr, size, - static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - case PhysicalType::INT32: - success = TryDecimalStringCast(value_ptr, size, - static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - case PhysicalType::INT64: - success = TryDecimalStringCast(value_ptr, size, - static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - case PhysicalType::INT128: - success = TryDecimalStringCast(value_ptr, size, - static_cast(vector_ptr[chunk_col_id])[number_of_rows], - parse_types[chunk_col_id].width, parse_types[chunk_col_id].scale); - break; - default: - throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " + - TypeIdToString(parse_types[chunk_col_id].internal_type)); - } - } else { + auto &parse_type = parse_types[chunk_col_id]; + auto &vector = parse_chunk.data[chunk_col_id]; + auto target = vector_ptr[chunk_col_id]; + if (decimal_separator != ',' && decimal_separator != '.') { throw InvalidInputException("Decimals can only have ',' and '.' as decimal separators"); } + switch (parse_type.internal_type) { + case PhysicalType::INT16: + success = ParseDecimal(value_ptr, size, parse_type, decimal_separator, vector, + static_cast(target)[number_of_rows]); + break; + case PhysicalType::INT32: + success = ParseDecimal(value_ptr, size, parse_type, decimal_separator, vector, + static_cast(target)[number_of_rows]); + break; + case PhysicalType::INT64: + success = ParseDecimal(value_ptr, size, parse_type, decimal_separator, vector, + static_cast(target)[number_of_rows]); + break; + case PhysicalType::INT128: + success = ParseDecimal(value_ptr, size, parse_type, decimal_separator, vector, + static_cast(target)[number_of_rows]); + break; + case PhysicalType::VARCHAR: + success = ParseDecimal(value_ptr, size, parse_type, decimal_separator, vector, + static_cast(target)[number_of_rows]); + break; + default: + throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " + + TypeIdToString(parse_type.internal_type)); + } break; } default: { @@ -1888,8 +1877,8 @@ bool StringValueScanner::CanDirectlyCast(const LogicalType &type, bool icu_loade case LogicalTypeId::DATE: case LogicalTypeId::TIMESTAMP: case LogicalTypeId::TIME: - case LogicalTypeId::DECIMAL: case LogicalType::BOOLEAN: + case LogicalTypeId::DECIMAL: return true; case LogicalType::TIMESTAMP_TZ: // We only try to do direct cast of timestamp tz if the ICU extension is not loaded, otherwise, it needs to go 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 8d4fd918e..83f3275f2 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 @@ -6,6 +6,7 @@ #include "duckdb/common/operator/integer_cast_operator.hpp" #include "duckdb/common/string.hpp" #include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/time.hpp" #include "duckdb/execution/operator/csv_scanner/sniffer/csv_sniffer.hpp" @@ -145,6 +146,14 @@ bool CSVSniffer::CanYouCastBignum(const char *value_ptr, idx_t value_size) { } } +//! Whether a value parses as a decimal of the tier, with the separator of the CSV +template +static bool TryParseDecimal(const char *value_ptr, idx_t value_size, uint32_t width, uint32_t scale, + char decimal_separator) { + typename DecimalHelper::OWNED parsed; + return DecimalHelper::TryParse(value_ptr, value_size, width, scale, parsed, decimal_separator); +} + bool CSVSniffer::CanYouCastIt(ClientContext &context, const string_t value, const LogicalType &type, const DialectOptions &dialect_options, const bool is_null, const char decimal_separator, const char thousands_separator) { @@ -249,61 +258,24 @@ bool CSVSniffer::CanYouCastIt(ClientContext &context, const string_t value, cons case LogicalTypeId::DECIMAL: { uint32_t width, scale; type.GetDecimalProperties(width, scale); - if (decimal_separator == ',') { - switch (type.InternalType()) { - case PhysicalType::INT16: { - int16_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - case PhysicalType::INT32: { - int32_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - case PhysicalType::INT64: { - int64_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - case PhysicalType::INT128: { - hugeint_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - default: - throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " + - TypeIdToString(type.InternalType())); - } - - } else if (decimal_separator == '.') { - switch (type.InternalType()) { - case PhysicalType::INT16: { - int16_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - case PhysicalType::INT32: { - int32_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - case PhysicalType::INT64: { - int64_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - case PhysicalType::INT128: { - hugeint_t dummy_value; - return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale); - } - - default: - throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " + - TypeIdToString(type.InternalType())); - } + if (decimal_separator != ',' && decimal_separator != '.') { + throw InvalidInputException("Decimals can only have ',' and '.' as decimal separators"); + } + switch (type.InternalType()) { + case PhysicalType::INT16: + return TryParseDecimal(value_ptr, value_size, width, scale, decimal_separator); + case PhysicalType::INT32: + return TryParseDecimal(value_ptr, value_size, width, scale, decimal_separator); + case PhysicalType::INT64: + return TryParseDecimal(value_ptr, value_size, width, scale, decimal_separator); + case PhysicalType::INT128: + return TryParseDecimal(value_ptr, value_size, width, scale, decimal_separator); + case PhysicalType::VARCHAR: + return TryParseDecimal(value_ptr, value_size, width, scale, decimal_separator); + default: + throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " + + TypeIdToString(type.InternalType())); } - throw InvalidInputException("Decimals can only have ',' and '.' as decimal separators"); } case LogicalTypeId::VARCHAR: return true; diff --git a/src/duckdb/src/execution/operator/schema/physical_drop.cpp b/src/duckdb/src/execution/operator/schema/physical_drop.cpp index 5d181b44f..9f9585d63 100644 --- a/src/duckdb/src/execution/operator/schema/physical_drop.cpp +++ b/src/duckdb/src/execution/operator/schema/physical_drop.cpp @@ -38,13 +38,15 @@ SourceResultType PhysicalDrop::GetDataInternal(ExecutionContext &context, DataCh auto &client_data = ClientData::Get(context.client); auto &default_entry = client_data.catalog_search_path->GetDefault(); auto ¤t_catalog = default_entry.GetCatalog(); - auto ¤t_schema = default_entry.GetSchema(); - D_ASSERT(info->GetQualifiedName().Name() != DEFAULT_SCHEMA); + auto current_schema = default_entry.GetSchemaPath(); + auto &dropped_schema = info->GetQualifiedName().Path(); + D_ASSERT(dropped_schema.size() > 2 || info->GetQualifiedName().Name() != DEFAULT_SCHEMA); auto resolved_current_catalog = IsInvalidCatalog(current_catalog) ? DatabaseManager::GetDefaultDatabase(context.client) : current_catalog; - if (catalog.GetName() == resolved_current_catalog && current_schema == info->GetQualifiedName().Name()) { - // Reset the schema to default + if (catalog.GetName() == resolved_current_catalog && dropped_schema.size() - 1 <= current_schema.size() && + std::equal(dropped_schema.begin() + 1, dropped_schema.end(), current_schema.begin())) { + // Reset the default when dropping its schema or an ancestor. SchemaSetting::SetLocal(context.client, DEFAULT_SCHEMA); } break; diff --git a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp index eda2ea5ae..da1df96af 100644 --- a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp +++ b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp @@ -156,8 +156,11 @@ static unique_ptr BindDecimalAverage(BindAggregateFunctionInput &i break; case PhysicalType::INT128: function.ReplaceImplementation( - MakeDecimalAvgFunction(LogicalType::DECIMAL(Decimal::MAX_WIDTH_DECIMAL, scale), return_type)); + MakeDecimalAvgFunction(LogicalType::DECIMAL(Decimal::MAX_WIDTH_INT128, scale), return_type)); break; + case PhysicalType::VARCHAR: + throw NotImplementedException("decimal_average over DECIMAL types wider than %d digits is not supported yet", + Decimal::MAX_WIDTH_INT128); default: throw InternalException("decimal_average: unexpected physical type"); } 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 cb6ae3316..f36a4e847 100644 --- a/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp +++ b/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp @@ -416,6 +416,9 @@ AggregateFunction GetDecimalFirstFunction(const LogicalType &type) { return GetFirstFunction(LogicalType::INTEGER); case PhysicalType::INT64: return GetFirstFunction(LogicalType::BIGINT); + case PhysicalType::VARCHAR: + // wide decimals are BIGNUM blobs + return GetFirstFunction(LogicalType::VARCHAR); default: return GetFirstFunction(LogicalType::HUGEINT); } diff --git a/src/duckdb/src/function/aggregate_function.cpp b/src/duckdb/src/function/aggregate_function.cpp index 39a1e1110..e83141052 100644 --- a/src/duckdb/src/function/aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate_function.cpp @@ -183,8 +183,11 @@ void BoundAggregateFunction::ReplaceImplementation(const AggregateFunction &func BindAggregateFunctionInput::BindAggregateFunctionInput(ClientContext &context_p, BoundAggregateFunction &bound_function_p, - vector> &arguments_p) - : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p), + vector> &arguments_p, + optional_ptr binder_p, + optional_ptr decimal_width_limit_p) + : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p, + binder_p, decimal_width_limit_p), bound_function(bound_function_p) { } diff --git a/src/duckdb/src/function/cast/bignum_casts.cpp b/src/duckdb/src/function/cast/bignum_casts.cpp index ac0b007bb..a013e3d68 100644 --- a/src/duckdb/src/function/cast/bignum_casts.cpp +++ b/src/duckdb/src/function/cast/bignum_casts.cpp @@ -371,6 +371,9 @@ BoundCastInfo DefaultCasts::BignumCastSwitch(BindCastInput &input, const Logical return BoundCastInfo(&Bignum::BignumToVarcharCast); case LogicalTypeId::DOUBLE: return BoundCastInfo(&VectorCastHelpers::TryCastErrorLoop); + case LogicalTypeId::DECIMAL: + // a BIGNUM is a decimal with scale 0 + return WideDecimalCast(BoundCastInfo(&VectorCastHelpers::ToDecimalCast), source, target); default: return TryVectorNullCast; } diff --git a/src/duckdb/src/function/cast/cast_statistics.cpp b/src/duckdb/src/function/cast/cast_statistics.cpp index ec7efedcb..e21c919c9 100644 --- a/src/duckdb/src/function/cast/cast_statistics.cpp +++ b/src/duckdb/src/function/cast/cast_statistics.cpp @@ -53,30 +53,60 @@ static bool WidenByInfinities(const BaseStatistics &input, const LogicalType &ta return true; } +//! The statistics of numeric values: the fixed-size types and the bignum_t tier of decimals +static bool IsNumericStats(const BaseStatistics &stats) { + return stats.GetStatsType() == StatisticsType::NUMERIC_STATS || + stats.GetStatsType() == StatisticsType::BIGNUM_STATS; +} + +static bool HasNumericMinMax(const BaseStatistics &stats) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + return BignumStats::HasMinMax(stats); + } + return NumericStats::HasMinMax(stats); +} + +static Value NumericMin(const BaseStatistics &stats) { + return stats.GetStatsType() == StatisticsType::BIGNUM_STATS ? BignumStats::Min(stats) : NumericStats::Min(stats); +} + +static Value NumericMax(const BaseStatistics &stats) { + return stats.GetStatsType() == StatisticsType::BIGNUM_STATS ? BignumStats::Max(stats) : NumericStats::Max(stats); +} + +static void SetNumericMinMax(BaseStatistics &stats, const Value &min, const Value &max) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + BignumStats::SetMin(stats, min); + BignumStats::SetMax(stats, max); + } else { + NumericStats::SetMin(stats, min); + NumericStats::SetMax(stats, max); + } +} + static unique_ptr StatisticsOperationsNumericNumericCast(const BaseStatistics &input, const LogicalType &target) { // Bail out if the stats are not numeric - if (input.GetStatsType() != StatisticsType::NUMERIC_STATS) { + if (!IsNumericStats(input)) { return nullptr; } if (!input.CanHaveNoNull()) { - auto result = NumericStats::CreateEmpty(target); + auto result = BaseStatistics::CreateEmpty(target); result.CopyBase(input); return result.ToUnique(); } - if (!NumericStats::HasMinMax(input)) { + if (!HasNumericMinMax(input)) { return nullptr; } - auto min = NumericStats::Min(input).DefaultTryCastAs(target); - auto max = NumericStats::Max(input).DefaultTryCastAs(target); + auto min = NumericMin(input).DefaultTryCastAs(target); + auto max = NumericMax(input).DefaultTryCastAs(target); if (!min || !max || !WidenByInfinities(input, target, *min, *max)) { // overflow in cast: bailout return nullptr; } - auto result = NumericStats::CreateEmpty(target); + auto result = BaseStatistics::CreateEmpty(target); result.CopyBase(input); - NumericStats::SetMin(result, *min); - NumericStats::SetMax(result, *max); + SetNumericMinMax(result, *min, *max); return result.ToUnique(); } @@ -88,6 +118,13 @@ bool CastStatistics::CanPropagate(const LogicalType &source, const LogicalType & return false; } // we can only propagate numeric -> numeric + if (BaseStatistics::GetStatsType(source) == StatisticsType::BIGNUM_STATS) { + // the bignum_t tier of decimals casts to the numeric types + return target.IsNumeric(); + } + if (BaseStatistics::GetStatsType(target) == StatisticsType::BIGNUM_STATS) { + return source.IsNumeric(); + } switch (source.InternalType()) { case PhysicalType::INT8: case PhysicalType::INT16: diff --git a/src/duckdb/src/function/cast/decimal_cast.cpp b/src/duckdb/src/function/cast/decimal_cast.cpp index 3ca21796c..ea0ebf168 100644 --- a/src/duckdb/src/function/cast/decimal_cast.cpp +++ b/src/duckdb/src/function/cast/decimal_cast.cpp @@ -2,12 +2,35 @@ #include "duckdb/function/cast/vector_cast_helpers.hpp" #include "duckdb/common/vector_operations/general_cast.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/common/types/cast_helpers.hpp" namespace duckdb { +static unique_ptr InitWideDecimalCastState(CastLocalStateParameters ¶meters) { + return make_uniq(parameters.context); +} + +static bool IsWideDecimal(const LogicalType &type) { + return type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type)); +} + +BoundCastInfo DefaultCasts::WideDecimalCast(BoundCastInfo info, const LogicalType &source, const LogicalType &target) { + if (!info.HasInitLocalState() && (IsWideDecimal(source) || IsWideDecimal(target))) { + info.SetInitLocalState(InitWideDecimalCastState); + } + return info; +} + +optional_ptr DefaultCasts::WideDecimalCastContext(CastParameters ¶meters) { + if (!parameters.local_state) { + return nullptr; + } + return parameters.local_state->Cast().context; +} + template static bool FromDecimalCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { auto &source_type = source.GetType(); @@ -26,6 +49,9 @@ static bool FromDecimalCast(Vector &source, Vector &result, idx_t count, CastPar case PhysicalType::INT128: return VectorCastHelpers::TemplatedDecimalCast(source, result, count, parameters, width, scale); + case PhysicalType::VARCHAR: + return VectorCastHelpers::TemplatedDecimalCast(source, result, count, + parameters, width, scale); default: throw InternalException("Unimplemented internal type for decimal"); } @@ -182,6 +208,92 @@ static bool TemplatedDecimalScaleDown(Vector &source, Vector &result, idx_t coun } } +//===--------------------------------------------------------------------===// +// Decimal -> Decimal through BIGNUM: the source or the target is of the bignum_t tier (width > 38) +//===--------------------------------------------------------------------===// +struct BignumDecimalScaleInput { + BignumDecimalScaleInput(Vector &result_p, CastParameters ¶meters, uint32_t source_width_p, + uint32_t source_scale_p, uint32_t target_width_p, uint32_t target_scale_p) + : result(result_p), vector_cast_data(result, parameters), source_width(source_width_p), + source_scale(source_scale_p), target_width(target_width_p), target_scale(target_scale_p), + context(DefaultCasts::WideDecimalCastContext(parameters)) { + } + + Vector &result; + VectorTryCastData vector_cast_data; + uint32_t source_width; + uint32_t source_scale; + uint32_t target_width; + uint32_t target_scale; + optional_ptr context; +}; + +//! The unscaled value of a decimal as a BIGNUM (the blob of a fixed-size tier is written into "blob") +static bignum_t UnscaledBignum(bignum_t input, string &blob) { + return input; +} + +template +static bignum_t UnscaledBignum(INPUT_TYPE input, string &blob) { + blob = DecimalHelper::FromInteger(hugeint_t(input)); + return bignum_t(string_t(blob)); +} + +struct BignumDecimalScaleOperator { + template + static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, BignumDecimalScaleInput &data) { + string unscaled_blob; + auto unscaled = UnscaledBignum(input, unscaled_blob); + string rescaled; + if (!DecimalHelper::TryRescale(unscaled, data.source_scale, data.target_width, data.target_scale, + rescaled, data.context)) { + auto error = StringUtil::Format("Casting value \"%s\" to type %s failed: value is out of range!", + Decimal::ToString(input, data.source_width, data.source_scale), + data.result.GetType().ToString()); + return HandleVectorCastError::Operation(std::move(error), mask, idx, data.vector_cast_data); + } + if constexpr (std::is_same::value) { + return bignum_t(StringVector::AddStringOrBlob(data.result, rescaled.data(), rescaled.size())); + } else { + // the checked width guarantees the value fits the integer + hugeint_t value; + if (!DecimalHelper::TryToHugeint(bignum_t(string_t(rescaled)), value)) { + throw InternalException("Rescaled decimal does not fit a HUGEINT despite the width check"); + } + return Cast::Operation(value); + } + } +}; + +template +static bool TemplatedBignumDecimalScale(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { + BignumDecimalScaleInput input(result, parameters, DecimalType::GetWidth(source.GetType()), + DecimalType::GetScale(source.GetType()), DecimalType::GetWidth(result.GetType()), + DecimalType::GetScale(result.GetType())); + UnaryExecutor::GenericExecute(source, result, count, input, + parameters.error_message); + return input.vector_cast_data.all_converted; +} + +static bool BignumDecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { + source.GetType().Verify(); + result.GetType().Verify(); + switch (result.GetType().InternalType()) { + case PhysicalType::INT16: + return TemplatedBignumDecimalScale(source, result, count, parameters); + case PhysicalType::INT32: + return TemplatedBignumDecimalScale(source, result, count, parameters); + case PhysicalType::INT64: + return TemplatedBignumDecimalScale(source, result, count, parameters); + case PhysicalType::INT128: + return TemplatedBignumDecimalScale(source, result, count, parameters); + case PhysicalType::VARCHAR: + return TemplatedBignumDecimalScale(source, result, count, parameters); + default: + throw NotImplementedException("Unimplemented internal type for decimal"); + } +} + template static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { auto source_scale = DecimalType::GetScale(source.GetType()); @@ -205,6 +317,8 @@ static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count case PhysicalType::INT128: return TemplatedDecimalScaleUp(source, result, count, parameters); + case PhysicalType::VARCHAR: + return TemplatedBignumDecimalScale(source, result, count, parameters); default: throw NotImplementedException("Unimplemented internal type for decimal"); } @@ -219,6 +333,8 @@ static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count return TemplatedDecimalScaleDown(source, result, count, parameters); case PhysicalType::INT128: return TemplatedDecimalScaleDown(source, result, count, parameters); + case PhysicalType::VARCHAR: + return TemplatedBignumDecimalScale(source, result, count, parameters); default: throw NotImplementedException("Unimplemented internal type for decimal"); } @@ -242,6 +358,18 @@ struct StringCastFromDecimalOperator { } }; +//! The bignum_t tier formats through the context of the cast, so that a long conversion checks for interrupts +static bool BignumDecimalToStringCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { + auto &source_type = source.GetType(); + auto width = DecimalType::GetWidth(source_type); + auto scale = DecimalType::GetScale(source_type); + auto context = DefaultCasts::WideDecimalCastContext(parameters); + UnaryExecutor::Execute(source, result, count, [&](bignum_t input) { + return StringVector::AddString(result, Decimal::ToString(input, width, scale, context)); + }); + return true; +} + template static bool DecimalToStringCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { auto &source_type = source.GetType(); @@ -253,8 +381,8 @@ static bool DecimalToStringCast(Vector &source, Vector &result, idx_t count, Cas return true; } -BoundCastInfo DefaultCasts::DecimalCastSwitch(BindCastInput &input, const LogicalType &source, - const LogicalType &target) { +static BoundCastInfo DecimalCastSwitchInternal(BindCastInput &input, const LogicalType &source, + const LogicalType &target) { // now switch on the result type switch (target.id()) { case LogicalTypeId::BOOLEAN: @@ -279,6 +407,8 @@ BoundCastInfo DefaultCasts::DecimalCastSwitch(BindCastInput &input, const Logica return FromDecimalCast; case LogicalTypeId::UHUGEINT: return FromDecimalCast; + case LogicalTypeId::BIGNUM: + return FromDecimalCast; case LogicalTypeId::DECIMAL: { // decimal to decimal cast // first we need to figure out the source and target internal types @@ -291,6 +421,8 @@ BoundCastInfo DefaultCasts::DecimalCastSwitch(BindCastInput &input, const Logica return DecimalDecimalCastSwitch; case PhysicalType::INT128: return DecimalDecimalCastSwitch; + case PhysicalType::VARCHAR: + return BignumDecimalDecimalCastSwitch; default: throw NotImplementedException("Unimplemented internal type for decimal in decimal_decimal cast"); } @@ -309,6 +441,8 @@ BoundCastInfo DefaultCasts::DecimalCastSwitch(BindCastInput &input, const Logica return DecimalToStringCast; case PhysicalType::INT128: return DecimalToStringCast; + case PhysicalType::VARCHAR: + return BignumDecimalToStringCast; default: throw InternalException("Unimplemented internal decimal type"); } @@ -318,4 +452,9 @@ BoundCastInfo DefaultCasts::DecimalCastSwitch(BindCastInput &input, const Logica } } +BoundCastInfo DefaultCasts::DecimalCastSwitch(BindCastInput &input, const LogicalType &source, + const LogicalType &target) { + return WideDecimalCast(DecimalCastSwitchInternal(input, source, target), source, target); +} + } // namespace duckdb diff --git a/src/duckdb/src/function/cast/numeric_casts.cpp b/src/duckdb/src/function/cast/numeric_casts.cpp index e92ccfbaf..c88e51179 100644 --- a/src/duckdb/src/function/cast/numeric_casts.cpp +++ b/src/duckdb/src/function/cast/numeric_casts.cpp @@ -73,7 +73,7 @@ static BoundCastInfo InternalNumericCastSwitch(const LogicalType &source, const case LogicalTypeId::DOUBLE: return BoundCastInfo(&VectorCastHelpers::TryCastLoop); case LogicalTypeId::DECIMAL: - return BoundCastInfo(&VectorCastHelpers::ToDecimalCast); + return DefaultCasts::WideDecimalCast(BoundCastInfo(&VectorCastHelpers::ToDecimalCast), source, target); case LogicalTypeId::VARCHAR: return BoundCastInfo(&VectorCastHelpers::StringCast); case LogicalTypeId::BIT: diff --git a/src/duckdb/src/function/cast/string_cast.cpp b/src/duckdb/src/function/cast/string_cast.cpp index 9551b089c..7e3f12e5c 100644 --- a/src/duckdb/src/function/cast/string_cast.cpp +++ b/src/duckdb/src/function/cast/string_cast.cpp @@ -96,7 +96,8 @@ static BoundCastInfo VectorStringCastNumericSwitch(BindCastInput &input, const L case LogicalTypeId::INTERVAL: return BoundCastInfo(&VectorCastHelpers::TryCastErrorLoop); case LogicalTypeId::DECIMAL: - return BoundCastInfo(&VectorCastHelpers::ToDecimalCast); + return DefaultCasts::WideDecimalCast(BoundCastInfo(&VectorCastHelpers::ToDecimalCast), source, + target); default: return DefaultCasts::TryVectorNullCast; } diff --git a/src/duckdb/src/function/cast/variant/from_variant.cpp b/src/duckdb/src/function/cast/variant/from_variant.cpp index 37ee672e7..bce2c050d 100644 --- a/src/duckdb/src/function/cast/variant/from_variant.cpp +++ b/src/duckdb/src/function/cast/variant/from_variant.cpp @@ -73,12 +73,14 @@ struct StringConversionPayload { //! decimal struct DecimalConversionPayloadFromVariant { public: - DecimalConversionPayloadFromVariant(idx_t width, idx_t scale) : width(width), scale(scale) { + DecimalConversionPayloadFromVariant(idx_t width, idx_t scale, Vector &vec) : width(width), scale(scale), vec(vec) { } public: idx_t width; idx_t scale; + //! The result vector that owns the BIGNUM blobs of decimals wider than 38 digits + Vector &vec; }; struct ToVariantCastData : public BoundCastData { @@ -184,8 +186,16 @@ struct VariantDecimalConversion { error = StringUtil::Format("Can't convert from VARIANT(DECIMAL(%d, %d))", width, scale); return false; } - VariantUtils::Available(blob_size, NumericCast(ptr - value), sizeof(T)); - ret = Load(ptr); + if constexpr (std::is_same::value) { + // the BIGNUM blob of a decimal wider than 38 digits + VariantUtils::Available(blob_size, NumericCast(ptr - value), 1); + auto length = VarintDecode(ptr); + VariantUtils::Available(blob_size, NumericCast(ptr - value), length); + ret = StringVector::AddStringOrBlob(payload.vec, reinterpret_cast(ptr), length); + } else { + VariantUtils::Available(blob_size, NumericCast(ptr - value), sizeof(T)); + ret = Load(ptr); + } return true; } }; @@ -1195,7 +1205,7 @@ static bool CastVariant(FromVariantConversionData &conversion_data, Vector &resu uint32_t width; uint32_t scale; target_type.GetDecimalProperties(width, scale); - DecimalConversionPayloadFromVariant decimal_payload(width, scale); + DecimalConversionPayloadFromVariant decimal_payload(width, scale, result); switch (physical_type) { case PhysicalType::INT16: @@ -1210,6 +1220,10 @@ static bool CastVariant(FromVariantConversionData &conversion_data, Vector &resu case PhysicalType::INT128: return CastVariantToPrimitive>(conversion_data, result, sel, offset, count, row, decimal_payload); + case PhysicalType::VARCHAR: + // decimals wider than 38 digits are BIGNUM blobs + return CastVariantToPrimitive>(conversion_data, result, sel, offset, + count, row, decimal_payload); default: throw NotImplementedException("Can't convert VARIANT to DECIMAL value of physical type: %s", EnumUtil::ToString(physical_type)); diff --git a/src/duckdb/src/function/cast/variant/to_json.cpp b/src/duckdb/src/function/cast/variant/to_json.cpp index 03be3de13..891f214d2 100644 --- a/src/duckdb/src/function/cast/variant/to_json.cpp +++ b/src/duckdb/src/function/cast/variant/to_json.cpp @@ -143,6 +143,8 @@ struct JSONConverterBase { val_str = Decimal::ToString(val, width, scale); } else if constexpr (std::is_same_v) { val_str = Decimal::ToString(val, width, scale); + } else if constexpr (std::is_same_v) { + 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 2a6dfeeb7..b44008fee 100644 --- a/src/duckdb/src/function/combine_types_rules.cpp +++ b/src/duckdb/src/function/combine_types_rules.cpp @@ -1,5 +1,6 @@ #include "duckdb/function/combine_types_rule.hpp" #include "duckdb/common/helper.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/insertion_order_preserving_map.hpp" @@ -133,6 +134,11 @@ static bool CombineEqualVarchar(LogicalTypeResolver &logical_type_resolver, cons } return true; } + +DecimalWidthLimit LogicalTypeResolver::GetDecimalWidthLimit() const { + return decimal_width_limit ? *decimal_width_limit : DecimalWidthLimit::FromSetting(context); +} + static bool CombineEqualDecimal(LogicalTypeResolver &logical_type_resolver, const LogicalType &left, const LogicalType &right, LogicalType &result) { // unify the width/scale so that the resulting decimal always fits @@ -143,13 +149,20 @@ static bool CombineEqualDecimal(LogicalTypeResolver &logical_type_resolver, cons auto extra_width_right = DecimalType::GetWidth(right) - DecimalType::GetScale(right); 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 = width - extra_width; + idx_t width = idx_t(extra_width) + scale; + const auto max_input_width = MaxValue(DecimalType::GetWidth(left), DecimalType::GetWidth(right)); + const auto decimal_width_limit = logical_type_resolver.GetDecimalWidthLimit(); + const idx_t width_limit = decimal_width_limit.ResultWidth(max_input_width); + if (width > width_limit && !Decimal::IsWide(width_limit)) { + // the result does not fit the fixed-size tiers: truncate the scale + width = width_limit; + scale = NumericCast(width - extra_width); } - result = LogicalType::DECIMAL(width, scale); + // a wide result is never truncated, a result wider than the inputs and the maximum width is an error + result = + LogicalType::DECIMAL(decimal_width_limit.CheckedWidth( + width, max_input_width, "Combining " + left.ToString() + " and " + right.ToString()), + scale); return true; } static bool CombineEqualList(LogicalTypeResolver &logical_type_resolver, const LogicalType &left, diff --git a/src/duckdb/src/function/function.cpp b/src/duckdb/src/function/function.cpp index 91434adcc..be7baa9cb 100644 --- a/src/duckdb/src/function/function.cpp +++ b/src/duckdb/src/function/function.cpp @@ -8,6 +8,8 @@ #include "duckdb/function/scalar/string_functions.hpp" #include "duckdb/function/scalar_function.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/common/types/decimal.hpp" namespace duckdb { @@ -723,4 +725,28 @@ optional_idx BindFunctionInput::GetArgumentIndex(const Identifier &name) const { return optional_idx(); } +Binder &BindFunctionInput::GetBinder() { + if (!binder) { + throw InternalException("Function %s cannot be bound without a Binder", function.GetName()); + } + return *binder; +} + +FunctionBinder BindFunctionInput::NestedFunctionBinder() { + if (binder) { + return FunctionBinder(*binder); + } + return FunctionBinder(context, decimal_width_limit); +} + +DecimalWidthLimit BindFunctionInput::GetDecimalWidthLimit() const { + if (binder) { + return binder->GetDecimalWidthLimit(); + } + if (decimal_width_limit) { + return *decimal_width_limit; + } + return DecimalWidthLimit::FromSetting(context); +} + } // namespace duckdb diff --git a/src/duckdb/src/function/function_binder.cpp b/src/duckdb/src/function/function_binder.cpp index c45e5ef7d..aac4f4a5f 100644 --- a/src/duckdb/src/function/function_binder.cpp +++ b/src/duckdb/src/function/function_binder.cpp @@ -28,6 +28,13 @@ FunctionBinder::FunctionBinder(ClientContext &context_p) : binder(nullptr), cont } FunctionBinder::FunctionBinder(Binder &binder_p) : binder(&binder_p), context(binder_p.context) { } +FunctionBinder::FunctionBinder(ClientContext &context_p, optional_ptr decimal_width_limit_p) + : binder(nullptr), context(context_p), decimal_width_limit(decimal_width_limit_p) { +} + +optional_ptr FunctionBinder::FixedDecimalWidthLimit() const { + return binder ? binder->GetFixedDecimalWidthLimit() : decimal_width_limit; +} //! Split the full (maybe-named) argument list into the positional and the named arguments. Returns false, and leaves //! the arguments as they are, if a positional argument follows a named one @@ -119,7 +126,8 @@ static int64_t ImplicitCastCost(optional_ptr context, const Logic static bool InferTemplateType(optional_ptr context, const LogicalType &source, const LogicalType &target, case_insensitive_map_t> &bindings, - FunctionMismatch::TemplateDeduction &failure) { + FunctionMismatch::TemplateDeduction &failure, + optional_ptr decimal_width_limit) { if (target.id() == LogicalTypeId::UNKNOWN || target.id() == LogicalTypeId::SQLNULL) { // If the actual type is unknown, we cannot infer anything more. // Therefore, we map all remaining templates in the source to UNKNOWN or SQLNULL, if not already inferred to @@ -159,9 +167,15 @@ static bool InferTemplateType(optional_ptr context, const Logical // Try to unify (promote) the type candidates - without a client context, with the built-in casts only LogicalType result; - const bool unified = context - ? LogicalType::TryGetMaxLogicalType(*context, it->second.back(), target, result) - : LogicalType::DefaultTryGetMaxLogicalTypeUnchecked(it->second.back(), target, result); + bool unified; + if (!context) { + unified = LogicalType::DefaultTryGetMaxLogicalTypeUnchecked(it->second.back(), target, result); + } else if (decimal_width_limit) { + unified = + LogicalType::TryGetMaxLogicalType(*context, it->second.back(), target, result, *decimal_width_limit); + } else { + unified = LogicalType::TryGetMaxLogicalType(*context, it->second.back(), target, result); + } if (unified) { // Type unification was successful if (it->second.back() != result) { @@ -195,7 +209,7 @@ static bool InferTemplateType(optional_ptr context, const Logical source.id() == LogicalTypeId::LIST ? ListType::GetChildType(source) : ArrayType::GetChildType(source); const auto &target_child = target.id() == LogicalTypeId::LIST ? ListType::GetChildType(target) : ArrayType::GetChildType(target); - if (!InferTemplateType(context, source_child, target_child, bindings, failure)) { + if (!InferTemplateType(context, source_child, target_child, bindings, failure, decimal_width_limit)) { return false; } } @@ -208,10 +222,10 @@ static bool InferTemplateType(optional_ptr context, const Logical const auto &target_key = MapType::KeyType(target); const auto &target_val = MapType::ValueType(target); - if (!InferTemplateType(context, source_key, target_key, bindings, failure)) { + if (!InferTemplateType(context, source_key, target_key, bindings, failure, decimal_width_limit)) { return false; } - if (!InferTemplateType(context, source_val, target_val, bindings, failure)) { + if (!InferTemplateType(context, source_val, target_val, bindings, failure, decimal_width_limit)) { return false; } } @@ -231,7 +245,8 @@ static bool InferTemplateType(optional_ptr context, const Logical for (idx_t i = 0; i < common_children; i++) { const auto &source_child_type = source_children[i].second; const auto &target_child_type = target_children[i].second; - if (!InferTemplateType(context, source_child_type, target_child_type, bindings, failure)) { + if (!InferTemplateType(context, source_child_type, target_child_type, bindings, failure, + decimal_width_limit)) { return false; } } @@ -279,13 +294,15 @@ static void SubstituteTemplateType(LogicalType &type, case_insensitive_map_t DeduceTemplates(optional_ptr context, const FunctionSignature &sig, const FunctionCallArguments &call, const vector &filled, - FunctionBinding &binding) { + FunctionBinding &binding, + optional_ptr decimal_width_limit) { FunctionMismatch::TemplateDeduction deduction; case_insensitive_map_t> bindings; for (idx_t i = 0; i < binding.argument_to_parameters.size(); i++) { auto ¶m_type = binding.parameter_types[binding.argument_to_parameters[i]]; auto &arg_type = call.GetArgument(i).type; - if (param_type.IsTemplated() && !InferTemplateType(context, param_type, arg_type, bindings, deduction)) { + if (param_type.IsTemplated() && + !InferTemplateType(context, param_type, arg_type, bindings, deduction, decimal_width_limit)) { deduction.argument = i; return FunctionMismatch::Reason(std::move(deduction)); } @@ -293,7 +310,8 @@ static optional DeduceTemplates(optional_ptrtype(), bindings, deduction)) { + !InferTemplateType(context, param.GetType(), param.GetDefaultValue()->type(), bindings, deduction, + decimal_width_limit)) { return FunctionMismatch::Reason(std::move(deduction)); } } @@ -341,11 +359,10 @@ static idx_t MismatchRank(const FunctionMismatch::Reason &reason) { } } -std::variant FunctionBinder::MatchOverload(optional_ptr context, - idx_t overload, - shared_ptr function, - const FunctionCallArguments &call, - bool explicit_casts) { +std::variant +FunctionBinder::MatchOverload(optional_ptr context, idx_t overload, + shared_ptr function, const FunctionCallArguments &call, + bool explicit_casts, optional_ptr decimal_width_limit) { // every mismatch is counted towards the distance, the most useful one is the reason idx_t mismatches = 0; optional reason; @@ -499,7 +516,7 @@ std::variant FunctionBinder::MatchOverload(op for (auto param_idx : binding.argument_to_parameters) { filled[param_idx] = true; } - auto template_mismatch = DeduceTemplates(context, sig, call, filled, binding); + auto template_mismatch = DeduceTemplates(context, sig, call, filled, binding, decimal_width_limit); if (template_mismatch) { return FunctionMismatch(overload, std::move(function), 0, std::move(*template_mismatch)); } @@ -511,7 +528,8 @@ std::variant FunctionBinder::MatchOverload(op } FunctionBindResult FunctionBinder::SelectFunction(optional_ptr context, const BaseFunctionSet &functions, - const FunctionCallArguments &call, bool explicit_casts) { + const FunctionCallArguments &call, bool explicit_casts, + optional_ptr decimal_width_limit) { // Look for duplicate names identifier_set_t seen_names; for (idx_t i = call.GetPositionalCount(); i < call.GetArgumentCount(); i++) { @@ -526,7 +544,8 @@ FunctionBindResult FunctionBinder::SelectFunction(optional_ptr co vector cheapest; vector mismatches; for (idx_t overload = 0; overload < functions.GetOverloadCount(); overload++) { - auto match = MatchOverload(context, overload, functions.GetSharedOverload(overload), call, explicit_casts); + auto match = MatchOverload(context, overload, functions.GetSharedOverload(overload), call, explicit_casts, + decimal_width_limit); auto binding = std::get_if(&match); if (!binding) { // Once an overload matches, unsuccessful candidates cannot contribute to the result or diagnostics. @@ -570,7 +589,7 @@ FunctionBinding FunctionBinder::MatchFunction(const shared_ptr &functio const vector>> &named_arguments) { FunctionSet functions(function->GetName()); functions.AddFunction(function); - auto selection = SelectFunction(context, functions, {arguments, named_arguments}, true); + auto selection = SelectFunction(context, functions, {arguments, named_arguments}, true, FixedDecimalWidthLimit()); if (!selection) { selection.GetError().Throw(); } @@ -613,7 +632,7 @@ FunctionBinder::SelectFunctionFromArguments(const BaseFunctionSet &functions, const auto implicit_names = AnyOverloadSupportsImplicitArgumentNames(functions); if (is_valid_call) { // Yes. Let's try to bind - auto result = SelectFunction(context, functions, {positional, named}); + auto result = SelectFunction(context, functions, {positional, named}, false, FixedDecimalWidthLimit()); if (result) { return result.GetBinding(); } @@ -644,7 +663,8 @@ FunctionBinder::SelectFunctionFromArguments(const BaseFunctionSet &functions, } } if (TrySplitArguments(arguments, positional, named)) { - auto retry_result = SelectFunction(context, functions, {positional, named}); + auto retry_result = + SelectFunction(context, functions, {positional, named}, false, FixedDecimalWidthLimit()); if (retry_result) { return retry_result.GetBinding(); } @@ -1484,7 +1504,7 @@ FunctionBinder::ResolveScalarFunctionTypes(const FunctionBinding &binding, vecto ResolveIncompleteArgumentTypes(bound_function, arguments); if (bound_function.HasResolveTypesCallback()) { - ResolveScalarFunctionTypesInput input(context, bound_function, arguments); + ResolveScalarFunctionTypesInput input(context, bound_function, arguments, binder, decimal_width_limit); bound_function.GetResolveTypesCallback()(input); VerifyArgumentCount(bound_function, arguments.size()); } @@ -1513,7 +1533,7 @@ FunctionBinder::ResolveScalarFunction(const FunctionBinding &binding, vector FunctionBinder::BindScalarFunction(const FunctionBinding if (result_func->Function().HasBindExpressionCallback()) { // if a bind_expression callback is registered - call it and emit the resulting expression FunctionBindExpressionInput input(context, result_func->FunctionMutable(), result_func->BindInfoMutable().get(), - result_func->GetChildrenMutable()); + result_func->GetChildrenMutable(), this->binder, decimal_width_limit); auto result = result_func->Function().GetBindExpressionCallback()(input); if (result) { // the callback constructs the expression itself @@ -1616,7 +1636,7 @@ FunctionBinder::ResolveAggregateFunction(const FunctionBinding &binding, vector< unique_ptr bind_info; if (bound_function.GetCallbacks().HasBindCallback()) { - BindAggregateFunctionInput input(context, bound_function, children); + BindAggregateFunctionInput input(context, bound_function, children, binder, decimal_width_limit); bind_info = bound_function.GetCallbacks().GetBindCallback()(input); // we may have lost some arguments in the bind @@ -1739,7 +1759,7 @@ FunctionBinder::ResolveWindowFunction(const FunctionBinding &binding, vector bind_info; if (bound_function.HasBindCallback()) { - BindWindowFunctionInput input(context, bound_function, children, order_types, arg_order_types); + BindWindowFunctionInput input(context, bound_function, children, order_types, arg_order_types, binder); bind_info = bound_function.GetBindCallback()(input); // we may have lost some arguments in the bind children.resize(MinValue(bound_function.GetArguments().size(), children.size())); diff --git a/src/duckdb/src/function/pragma/pragma_queries.cpp b/src/duckdb/src/function/pragma/pragma_queries.cpp index 0f4ba89a4..f9fbfeb01 100644 --- a/src/duckdb/src/function/pragma/pragma_queries.cpp +++ b/src/duckdb/src/function/pragma/pragma_queries.cpp @@ -1,19 +1,14 @@ #include "duckdb/common/assert.hpp" -#include "duckdb/catalog/catalog_search_path.hpp" #include "duckdb/common/constants.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/function/pragma/pragma_functions.hpp" -#include "duckdb/main/client_data.hpp" #include "duckdb/main/config.hpp" -#include "duckdb/main/database_manager.hpp" #include "duckdb/main/extension_helper.hpp" #include "duckdb/parser/parser.hpp" -#include "duckdb/parser/qualified_name.hpp" #include "duckdb/parser/statement/copy_statement.hpp" #include "duckdb/parser/statement/export_statement.hpp" #include "duckdb/parser/keyword_helper.hpp" -#include "duckdb/common/enums/on_entry_not_found.hpp" namespace duckdb { @@ -21,24 +16,8 @@ static string PragmaTableInfo(ClientContext &context, const FunctionParameters & return StringUtil::Format("SELECT * FROM pragma_table_info(%s);", SQLString(parameters.values[0].ToString())); } -string PragmaShowTables(const string &database, const string &schema, optional_idx schema_oid) { - string where_clause = ""; - vector where_conditions; - if (schema_oid.IsValid()) { - // the schema was resolved to a (possibly nested) schema entry - filter on its oid - where_conditions.push_back(StringUtil::Format("schema_oid = %llu", schema_oid.GetIndex())); - } else { - if (!database.empty()) { - where_conditions.push_back(StringUtil::Format("lower(database_name) = lower(%s)", SQLString(database))); - } - if (!schema.empty()) { - where_conditions.push_back(StringUtil::Format("lower(schema_name) = lower(%s)", SQLString(schema))); - } - } - if (where_conditions.empty()) { - where_conditions.push_back("in_search_path(database_name, schema_name)"); - } - where_clause = "WHERE " + StringUtil::Join(where_conditions, " AND "); +string PragmaShowTables(const string &filter) { + auto where_clause = "WHERE " + filter; // clang-format off string query = R"EOF( @@ -67,7 +46,7 @@ string PragmaShowTables(const string &database, const string &schema, optional_i } static string PragmaShowTables(ClientContext &context, const FunctionParameters ¶meters) { - return PragmaShowTables(); + return "SHOW TABLES"; } string PragmaShowTablesExpanded() { @@ -82,7 +61,7 @@ string PragmaShowTablesExpanded() { FROM duckdb_tables t JOIN duckdb_columns c USING (table_oid) - GROUP BY database, schema, name + GROUP BY database, schema, name, t.table_oid UNION ALL @@ -96,7 +75,7 @@ string PragmaShowTablesExpanded() { FROM duckdb_views v JOIN duckdb_columns c ON (v.view_oid=c.table_oid) - GROUP BY database, schema, name + GROUP BY database, schema, name, v.view_oid ORDER BY database, schema, name )"; diff --git a/src/duckdb/src/function/scalar/comparison/comparison.cpp b/src/duckdb/src/function/scalar/comparison/comparison.cpp index 5717a36da..84c12509e 100644 --- a/src/duckdb/src/function/scalar/comparison/comparison.cpp +++ b/src/duckdb/src/function/scalar/comparison/comparison.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/function/scalar/comparison_functions.hpp" @@ -81,7 +82,8 @@ static unique_ptr ComparisonBind(BindScalarFunctionInput &input) { auto left_type = ExpressionBinder::GetExpressionReturnType(*arguments[0]); auto right_type = ExpressionBinder::GetExpressionReturnType(*arguments[1]); LogicalType input_type; - if (!BoundComparisonExpression::TryBindComparison(context, left_type, right_type, input_type, TYPE)) { + if (!BoundComparisonExpression::TryBindComparison(context, left_type, right_type, input_type, TYPE, + input.GetDecimalWidthLimit())) { throw BinderException("Cannot compare values of type %s and type %s - an explicit cast is required", left_type.ToString(), right_type.ToString()); } @@ -190,13 +192,14 @@ unique_ptr BoundComparisonExpression::Create(ExpressionType type, un } unique_ptr BoundComparisonExpression::Bind(ClientContext &context, ExpressionType type, - unique_ptr left, unique_ptr right) { + unique_ptr left, unique_ptr right, + optional_ptr binder) { vector> children; children.push_back(std::move(left)); children.push_back(std::move(right)); BoundScalarFunction function(GetComparisonFunction(type)); - BindScalarFunctionInput input(context, function, children); + BindScalarFunctionInput input(context, function, children, binder); function.GetBindCallback()(input); return make_uniq(std::move(function), std::move(children), nullptr, true); } diff --git a/src/duckdb/src/function/scalar/create_sort_key.cpp b/src/duckdb/src/function/scalar/create_sort_key.cpp index eb2fff76e..5ca15fcc4 100644 --- a/src/duckdb/src/function/scalar/create_sort_key.cpp +++ b/src/duckdb/src/function/scalar/create_sort_key.cpp @@ -12,6 +12,7 @@ #include "duckdb/common/enums/order_type.hpp" #include "duckdb/common/radix.hpp" #include "duckdb/common/swar.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/function/scalar/generic_functions.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" @@ -1044,6 +1045,7 @@ unique_ptr DecodeSortKeyBind(BindScalarFunctionInput &input) { idx_t constant_size = 0; child_list_t children; auto result = make_uniq(); + const auto decimal_width_limit = input.GetDecimalWidthLimit(); for (idx_t i = 1; i < arguments.size(); i += 2) { // Parse column definition Value col = input.GetConstant(i); @@ -1055,8 +1057,8 @@ unique_ptr DecodeSortKeyBind(BindScalarFunctionInput &input) { const auto &col_name = col_def.GetName(); auto col_type = col_def.GetType(); if (col_type.IsUnbound()) { - // Resolve the parsed type against the catalog. - col_type = TransformStringToLogicalType(col_type.ToString(), context); + // Resolve the parsed type against the catalog, within the decimal width limit of the bind + col_type = TransformStringToLogicalType(col_type.ToString(), context, &decimal_width_limit); } // Keep track of this to validate the arguments diff --git a/src/duckdb/src/function/scalar/operator/add.cpp b/src/duckdb/src/function/scalar/operator/add.cpp index f951f2068..299e02f5d 100644 --- a/src/duckdb/src/function/scalar/operator/add.cpp +++ b/src/duckdb/src/function/scalar/operator/add.cpp @@ -1,6 +1,9 @@ #include "duckdb/common/operator/add.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/common/types/value.hpp" #include "duckdb/common/types/date.hpp" @@ -347,6 +350,12 @@ hugeint_t DecimalAddOverflowCheck::Operation(hugeint_t left, hugeint_t right) { return result; } +bignum_t AddOperator::Operation(bignum_t left, bignum_t right, StringHeap &heap, BignumArithmeticState &state) { + const BignumIntermediate lhs(left); + const BignumIntermediate rhs(right); + return bignum_t(BignumIntermediate::Add(heap, lhs, rhs)); +} + //===--------------------------------------------------------------------===// // add time operator //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index 58cf027e5..80b83fa8f 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -18,8 +18,10 @@ #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/types/date.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/interval.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/function/scalar/operators.hpp" #include "duckdb/function/scalar/operator_functions.hpp" @@ -30,6 +32,7 @@ #include "duckdb/storage/statistics/numeric_stats.hpp" #include #include +#include namespace duckdb { @@ -111,6 +114,40 @@ static Value NumericStatsValue(const LogicalType &type, hugeint_t value) { return Value::Numeric(type, value); } +//! The bignum_t tier of decimals (width > 38): the operator allocates its result in the heap of the result vector +template +static void BignumDecimalBinaryFunction(DataChunk &args, ExpressionState &state, Vector &result) { + auto &heap = StringVector::GetStringHeap(result); + BignumArithmeticState arithmetic_state(state.GetContext()); + BinaryExecutor::Execute( + args.data[0], args.data[1], result, args.size(), + [&](bignum_t left, bignum_t right) { return OP::Operation(left, right, heap, arithmetic_state); }); +} + +//! Whether an operator has a kernel for the bignum_t tier of decimals +template +struct HasBignumOperation : std::false_type {}; + +template +struct HasBignumOperation< + OP, std::void_t(), std::declval(), + std::declval(), std::declval()))>> + : std::true_type {}; + +//! The physical types of a DECIMAL: the integer tiers and, above 38 digits, bignum_t +template +static scalar_function_t GetScalarDecimalFunction(PhysicalType type) { + if (type == PhysicalType::VARCHAR) { + if constexpr (HasBignumOperation::value) { + return &BignumDecimalBinaryFunction; + } else { + // the bignum_t tier binds exact result widths, so it has no overflow checking kernels + throw InternalException("The bignum_t tier of decimals has no kernel for this operator"); + } + } + return GetScalarIntegerFunction(type); +} + static Value NumericStatsValue(const LogicalType &type, uint64_t value) { D_ASSERT(type.IsNumeric()); return Value::Numeric(type, uhugeint_t(value)); @@ -190,6 +227,43 @@ struct SubtractPropagateStatistics { } }; +//! The bounds of an operation in the bignum_t tier of decimals: the combinations of the input bounds are computed +//! exactly (a cut input bound widens the result bounds), the result overflows when one of them does not fit the +//! width of the result type +template +static bool BignumDecimalPropagateStatistics(const LogicalType &type, const BaseStatistics &lstats, + const BaseStatistics &rstats, Value &new_min, Value &new_max) { + const auto width = DecimalType::GetWidth(type); + const string lblobs[] {BignumStats::MinBlob(lstats), BignumStats::MaxBlob(lstats)}; + const string rblobs[] {BignumStats::MinBlob(rstats), BignumStats::MaxBlob(rstats)}; + const string_t lvals[] {string_t(lblobs[0]), string_t(lblobs[1])}; + const string_t rvals[] {string_t(rblobs[0]), string_t(rblobs[1])}; + StringHeap heap; + BignumArithmeticState state; + string_t min; + string_t max; + for (idx_t l = 0; l < 2; l++) { + for (idx_t r = 0; r < 2; r++) { + // the combination of two bounds is exact in a BIGNUM + auto result = OP::Operation(bignum_t(lvals[l]), bignum_t(rvals[r]), heap, state).data; + if (!DecimalHelper::FitsWidth(bignum_t(result), width)) { + // potential overflow + return true; + } + // the byte order of the BIGNUM encoding is the numeric order + if ((l == 0 && r == 0) || LessThan::Operation(result, min)) { + min = result; + } + if ((l == 0 && r == 0) || GreaterThan::Operation(result, max)) { + max = result; + } + } + } + new_min = Value::DECIMAL(bignum_t(min), width, DecimalType::GetScale(type)); + new_max = Value::DECIMAL(bignum_t(max), width, DecimalType::GetScale(type)); + return false; +} + struct DecimalArithmeticBindData : public FunctionData { DecimalArithmeticBindData() : check_overflow(false) { } @@ -218,7 +292,17 @@ unique_ptr PropagateNumericStats(ClientContext &context, Functio auto &rstats = child_stats[1]; Value new_min, new_max; bool potential_overflow = true; - if (NumericStats::HasMinMax(lstats) && NumericStats::HasMinMax(rstats)) { + const bool bignum_tier = BaseStatistics::GetStatsType(expr.GetReturnType()) == StatisticsType::BIGNUM_STATS; + if (bignum_tier) { + if constexpr (HasBignumOperation::value) { + if (lstats.GetStatsType() == StatisticsType::BIGNUM_STATS && + rstats.GetStatsType() == StatisticsType::BIGNUM_STATS && BignumStats::HasMinMax(lstats) && + BignumStats::HasMinMax(rstats)) { + potential_overflow = + BignumDecimalPropagateStatistics(expr.GetReturnType(), lstats, rstats, new_min, new_max); + } + } + } else if (NumericStats::HasMinMax(lstats) && NumericStats::HasMinMax(rstats)) { switch (expr.GetReturnType().InternalType()) { case PhysicalType::INT8: potential_overflow = @@ -273,13 +357,23 @@ unique_ptr PropagateNumericStats(ClientContext &context, Functio auto &bind_data = input.bind_data->Cast(); bind_data.check_overflow = false; } - expr.FunctionMutable().SetFunctionCallback( - GetScalarIntegerFunction(expr.GetReturnType().InternalType())); + if constexpr (HasBignumOperation::value) { + expr.FunctionMutable().SetFunctionCallback( + GetScalarDecimalFunction(expr.GetReturnType().InternalType())); + } else { + expr.FunctionMutable().SetFunctionCallback( + GetScalarIntegerFunction(expr.GetReturnType().InternalType())); + } expr.FunctionMutable().SetErrorMode(FunctionErrors::CANNOT_ERROR); } - auto result = NumericStats::CreateEmpty(expr.GetReturnType()); - NumericStats::SetMin(result, new_min); - NumericStats::SetMax(result, new_max); + auto result = BaseStatistics::CreateEmpty(expr.GetReturnType()); + if (bignum_tier) { + BignumStats::SetMin(result, new_min); + BignumStats::SetMax(result, new_max); + } else { + NumericStats::SetMin(result, new_min); + NumericStats::SetMax(result, new_max); + } result.CombineValidity(lstats, rstats); return result.ToUnique(); } @@ -328,10 +422,11 @@ unique_ptr PropagateFloatingStats(ClientContext &context, Functi //! Computes the result type of a decimal addition, subtraction or modulo over the given input types template -LogicalType DecimalArithmeticResultType(const vector &input_types, bool &check_overflow) { +LogicalType DecimalArithmeticResultType(const DecimalWidthLimit &decimal_width_limit, + const vector &input_types, bool &check_overflow) { check_overflow = false; // get the max width and scale of the input arguments - uint32_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, max_decimal_width = 0; for (auto &input_type : input_types) { if (input_type.id() == LogicalTypeId::UNKNOWN) { continue; @@ -346,21 +441,27 @@ LogicalType DecimalArithmeticResultType(const vector &input_types, if (width > max_width) { max_width = width; } + if (input_type.id() == LogicalTypeId::DECIMAL) { + max_decimal_width = MaxValue(width, max_decimal_width); + } max_scale = MaxValue(scale, max_scale); max_width_over_scale = MaxValue(width - scale, max_width_over_scale); } D_ASSERT(max_width > 0); - uint32_t required_width = MaxValue(max_scale + max_width_over_scale, max_width); + idx_t required_width = MaxValue(idx_t(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++; } - if (required_width > Decimal::MAX_WIDTH_DECIMAL) { - // target width does not fit in decimal at all: truncate the scale and perform overflow detection + const idx_t width_limit = decimal_width_limit.ResultWidth(max_decimal_width); + if (required_width > width_limit && !Decimal::IsWide(width_limit)) { + // the result does not fit the fixed-size tiers: clamp the width and perform overflow detection check_overflow = true; - required_width = Decimal::MAX_WIDTH_DECIMAL; + required_width = width_limit; } - return LogicalType::DECIMAL(required_width, max_scale); + return LogicalType::DECIMAL( + decimal_width_limit.CheckedWidth(required_width, max_decimal_width, IS_MODULO ? "Modulo" : "Addition"), + max_scale); } //! Resolves the types of a decimal addition, subtraction or modulo, returns whether overflow checks are required @@ -369,7 +470,8 @@ bool ResolveDecimalArithmeticTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); bool check_overflow; auto argument_types = input.GetArgumentTypes(); - auto result_type = DecimalArithmeticResultType(argument_types, check_overflow); + auto result_type = + DecimalArithmeticResultType(input.GetDecimalWidthLimit(), argument_types, check_overflow); // we cast all input types to the specified type for (idx_t i = 0; i < argument_types.size(); i++) { // first check if the cast is necessary @@ -391,7 +493,8 @@ bool ResolveDecimalArithmeticTypes(ResolveScalarFunctionTypesInput &input) { template unique_ptr BindDecimalArithmetic(BindScalarFunctionInput &input) { auto bind_data = make_uniq(); - DecimalArithmeticResultType(input.GetBoundFunction().GetLogicalArguments(), bind_data->check_overflow); + auto &input_types = input.GetBoundFunction().GetLogicalArguments(); + DecimalArithmeticResultType(input.GetDecimalWidthLimit(), input_types, bind_data->check_overflow); return std::move(bind_data); } @@ -403,10 +506,10 @@ void DecimalAddSubtractResolveTypes(ResolveScalarFunctionTypesInput &input) { // now select the physical function to execute auto &result_type = bound_function.GetReturnType(); if (check_overflow) { - bound_function.SetFunctionCallback(GetScalarBinaryFunction(result_type.InternalType())); + bound_function.SetFunctionCallback(GetScalarDecimalFunction(result_type.InternalType())); } else { // the result type holds every result of the operation, so it cannot overflow - bound_function.SetFunctionCallback(GetScalarBinaryFunction(result_type.InternalType())); + bound_function.SetFunctionCallback(GetScalarDecimalFunction(result_type.InternalType())); bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } if (IS_SUBTRACT) { @@ -426,16 +529,16 @@ void SerializeDecimalArithmetic(Serializer &serializer, const optional_ptr +template unique_ptr DeserializeDecimalArithmetic(Deserializer &deserializer, BoundScalarFunction &bound_function) { // // re-change the function pointers auto check_overflow = deserializer.ReadProperty(100, "check_overflow"); auto return_type = deserializer.ReadProperty(101, "return_type"); auto arguments = deserializer.ReadProperty>(102, "arguments"); if (check_overflow) { - bound_function.SetFunctionCallback(GetScalarBinaryFunction(return_type.InternalType())); + bound_function.SetFunctionCallback(GetScalarDecimalFunction(return_type.InternalType())); } else { - bound_function.SetFunctionCallback(GetScalarBinaryFunction(return_type.InternalType())); + bound_function.SetFunctionCallback(GetScalarDecimalFunction(return_type.InternalType())); bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } bound_function.SetStatisticsCallback(nullptr); // TODO we likely dont want to do stats prop again @@ -813,7 +916,10 @@ static void DecimalNegateResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); auto &decimal_type = input.GetArgumentType(0); auto width = DecimalType::GetWidth(decimal_type); - if (width <= Decimal::MAX_WIDTH_INT16) { + if (decimal_type.InternalType() == PhysicalType::VARCHAR) { + // the bignum_t tier negates the BIGNUM blob + bound_function.SetFunctionCallback(BignumNegate); + } else if (width <= Decimal::MAX_WIDTH_INT16) { bound_function.SetFunctionCallback( ScalarFunction::GetScalarUnaryFunction(LogicalTypeId::SMALLINT)); } else if (width <= Decimal::MAX_WIDTH_INT32) { @@ -1130,9 +1236,11 @@ struct MultiplyPropagateStatistics { }; //! Computes the result type of a decimal multiplication over the given input types -LogicalType DecimalMultiplyResultType(const vector &input_types, bool &check_overflow) { +LogicalType DecimalMultiplyResultType(const DecimalWidthLimit &decimal_width_limit, + const vector &input_types, bool &check_overflow) { check_overflow = false; - uint32_t result_width = 0, result_scale = 0, max_width = 0; + idx_t result_width = 0, result_scale = 0; + uint32_t max_width = 0, max_decimal_width = 0; for (auto &input_type : input_types) { if (input_type.id() == LogicalTypeId::UNKNOWN) { continue; @@ -1145,34 +1253,40 @@ LogicalType DecimalMultiplyResultType(const vector &input_types, bo input_type.ToString()); } max_width = MaxValue(width, max_width); + if (input_type.id() == LogicalTypeId::DECIMAL) { + max_decimal_width = MaxValue(width, max_decimal_width); + } result_width += width; result_scale += scale; } D_ASSERT(max_width > 0); - if (result_scale > Decimal::MAX_WIDTH_DECIMAL) { + const idx_t width_limit = decimal_width_limit.ResultWidth(max_decimal_width); + if (result_scale > width_limit) { throw OutOfRangeException( "Needed scale %d to accurately represent the multiplication result, but this is out of range of the " "DECIMAL type. Max scale is %d; could not perform an accurate multiplication. Either add a cast to DOUBLE, " "or add an explicit cast to a decimal with a lower scale.", - result_scale, Decimal::MAX_WIDTH_DECIMAL); + result_scale, width_limit); } if (result_width > Decimal::MAX_WIDTH_INT64 && max_width <= Decimal::MAX_WIDTH_INT64 && result_scale < Decimal::MAX_WIDTH_INT64) { check_overflow = true; result_width = Decimal::MAX_WIDTH_INT64; } - if (result_width > Decimal::MAX_WIDTH_DECIMAL) { + if (result_width > width_limit && !Decimal::IsWide(width_limit)) { + // the result does not fit the fixed-size tiers: clamp the width and perform overflow detection check_overflow = true; - result_width = Decimal::MAX_WIDTH_DECIMAL; + result_width = width_limit; } - return LogicalType::DECIMAL(result_width, result_scale); + return LogicalType::DECIMAL(decimal_width_limit.CheckedWidth(result_width, max_decimal_width, "Multiplication"), + NumericCast(result_scale)); } void DecimalMultiplyResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); bool check_overflow; auto argument_types = input.GetArgumentTypes(); - auto result_type = DecimalMultiplyResultType(argument_types, check_overflow); + auto result_type = DecimalMultiplyResultType(input.GetDecimalWidthLimit(), argument_types, check_overflow); auto result_width = DecimalType::GetWidth(result_type); // since our scale is the summation of our input scales, we do not need to cast to the result scale // however, we might need to cast to the correct internal type @@ -1194,10 +1308,10 @@ void DecimalMultiplyResolveTypes(ResolveScalarFunctionTypesInput &input) { // now select the physical function to execute if (check_overflow) { bound_function.SetFunctionCallback( - GetScalarBinaryFunction(result_type.InternalType())); + GetScalarDecimalFunction(result_type.InternalType())); } else { // the result type holds every product of the input types, so the operation cannot overflow - bound_function.SetFunctionCallback(GetScalarBinaryFunction(result_type.InternalType())); + bound_function.SetFunctionCallback(GetScalarDecimalFunction(result_type.InternalType())); bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } bound_function.SetStatisticsCallback( @@ -1207,7 +1321,8 @@ void DecimalMultiplyResolveTypes(ResolveScalarFunctionTypesInput &input) { //! The overflow check is derived from the types the function was called with, before they were cast unique_ptr BindDecimalMultiply(BindScalarFunctionInput &input) { auto bind_data = make_uniq(); - DecimalMultiplyResultType(input.GetBoundFunction().GetLogicalArguments(), bind_data->check_overflow); + auto &input_types = input.GetBoundFunction().GetLogicalArguments(); + DecimalMultiplyResultType(input.GetDecimalWidthLimit(), input_types, bind_data->check_overflow); return std::move(bind_data); } @@ -1294,6 +1409,10 @@ interval_t DivideOperator::Operation(interval_t left, double right) { return result; } +//! The BIGNUM division and modulo kernel, also the bignum_t tier of the decimal modulo +template +static void BignumDivideOperation(DataChunk &args, ExpressionState &state, Vector &result); + namespace { [[noreturn]] void ThrowDivisionByZero(const Expression &expr) { @@ -1411,6 +1530,9 @@ scalar_function_t GetBinaryFunctionZeroCheck(PhysicalType type) { return BinaryScalarFunctionZeroCheck>; case PhysicalType::DOUBLE: return BinaryScalarFunctionZeroCheck>; + case PhysicalType::VARCHAR: + // the bignum_t tier of decimals divides through the BIGNUM kernel + return BignumDivideOperation::value>; default: throw NotImplementedException("Unimplemented type for GetBinaryFunctionZeroCheck"); } @@ -1774,6 +1896,11 @@ unique_ptr PropagateModuloStats(ClientContext &context, Function D_ASSERT(child_stats.size() == 2); auto &lstats = child_stats[0]; auto &rstats = child_stats[1]; + if (lstats.GetStatsType() != StatisticsType::NUMERIC_STATS || + rstats.GetStatsType() != StatisticsType::NUMERIC_STATS) { + // the bignum_t tier of decimals has no modulo bounds + return nullptr; + } if (!NumericStats::HasMinMax(rstats)) { return nullptr; } diff --git a/src/duckdb/src/function/scalar/operator/decimal_division.cpp b/src/duckdb/src/function/scalar/operator/decimal_division.cpp index 2e8c94c08..ef57f834b 100644 --- a/src/duckdb/src/function/scalar/operator/decimal_division.cpp +++ b/src/duckdb/src/function/scalar/operator/decimal_division.cpp @@ -49,7 +49,7 @@ static constexpr uint8_t DecimalTierWidth() { } else if constexpr (std::is_same_v) { return Decimal::MAX_WIDTH_INT64; } else { - return Decimal::MAX_WIDTH_DECIMAL; + return Decimal::MAX_WIDTH_INT128; } } @@ -219,7 +219,7 @@ 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 -// Both are capped at Decimal::MAX_WIDTH_DECIMAL (38). +// Both are capped at Decimal::MAX_WIDTH_INT128 (38). static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); auto &lhs_type = input.GetArgumentType(0); @@ -229,6 +229,10 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) if (!lhs_type.GetDecimalProperties(p1, s1) || !rhs_type.GetDecimalProperties(p2, s2)) { throw InvalidInputException("decimal_division: both arguments must be DECIMAL"); } + if (Decimal::IsWide(p1) || Decimal::IsWide(p2)) { + throw NotImplementedException("decimal_division is not supported for DECIMAL types wider than %d digits", + Decimal::MAX_WIDTH_INT128); + } // 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); @@ -237,9 +241,9 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) if (input.GetArgumentCount() == 3) { auto scale_val = input.GetNonNullConstant(2); auto scale_i = scale_val.GetValue(); - if (scale_i < 0 || scale_i > Decimal::MAX_WIDTH_DECIMAL) { + if (scale_i < 0 || scale_i > Decimal::MAX_WIDTH_INT128) { throw InvalidInputException("decimal_division: scale must be between 0 and %d, got %d", - Decimal::MAX_WIDTH_DECIMAL, scale_i); + Decimal::MAX_WIDTH_INT128, scale_i); } result_scale = UnsafeNumericCast(scale_i); } else { @@ -253,19 +257,19 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) } uint32_t result_width = UnsafeNumericCast(result_width_i); - if (result_scale > Decimal::MAX_WIDTH_DECIMAL) { + if (result_scale > Decimal::MAX_WIDTH_INT128) { throw OutOfRangeException( "Needed scale %d to accurately represent the division result, but this is out of range of the " "DECIMAL type. Max scale is %d; could not perform an accurate division. Either add a cast to DOUBLE, " "or add an explicit cast to a decimal with a lower scale.", - result_scale, Decimal::MAX_WIDTH_DECIMAL); + result_scale, Decimal::MAX_WIDTH_INT128); } - if (result_width > Decimal::MAX_WIDTH_DECIMAL) { + if (result_width > Decimal::MAX_WIDTH_INT128) { throw OutOfRangeException( "Needed width %d to accurately represent the division result, but this is out of range of the " "DECIMAL type. Max width is %d; could not perform an accurate division. Either add a cast to DOUBLE, " "or add an explicit cast to a decimal with a lower scale.", - result_width, Decimal::MAX_WIDTH_DECIMAL); + result_width, Decimal::MAX_WIDTH_INT128); } bound_function.SetReturnType(LogicalType::DECIMAL(result_width, result_scale)); diff --git a/src/duckdb/src/function/scalar/operator/multiply.cpp b/src/duckdb/src/function/scalar/operator/multiply.cpp index f0394ef90..b98003c0b 100644 --- a/src/duckdb/src/function/scalar/operator/multiply.cpp +++ b/src/duckdb/src/function/scalar/operator/multiply.cpp @@ -1,6 +1,9 @@ #include "duckdb/common/operator/multiply.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/types/hugeint.hpp" @@ -320,4 +323,10 @@ hugeint_t DecimalMultiplyOverflowCheck::Operation(hugeint_t left, hugeint_t righ return result; } +bignum_t MultiplyOperator::Operation(bignum_t left, bignum_t right, StringHeap &heap, BignumArithmeticState &state) { + const BignumIntermediate lhs(left); + const BignumIntermediate rhs(right); + return bignum_t(BignumIntermediate::Multiply(heap, state, lhs, rhs)); +} + } // namespace duckdb diff --git a/src/duckdb/src/function/scalar/operator/subtract.cpp b/src/duckdb/src/function/scalar/operator/subtract.cpp index 87cd193d6..08b345fc0 100644 --- a/src/duckdb/src/function/scalar/operator/subtract.cpp +++ b/src/duckdb/src/function/scalar/operator/subtract.cpp @@ -1,6 +1,9 @@ #include "duckdb/common/operator/subtract.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" @@ -251,6 +254,15 @@ hugeint_t DecimalSubtractOverflowCheck::Operation(hugeint_t left, hugeint_t righ return result; } +bignum_t SubtractOperator::Operation(bignum_t left, bignum_t right, StringHeap &heap, BignumArithmeticState &state) { + const BignumIntermediate lhs(left); + // the right operand is negated on a copy, its bytes can be shared with the left operand and other rows + const BignumIntermediate rhs_value(right); + const bignum_t negated_rhs(rhs_value.Negate(heap)); + const BignumIntermediate rhs(negated_rhs); + return bignum_t(BignumIntermediate::Add(heap, lhs, rhs)); +} + //===--------------------------------------------------------------------===// // subtract time operator //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/function/scalar/string/concat.cpp b/src/duckdb/src/function/scalar/string/concat.cpp index f32de3e62..e370de038 100644 --- a/src/duckdb/src/function/scalar/string/concat.cpp +++ b/src/duckdb/src/function/scalar/string/concat.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/constant_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -251,7 +252,8 @@ void ResolveListConcatTypes(ResolveScalarFunctionTypesInput &input, bool is_oper throw BinderException(arg, "Cannot concatenate types %s - an explicit cast is required", type_list); } } - if (!LogicalType::TryGetMaxLogicalType(context, child_type, next_type, child_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, child_type, next_type, child_type, + input.GetDecimalWidthLimit())) { throw BinderException(arg, "Cannot concatenate lists of types %s[] and %s[] - an explicit cast is required", child_type.ToString(), next_type.ToString()); } diff --git a/src/duckdb/src/function/scalar/struct/struct_contains.cpp b/src/duckdb/src/function/scalar/struct/struct_contains.cpp index 26ed917df..f8fa4ad6f 100644 --- a/src/duckdb/src/function/scalar/struct/struct_contains.cpp +++ b/src/duckdb/src/function/scalar/struct/struct_contains.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/constant_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/map_vector.hpp" @@ -256,7 +257,8 @@ static void StructContainsResolveTypes(ResolveScalarFunctionTypesInput &input) { LogicalType target_type = arguments[1]->GetReturnType(); for (auto &child : struct_children) { LogicalType max_type; - if (LogicalType::TryGetMaxLogicalType(context, child.second, target_type, max_type)) { + if (LogicalType::TryGetMaxLogicalType(context, child.second, target_type, max_type, + input.GetDecimalWidthLimit())) { target_type = max_type; } } @@ -266,7 +268,8 @@ static void StructContainsResolveTypes(ResolveScalarFunctionTypesInput &input) { for (idx_t child_idx = 0; child_idx < struct_children.size(); child_idx++) { auto &struct_child_type = struct_children[child_idx].second; LogicalType max_type; - if (LogicalType::TryGetMaxLogicalType(context, struct_child_type, target_type, max_type) && + if (LogicalType::TryGetMaxLogicalType(context, struct_child_type, target_type, max_type, + input.GetDecimalWidthLimit()) && max_type == target_type) { new_child_types.push_back(target_type); } else { diff --git a/src/duckdb/src/function/scalar/system/aggregate_export.cpp b/src/duckdb/src/function/scalar/system/aggregate_export.cpp index 5126430d5..6bfad32c9 100644 --- a/src/duckdb/src/function/scalar/system/aggregate_export.cpp +++ b/src/duckdb/src/function/scalar/system/aggregate_export.cpp @@ -233,12 +233,14 @@ void AggregateStateCombine(DataChunk &input, ExpressionState &state_p, Vector &r } } -// looks up the aggregate function with the given name in the catalog and binds it with the given argument types +// looks up the aggregate function with the given name in the catalog and binds it with the given argument types, +// within the decimal width of the function binder (the expression that rebinds the aggregate binds within it) // constant_parameters holds the values of arguments that must be re-bound with a specific constant // (e.g. string_agg's separator), keyed by argument index - all other arguments are bound with a NULL value -unique_ptr BindExportedAggregate(ClientContext &context, const string &function_name, +unique_ptr BindExportedAggregate(FunctionBinder &function_binder, const string &function_name, const vector &argument_types, const map &constant_parameters) { + auto &context = function_binder.context; auto &func = Catalog::GetSystemCatalog(context).GetEntry( context, QualifiedName(Catalog::GetSystemCatalog(context).GetName(), Identifier::DefaultSchema(), Identifier(function_name))); @@ -247,8 +249,8 @@ unique_ptr BindExportedAggregate(ClientContext &context } auto &aggr_entry = func.Cast(); - FunctionBinder function_binder(context); - auto best_function = FunctionBinder::SelectFunction(context, aggr_entry.functions, argument_types); + auto best_function = FunctionBinder::SelectFunction(context, aggr_entry.functions, argument_types, false, + function_binder.FixedDecimalWidthLimit()); if (!best_function.IsSuccess()) { throw BinderException("Could not re-bind exported aggregate %s: %s", function_name, best_function.GetError().Message()); @@ -349,8 +351,10 @@ void ParseStateParameters(const Value ¶meters, vector &argument // parses an ORDER BY spec (a list of {column, order} structs) - shared by the re-bind path and to_aggregate_state void ParseOrderBys(const Value &order_value, idx_t column_count, vector &orders); -unique_ptr BindAggregateStateInternal(ClientContext &context, BoundSimpleFunction &function, +unique_ptr BindAggregateStateInternal(FunctionBinder &function_binder, + BoundSimpleFunction &function, vector> &arguments) { + auto &context = function_binder.context; auto &arg_return_type = arguments[0]->GetReturnType(); if (!arg_return_type.IsAggregateState()) { throw BinderException("Can only %s %s, not AGGREGATE_STATE", function.GetName(), arg_return_type.ToString()); @@ -375,7 +379,7 @@ unique_ptr BindAggregateStateInternal(ClientContext &co map constant_parameters; ParseStateParameters(entry->second, argument_types, constant_parameters); - auto inner = BindExportedAggregate(context, function_name, argument_types, constant_parameters); + auto inner = BindExportedAggregate(function_binder, function_name, argument_types, constant_parameters); auto order_entry = ext_info->properties.find("order_bys"); if (order_entry == ext_info->properties.end()) { @@ -409,8 +413,8 @@ unique_ptr BindAggregateStateInternal(ClientContext &co unique_ptr BindAggregateState(BindScalarFunctionInput &input) { auto &bound_function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto bind_data = - BindAggregateStateInternal(input.GetClientContext(), input.GetBoundFunction(), input.GetArguments()); + auto function_binder = input.NestedFunctionBinder(); + auto bind_data = BindAggregateStateInternal(function_binder, bound_function, arguments); // combine - both arguments must be aggregate states of the same function with the same signature if (arguments.size() == 2 && arguments[0]->GetReturnType() != arguments[1]->GetReturnType()) { @@ -495,7 +499,8 @@ unique_ptr CombineAggrBind(BindAggregateFunctionInput &input) { auto &arguments = input.GetArguments(); D_ASSERT(arguments.size() == 1 || arguments.size() == 2); - auto bind_data = BindAggregateStateInternal(input.GetClientContext(), function, arguments); + auto function_binder = input.NestedFunctionBinder(); + auto bind_data = BindAggregateStateInternal(function_binder, function, arguments); // Copy underlying aggregate's callbacks into this function (same pattern as `ExportAggregateFunction::Bind`) function.SetStateSizeCallback(bind_data->aggr.GetStateSizeCallback()); @@ -648,8 +653,8 @@ LogicalType CreateSortedAggregateStateType(const BoundAggregateFunction &inner_f } // parses a single entry of the to_aggregate_state signature list - either a TYPE value (e.g. make_type('VARCHAR')) -// or a string naming a type (e.g. 'VARCHAR') -LogicalType ParseSignatureType(ClientContext &context, const Value &arg) { +// or a string naming a type (e.g. 'VARCHAR'), bound within the decimal width limit of the bind +LogicalType ParseSignatureType(ClientContext &context, const Value &arg, const DecimalWidthLimit &decimal_width_limit) { if (arg.IsNull()) { throw BinderException("to_aggregate_state: the signature cannot contain NULL values"); } @@ -662,7 +667,7 @@ LogicalType ParseSignatureType(ClientContext &context, const Value &arg) { if (StringUtil::CIEquals(name, "ANY")) { return LogicalType::ANY; } - return TransformStringToLogicalType(name, context); + return TransformStringToLogicalType(name, context, &decimal_width_limit); } throw BinderException("to_aggregate_state: the signature must be a list of types"); } @@ -764,10 +769,11 @@ unique_ptr BindToAggregateState(INPUT &input) { if (signature_val.type().id() != LogicalTypeId::LIST) { throw BinderException("to_aggregate_state: the signature must be a list of types"); } - // the signature lists all of the argument types in order + // the signature lists all of the argument types in order, bound within the width limit of the bind + const auto decimal_width_limit = input.GetDecimalWidthLimit(); vector argument_types; for (auto &arg : ListValue::GetChildren(signature_val)) { - argument_types.push_back(ParseSignatureType(context, arg)); + argument_types.push_back(ParseSignatureType(context, arg, decimal_width_limit)); } // constant_parameters holds the values of arguments that must be re-bound with a specific constant rather than a @@ -782,7 +788,8 @@ unique_ptr BindToAggregateState(INPUT &input) { entry.second = entry.second.CastAs(context, argument_types[entry.first]); } - auto bind_data = BindExportedAggregate(context, function_name, argument_types, constant_parameters); + auto function_binder = input.NestedFunctionBinder(); + auto bind_data = BindExportedAggregate(function_binder, function_name, argument_types, constant_parameters); auto &aggr = bind_data->aggr; if (!aggr.HasGetStateTypeCallback()) { throw BinderException( diff --git a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp index 43bc7539d..de6987d07 100644 --- a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp @@ -351,6 +351,12 @@ void GetTypedBounds(const BaseStatistics &typed_stats, Value &min_bound, Value & max_bound = NumericStats::Max(typed_stats); } break; + case StatisticsType::BIGNUM_STATS: + if (BignumStats::HasMinMax(typed_stats)) { + min_bound = BignumStats::Min(typed_stats); + max_bound = BignumStats::Max(typed_stats); + } + break; case StatisticsType::STRING_STATS: // only VARCHAR has UTF-8 ordered min/max we can turn into valid lower/upper bounds if (typed_stats.GetType().id() == LogicalTypeId::VARCHAR) { diff --git a/src/duckdb/src/function/scalar/variant/variant_utils.cpp b/src/duckdb/src/function/scalar/variant/variant_utils.cpp index 1ff008625..228241603 100644 --- a/src/duckdb/src/function/scalar/variant/variant_utils.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_utils.cpp @@ -16,7 +16,10 @@ namespace duckdb { PhysicalType VariantDecimalData::GetPhysicalType() const { - if (width > DecimalWidth::max) { + if (width > DecimalWidth::max) { + // decimals wider than 38 digits are BIGNUM blobs + return PhysicalType::VARCHAR; + } else if (width > DecimalWidth::max) { return PhysicalType::INT128; } else if (width > DecimalWidth::max) { return PhysicalType::INT64; @@ -56,6 +59,18 @@ VariantDecimalData VariantUtils::DecodeDecimalData(const UnifiedVariantVectorDat return VariantDecimalData(width, scale, value_ptr); } +string_t VariantUtils::DecodeWideDecimalData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t value_index) { + auto decimal = DecodeDecimalData(variant, row, value_index); + D_ASSERT(decimal.GetPhysicalType() == PhysicalType::VARCHAR); + auto &blob = variant.GetData(row); + auto data = const_data_ptr_cast(blob.GetData()); + auto ptr = decimal.value_ptr; + VariantUtils::Available(blob.GetSize(), NumericCast(ptr - data), 1); + auto length = VarintDecode(ptr); + VariantUtils::Available(blob.GetSize(), NumericCast(ptr - data), length); + return string_t(reinterpret_cast(ptr), length); +} + string_t VariantUtils::DecodeStringData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t value_index) { auto byte_offset = variant.GetByteOffset(row, value_index); auto &blob = variant.GetData(row); diff --git a/src/duckdb/src/function/scalar_function.cpp b/src/duckdb/src/function/scalar_function.cpp index f584ff9de..28dcc230d 100644 --- a/src/duckdb/src/function/scalar_function.cpp +++ b/src/duckdb/src/function/scalar_function.cpp @@ -1,5 +1,7 @@ #include "duckdb/function/scalar_function.hpp" #include "duckdb/function/function_binder.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/parser/parsed_expression.hpp" @@ -14,6 +16,16 @@ FunctionUnbindInput::FunctionUnbindInput(const BoundFunctionExpression &expressi FunctionUnbindInput::~FunctionUnbindInput() { } +DecimalWidthLimit FunctionBindExpressionInput::GetDecimalWidthLimit() const { + if (binder) { + return binder->GetDecimalWidthLimit(); + } + if (decimal_width_limit) { + return *decimal_width_limit; + } + return DecimalWidthLimit::FromSetting(context); +} + void ThrowNonFallibleFunctionError(const Identifier &name, std::exception &ex) { ErrorData error(ex); if (!Exception::IsExecutionError(error.Type())) { 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 9465106c4..03bf9ab73 100644 --- a/src/duckdb/src/function/table/arrow/arrow_duck_schema.cpp +++ b/src/duckdb/src/function/table/arrow/arrow_duck_schema.cpp @@ -114,7 +114,8 @@ unique_ptr ArrowType::GetTypeFromFormat(string &format) { // We have a bit-width defined bitwidth = std::stoull(parameters[2]); } - if (width > 38 || bitwidth > 128) { + // decimal256 holds up to 76 digits, above 38 digits it becomes a wide (BIGNUM-backed) DuckDB decimal + if (width > 76 || bitwidth > 256 || (width > 38 && bitwidth < 256) || scale > width) { throw NotImplementedException("Unsupported Internal Arrow Type for Decimal %s", format); } switch (bitwidth) { diff --git a/src/duckdb/src/function/table/arrow_conversion.cpp b/src/duckdb/src/function/table/arrow_conversion.cpp index 18dec3070..ee46d150b 100644 --- a/src/duckdb/src/function/table/arrow_conversion.cpp +++ b/src/duckdb/src/function/table/arrow_conversion.cpp @@ -10,6 +10,7 @@ #include "duckdb/common/limits.hpp" #include "duckdb/common/operator/multiply.hpp" #include "duckdb/common/types/arrow_aux_data.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/arrow_string_view_type.hpp" #include "duckdb/function/table/arrow.hpp" @@ -879,6 +880,59 @@ static void ConvertDecimal(Vector &vector, ArrowArray &array, idx_t size, idx_t } } +//! Converts 32-byte little-endian two's complement Arrow decimal256 values into wide or fixed-size decimals +static void ConvertDecimal256(const_data_ptr_t src_ptr, Vector &vector, idx_t size, ValidityMask &val_mask) { + constexpr idx_t DECIMAL256_BYTES = 32; + switch (vector.GetType().InternalType()) { + case PhysicalType::VARCHAR: { + auto tgt_ptr = FlatVector::GetDataMutable(vector); + for (idx_t row = 0; row < size; row++) { + if (!val_mask.RowIsValid(row)) { + continue; + } + auto blob = + DecimalHelper::FromTwosComplement(src_ptr + row * DECIMAL256_BYTES, DECIMAL256_BYTES, false); + tgt_ptr[row] = bignum_t(StringVector::AddStringOrBlob(vector, blob.data(), blob.size())); + } + break; + } + case PhysicalType::INT16: + case PhysicalType::INT32: + case PhysicalType::INT64: + case PhysicalType::INT128: { + for (idx_t row = 0; row < size; row++) { + if (!val_mask.RowIsValid(row)) { + continue; + } + auto blob = + DecimalHelper::FromTwosComplement(src_ptr + row * DECIMAL256_BYTES, DECIMAL256_BYTES, false); + hugeint_t value; + if (!DecimalHelper::TryToHugeint(bignum_t(string_t(blob)), value)) { + throw ConversionException("Arrow decimal256 value does not fit in %s", vector.GetType().ToString()); + } + switch (vector.GetType().InternalType()) { + case PhysicalType::INT16: + FlatVector::GetDataMutable(vector)[row] = Cast::Operation(value); + break; + case PhysicalType::INT32: + FlatVector::GetDataMutable(vector)[row] = Cast::Operation(value); + break; + case PhysicalType::INT64: + FlatVector::GetDataMutable(vector)[row] = Cast::Operation(value); + break; + default: + FlatVector::GetDataMutable(vector)[row] = value; + break; + } + } + break; + } + default: + throw NotImplementedException("Unsupported physical type for Decimal: %s", + TypeIdToString(vector.GetType().InternalType())); + } +} + void ArrowToDuckDBConversion::ColumnArrowToDuckDB(Vector &vector, ArrowArray &array, idx_t chunk_offset, ArrowArrayScanState &array_state, idx_t size, const ArrowType &arrow_type, int64_t nested_offset, @@ -1210,6 +1264,12 @@ void ArrowToDuckDBConversion::ColumnArrowToDuckDB(Vector &vector, ArrowArray &ar case DecimalBitWidth::DECIMAL_128: ConvertDecimal(vector, array, size, offset); break; + case DecimalBitWidth::DECIMAL_256: { + auto src_ptr = ArrowBufferData(array, 1) + 32 * offset; + auto &val_mask = FlatVector::ValidityMutable(vector); + ConvertDecimal256(src_ptr, vector, size, val_mask); + break; + } default: throw NotImplementedException("Unsupported precision for Arrow Decimal Type."); } diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index 305741049..a834e7db8 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -1023,7 +1023,8 @@ unique_ptr TableScanInitGlobal(ClientContext &context, bool index_scan = false; RowIdVectorOutput row_ids(max_count); - info->BindIndexes(context, ART::TYPE_NAME); + // a read does not need an index whose stored keys do not match: it is left unbound and the scan does without it + info->BindIndexes(context, ART::TYPE_NAME, true); // Exclude rowid-shifting vacuum from the ART probe until the index scan finishes: collected rowids must be // fetched against the matching row-group tree. Falling back to a table scan releases the lock on return. diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index 9f6dcce81..c5712684f 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-alpha55910" +#define DUCKDB_PATCH_VERSION "0-alpha55959" #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-alpha55910" +#define DUCKDB_VERSION "v2.1.0-alpha55959" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "6f053d3d8f" +#define DUCKDB_SOURCE_ID "a2deaf15a4" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/type_constructor.cpp b/src/duckdb/src/function/type_constructor.cpp index b28f765c0..ad916ec8f 100644 --- a/src/duckdb/src/function/type_constructor.cpp +++ b/src/duckdb/src/function/type_constructor.cpp @@ -194,7 +194,8 @@ string TypeConstructor::ToString() const { } LogicalType TypeConstructorSet::Bind(optional_ptr context, const LogicalType &base_type, - const vector &arguments, QueryLocation query_location) const { + const vector &arguments, QueryLocation query_location, + optional_ptr decimal_width_limit) const { D_ASSERT(!functions.empty()); // Fast path for the common case: a single constructor taking no modifiers, which is every type that is not @@ -206,7 +207,7 @@ LogicalType TypeConstructorSet::Bind(optional_ptr context, const throw BinderException(query_location, "Type %s does not take any type parameters", name); } vector modifiers; - BindLogicalTypeInput input {context, base_type, modifiers, query_location}; + BindLogicalTypeInput input {context, base_type, modifiers, query_location, decimal_width_limit}; return functions[0]->GetBindFunction()(input); } } @@ -236,7 +237,7 @@ LogicalType TypeConstructorSet::Bind(optional_ptr context, const auto &constructor = *constructor_ptr; auto modifiers = NormalizeArguments(name, constructor, arguments, query_location); - BindLogicalTypeInput input {context, base_type, modifiers, query_location}; + BindLogicalTypeInput input {context, base_type, modifiers, query_location, decimal_width_limit}; return constructor.GetBindFunction()(input); } diff --git a/src/duckdb/src/function/variant/variant_shredding.cpp b/src/duckdb/src/function/variant/variant_shredding.cpp index 7a885894a..a71cf3b73 100644 --- a/src/duckdb/src/function/variant/variant_shredding.cpp +++ b/src/duckdb/src/function/variant/variant_shredding.cpp @@ -43,6 +43,21 @@ static void WriteShreddedDecimal(UnifiedVariantVectorData &variant, Vector &resu } } +//! Decimals wider than 38 digits are BIGNUM blobs +static void WriteShreddedWideDecimal(UnifiedVariantVectorData &variant, Vector &result, const SelectionVector &sel, + const SelectionVector &value_index_sel, const SelectionVector &result_sel, + idx_t count) { + auto result_data = FlatVector::ScatterWriter(result); + for (idx_t i = 0; i < count; i++) { + auto row = sel[i]; + auto result_row = result_sel[i]; + auto value_index = value_index_sel[i]; + D_ASSERT(variant.RowIsValid(row) && variant.GetTypeId(row, value_index) == VariantLogicalType::DECIMAL); + + result_data[result_row] = VariantUtils::DecodeWideDecimalData(variant, row, value_index); + } +} + #ifdef D_ASSERT_IS_ENABLED static bool IsVariantStringType(VariantLogicalType type_id) { switch (type_id) { @@ -142,6 +157,9 @@ void VariantShredding::WriteTypedPrimitiveValues(UnifiedVariantVectorData &varia case PhysicalType::INT128: WriteShreddedDecimal(variant, result, sel, value_index_sel, result_sel, count); break; + case PhysicalType::VARCHAR: + WriteShreddedWideDecimal(variant, result, sel, value_index_sel, result_sel, count); + break; default: throw InvalidInputException("Can't shred on column of type '%s'", type.ToString()); } diff --git a/src/duckdb/src/function/window/window_boundaries_state.cpp b/src/duckdb/src/function/window/window_boundaries_state.cpp index 7164fbb70..b2f71a4e3 100644 --- a/src/duckdb/src/function/window/window_boundaries_state.cpp +++ b/src/duckdb/src/function/window/window_boundaries_state.cpp @@ -287,6 +287,10 @@ static idx_t FindRangeBound(WindowCursor &range_lo, WindowCursor &range_hi, cons case PhysicalType::INTERVAL: return FindTypedRangeBound(range_lo, range_hi, order_begin, order_end, range, boundary, chunk_idx, prev); + case PhysicalType::VARCHAR: + // wide decimals: the byte order of the BIGNUM blobs is their numeric order + return FindTypedRangeBound(range_lo, range_hi, order_begin, order_end, range, boundary, + chunk_idx, prev); default: throw InternalException("Unsupported column type for RANGE"); } diff --git a/src/duckdb/src/function/window/window_value_function.cpp b/src/duckdb/src/function/window/window_value_function.cpp index e1f2adcdf..011fc958a 100644 --- a/src/duckdb/src/function/window/window_value_function.cpp +++ b/src/duckdb/src/function/window/window_value_function.cpp @@ -1,3 +1,6 @@ +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/decimal_helper.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/function/window/window_executor.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/cast_operators.hpp" @@ -1304,6 +1307,12 @@ double LossyFillCast(uhugeint_t val) { return d; } +//! The bignum_t tier of decimals interpolates on the unscaled value, like the fixed-size tiers +template <> +double LossyFillCast(bignum_t val) { + return DecimalHelper::ToDouble(val, 0); +} + template static double FillSlopeFunc(WindowCursor &cursor, idx_t row_idx, idx_t prev_valid, idx_t next_valid) { // Cast everything to doubles immediately so we can interpolate backwards (x < x0) @@ -1353,6 +1362,8 @@ static fill_slope_t GetFillSlopeFunction(const LogicalType &type) { return FillSlopeFunc; case PhysicalType::DOUBLE: return FillSlopeFunc; + case PhysicalType::VARCHAR: + return FillSlopeFunc; default: throw InternalException("Unsupported FILL slope type."); } @@ -1442,6 +1453,87 @@ static void FillInterpolateFunc(Vector &result, idx_t i, WindowCursor &cursor, i data[i] = InterpolateOperator::Operation(y0, slope, y1); } +//! The delta between the ends of a wide FILL scaled by the slope and truncated towards zero, as the hugeint tier +//! computes it in DOUBLE; beyond the DOUBLE range the slope is applied exactly as mantissa / 2^shift, with the power +//! of two as a BIGNUM so that a tiny slope keeps every mantissa bit. Reports whether a fraction was dropped and +//! the sign of the scaled delta, which decide the truncation of an extrapolated sum +static string ScaleFillDelta(const bignum_t &delta, double slope, StringHeap &heap, BignumArithmeticState &state, + bool &fraction_dropped, bool &negative) { + const auto scaled = DecimalHelper::ToDouble(delta, 0) * slope; + if (std::isfinite(scaled)) { + const auto integer_part = std::trunc(scaled); + fraction_dropped = scaled != integer_part; + negative = scaled < 0; + return DecimalHelper::FromDouble(integer_part); + } + int exponent; + const double fraction = std::frexp(std::fabs(slope), &exponent); + const auto mantissa = static_cast(std::ldexp(fraction, 53)); + const int shift = 53 - exponent; + const string mantissa_blob = DecimalHelper::FromInteger(hugeint_t(slope < 0 ? -mantissa : mantissa)); + const bignum_t mantissa_value {string_t(mantissa_blob)}; + const BignumIntermediate mantissa_intermediate(mantissa_value); + const BignumIntermediate delta_intermediate(delta); + const bignum_t product {BignumIntermediate::Multiply(heap, state, delta_intermediate, mantissa_intermediate)}; + const BignumIntermediate product_intermediate(product); + negative = DecimalHelper::IsNegative(product); + fraction_dropped = false; + const string power_blob = DecimalHelper::PowerOfTwo(NumericCast(std::abs(shift))); + const bignum_t power_value {string_t(power_blob)}; + const BignumIntermediate power(power_value); + if (shift < 0) { + return BignumIntermediate::Multiply(heap, state, product_intermediate, power).GetString(); + } + string_t quotient; + string_t remainder; + if (!BignumIntermediate::TryDivMod(heap, state, product_intermediate, power, quotient, remainder)) { + throw InternalException("FILL: division by a power of two failed"); + } + fraction_dropped = !DecimalHelper::IsZero(bignum_t(remainder)); + return quotient.GetString(); +} + +//! The bignum_t tier of decimals, which rounds like the hugeint tier: the exact delta between the ends is scaled by the +//! slope, an interpolation truncates the scaled delta towards zero and an extrapolation the sum, NULL if the result +//! does not fit the width +static void FillInterpolateBignum(Vector &result, idx_t i, WindowCursor &cursor, idx_t lo, idx_t hi, double slope) { + if (!std::isfinite(slope)) { + return; + } + // an intermediate refers to the bytes of the bignum_t it is built from, which therefore outlives it + StringHeap heap; + BignumArithmeticState state; + const auto y0 = cursor.GetCell(0, lo); + const auto y1 = cursor.GetCell(0, hi); + const BignumIntermediate start(y0); + const BignumIntermediate end(y1); + const bignum_t negated_start {start.Negate(heap)}; + const BignumIntermediate negated(negated_start); + const bignum_t delta {BignumIntermediate::Add(heap, end, negated)}; + bool fraction_dropped; + bool scaled_negative; + const string offset_blob = ScaleFillDelta(delta, slope, heap, state, fraction_dropped, scaled_negative); + const bignum_t offset_value {string_t(offset_blob)}; + const BignumIntermediate offset(offset_value); + bignum_t filled {BignumIntermediate::Add(heap, start, offset)}; + // an extrapolation truncates the sum: a dropped fraction of the opposite sign moves it one towards zero + const bool extrapolating = slope < 0 || slope > 1; + if (extrapolating && fraction_dropped && !DecimalHelper::IsZero(filled) && + DecimalHelper::IsNegative(filled) != scaled_negative) { + const BignumIntermediate sum(filled); + const string step_blob = + DecimalHelper::FromInteger(hugeint_t(DecimalHelper::IsNegative(filled) ? 1 : -1)); + const bignum_t step_value {string_t(step_blob)}; + const BignumIntermediate step(step_value); + filled = bignum_t(BignumIntermediate::Add(heap, sum, step)); + } + if (!DecimalHelper::FitsWidth(filled, DecimalType::GetWidth(result.GetType()))) { + return; + } + FlatVector::GetDataMutable(result)[i] = StringVector::AddStringOrBlob(result, filled.data); + FlatVector::SetNull(result, i, false); +} + static fill_interpolate_t GetFillInterpolateFunction(const LogicalType &type) { switch (type.InternalType()) { case PhysicalType::UINT8: @@ -1468,6 +1560,8 @@ static fill_interpolate_t GetFillInterpolateFunction(const LogicalType &type) { return FillInterpolateFunc; case PhysicalType::DOUBLE: return FillInterpolateFunc; + case PhysicalType::VARCHAR: + return FillInterpolateBignum; default: throw InternalException("Unsupported FILL interpolation type."); } @@ -1485,12 +1579,7 @@ static bool FillValidateTime(Vector &result, idx_t i, const LogicalType &type) { template static bool FillValidateDecimal(Vector &result, idx_t i, const LogicalType &type) { - const auto value = FlatVector::GetData(result)[i]; - T limit; - if (!TryCast::Operation(Hugeint::POWERS_OF_TEN[DecimalType::GetWidth(type)], limit)) { - return true; - } - return value < limit && value > -limit; + return DecimalHelper::FitsWidth(FlatVector::GetData(result)[i], DecimalType::GetWidth(type)); } template @@ -1535,6 +1624,8 @@ static fill_validate_t GetFillValidateFunction(const LogicalType &type) { return FillValidateDecimal; case PhysicalType::INT128: return FillValidateDecimal; + case PhysicalType::VARCHAR: + return FillValidateDecimal; default: throw InternalException("Unsupported FILL decimal type."); } @@ -1550,6 +1641,10 @@ static bool FillValueFunction(idx_t row_idx, WindowCursor &cursor) { return !cursor.CellIsNull(0, row_idx) && Value::IsFinite(cursor.GetCell(0, row_idx)); } +static bool FillValueBignum(idx_t row_idx, WindowCursor &cursor) { + return !cursor.CellIsNull(0, row_idx); +} + static fill_value_t GetFillValueFunction(const LogicalType &type) { // Special cases temporal values because they can have infinities switch (type.id()) { @@ -1591,6 +1686,8 @@ static fill_value_t GetFillValueFunction(const LogicalType &type) { return FillValueFunction; case PhysicalType::DOUBLE: return FillValueFunction; + case PhysicalType::VARCHAR: + return FillValueBignum; default: throw InternalException("Unsupported FILL value type."); } diff --git a/src/duckdb/src/function/window_function.cpp b/src/duckdb/src/function/window_function.cpp index 78be453db..ebf10790a 100644 --- a/src/duckdb/src/function/window_function.cpp +++ b/src/duckdb/src/function/window_function.cpp @@ -59,8 +59,10 @@ bool BoundWindowFunction::operator!=(const BoundWindowFunction &rhs) const { BindWindowFunctionInput::BindWindowFunctionInput(ClientContext &context_p, BoundWindowFunction &bound_function_p, vector> &arguments_p, - OptionalOrderTypes order_types_p, OptionalOrderTypes arg_order_types_p) - : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p), + OptionalOrderTypes order_types_p, OptionalOrderTypes arg_order_types_p, + optional_ptr binder_p) + : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p, + binder_p), bound_function(bound_function_p), order_types(order_types_p), arg_order_types(arg_order_types_p) { } diff --git a/src/duckdb/src/include/duckdb.h b/src/duckdb/src/include/duckdb.h index 292cd2edc..9dd471822 100644 --- a/src/duckdb/src/include/duckdb.h +++ b/src/duckdb/src/include/duckdb.h @@ -733,7 +733,9 @@ struct duckdb_uhugeint { }; /*! - * DECIMAL is composed of a width and a scale. Value is stored in a HUGEINT. + * DECIMAL is composed of a width and a scale. Value is stored in a HUGEINT. Decimals wider than 38 digits store their + * value as BIGNUM; a duckdb_decimal can only carry those whose width fits in the uint8_t and whose value fits in 128 + * bits, the exact value is available through the VARCHAR conversions. * * history: * - stable: v0.3.3 @@ -5282,6 +5284,8 @@ DUCKDB_C_API duckdb_logical_type duckdb_create_enum_type(const char **member_nam * Creates a DECIMAL type with the specified width and scale. The resulting type should be destroyed with * `duckdb_destroy_logical_type`. * + * The uint8_t parameters reach widths up to 255; widths above 38 create wide decimals stored as BIGNUM. + * * history: * - stable: v0.3.3 * @@ -5309,6 +5313,9 @@ DUCKDB_C_API duckdb_type duckdb_get_type_id(duckdb_logical_type type); /*! * Retrieves the width of a decimal type. * + * The uint8_t reaches widths up to 255; a wider decimal reports 0, its values are best read through their VARCHAR + * conversion. + * * history: * - stable: v0.3.3 * @@ -5322,6 +5329,8 @@ DUCKDB_C_API uint8_t duckdb_decimal_width(duckdb_logical_type type); /*! * Retrieves the scale of a decimal type. * + * Reports 0 for a decimal whose width does not fit in a uint8_t, like `duckdb_decimal_width`. + * * history: * - stable: v0.3.3 * @@ -5335,6 +5344,9 @@ DUCKDB_C_API uint8_t duckdb_decimal_scale(duckdb_logical_type type); /*! * Retrieves the internal storage type of a decimal type. * + * Decimals of up to 38 digits are stored as SMALLINT, INTEGER, BIGINT or HUGEINT. Wider decimals store their unscaled + * value as BIGNUM, which is what their vectors hold. + * * history: * - stable: v0.3.3 * @@ -8670,7 +8682,8 @@ DUCKDB_C_API duckdb_value duckdb_create_bignum(duckdb_bignum input); #if DUCKDB_API_VERSION_AT_LEAST(1, 2, 0) /*! - * Creates a DECIMAL value from a duckdb_decimal + * Creates a DECIMAL value from a duckdb_decimal. The uint8_t fields of a duckdb_decimal reach widths up to 255 digits; + * widths above 38 create a wide decimal whose unscaled value is the 128-bit value of the duckdb_decimal. * * history: * - stable: v1.2.0 @@ -9050,7 +9063,8 @@ DUCKDB_C_API duckdb_bignum duckdb_get_bignum(duckdb_value val); #if DUCKDB_API_VERSION_AT_LEAST(1, 2, 0) /*! - * Returns the duckdb_decimal value of the given value. + * Returns the duckdb_decimal value of the given value. A decimal wider than 38 digits is only representable when its + * unscaled value fits in 128 bits; use `duckdb_get_varchar` for the exact value otherwise. * * history: * - stable: v1.2.0 diff --git a/src/duckdb/src/include/duckdb/catalog/catalog.hpp b/src/duckdb/src/include/duckdb/catalog/catalog.hpp index afda13719..ba4285888 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog.hpp @@ -246,10 +246,13 @@ class Catalog { const EntryLookupInfo &schema_lookup, OnEntryNotFound if_not_found) = 0; - //! Whether schema strings can denote nested paths as well as literal schema names. + //! Whether the catalog supports nested schema lookup, creation and dropping. + //! Also enables nested paths in string schema arguments. Literal dotted names do not require this capability. virtual bool SupportsNestedSchemas() const { return false; } + //! Reject unsupported nested paths before invoking extension catalog methods. + DUCKDB_API void CheckNestedSchemaSupport(const QualifiedName &name, CatalogType type) const; //! Resolve a string schema argument, preferring an existing nested entry over a literal dotted schema. DUCKDB_API QualifiedName ResolveEntryName(ClientContext &context, const string &schema_arg, const string &entry_name, CatalogType type = CatalogType::TABLE_ENTRY, @@ -542,6 +545,7 @@ class Catalog { optional_ptr GetEntryInCatalog(CatalogEntryRetriever &retriever, const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found); //! Lookup an entry in the schema (taken from the lookup_info), returning the entry and schema if they exist + CatalogEntryLookup TryLookupEntry(CatalogTransaction transaction, const EntryLookupInfo &lookup_info); virtual CatalogEntryLookup TryLookupEntryInternal(CatalogTransaction transaction, const EntryLookupInfo &lookup_info); //! Looks the entry up within this catalog only, using the schema carried in the lookup_info. Does not resolve the 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 70bd7c9a2..1a85520f5 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 @@ -65,7 +65,7 @@ class SchemaCatalogEntry : public InCatalogEntry { } //! The full path of this schema (its parent chain outermost first, ending with this schema's own name) - vector GetSchemaPath() const; + DUCKDB_API vector GetSchemaPath() const; //! The schema path formatted as a SQL name, without the catalog. DUCKDB_API string GetSchemaName() const; //! The fully qualified name of an entry in this schema: [catalog, schema path..., entry_name] diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp index 53fa36533..e4452ed85 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp @@ -90,7 +90,7 @@ class TableCatalogEntry : public StandardEntry { virtual DataTable &GetStorage(); //! Returns a list of the constraints of the table - DUCKDB_API const vector> &GetConstraints() const; + DUCKDB_API virtual const vector> &GetConstraints() const; DUCKDB_API string ToSQL() const override; //! Get statistics of a column (physical or virtual) within the table diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp index 585f82b4e..79a9891be 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp @@ -48,7 +48,9 @@ struct CatalogSearchEntry { return !parent_schemas.empty(); } //! The names of the schemas from the top level down to this schema - vector GetSchemaPath() const; + DUCKDB_API vector GetSchemaPath() const; + //! The schema name, including its parent path for nested schemas + string GetSchemaName() const; string ToString() const; static string ListToString(const vector &input); diff --git a/src/duckdb/src/include/duckdb/common/bignum.hpp b/src/duckdb/src/include/duckdb/common/bignum.hpp index 6f565e0f3..62be0f8f8 100644 --- a/src/duckdb/src/include/duckdb/common/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/bignum.hpp @@ -13,12 +13,14 @@ #include "duckdb/common/vector.hpp" #include "duckdb/common/optional_ptr.hpp" #include +#include "duckdb/common/types/null_value.hpp" #include "duckdb/common/types/string_type.hpp" #include "duckdb/common/bignum_limbs.hpp" namespace duckdb { class StringHeap; class ArenaAllocator; +class ClientContext; class Context; struct bignum_t { @@ -38,6 +40,11 @@ struct bignum_t { void Print() const; }; +template <> +inline bignum_t NullValue() { + return bignum_t(NullValue()); +} + enum AbsoluteNumberComparison : uint8_t { // If number is equal EQUAL = 0, @@ -49,10 +56,15 @@ enum AbsoluteNumberComparison : uint8_t { //! Per-vector scratch digit buffers and interrupt-check state for BIGNUM multiplication and division struct BignumArithmeticState { + //! The context, if any, lets long operations check for interrupts + DUCKDB_API explicit BignumArithmeticState(optional_ptr client_context = nullptr); explicit BignumArithmeticState(Context &context_p) : context(context_p) { } - Context &context; + //! Counts digit operations and checks for an interrupt about once a millisecond, when a context is set + DUCKDB_API void AccountWork(idx_t work); + + optional_ptr context; //! Digit operations performed since the last interrupt check idx_t work_since_interrupt_check = 0; unsafe_vector lhs_digits; @@ -100,10 +112,17 @@ struct BignumIntermediate { //! Multiplies two BignumIntermediates and returns a string_t result, equivalent of a * static string_t Multiply(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, const BignumIntermediate &rhs); + //! Multiplies two magnitudes given as little-endian bignum_digit_t digits, result = lhs * rhs without leading zeros + DUCKDB_API static void MultiplyMagnitudes(BignumArithmeticState &state, const unsafe_vector &lhs, + const unsafe_vector &rhs, + unsafe_vector &result); //! Truncating division (a // b) or, with want_remainder, the remainder with the sign of the dividend (a % b) //! Returns false without writing a result when the divisor is zero static bool TryDivMod(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, const BignumIntermediate &rhs, bool want_remainder, string_t &result); + //! Truncating division and remainder in one go, see TryDivMod + static bool TryDivMod(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, + const BignumIntermediate &rhs, string_t "ient, string_t &remainder); //! Negates a value, e.g., -x string_t Negate(StringHeap &heap) const; void NegateInPlace(); diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 1852d5dfd..3a7a56f5c 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -200,6 +200,8 @@ enum class DebugVerificationMode : uint8_t; enum class DecimalBitWidth : uint8_t; +enum class DecimalRounding : uint8_t; + enum class DefaultOrderByNullType : uint8_t; enum class DeferredRuntimeFilterType : uint8_t; @@ -959,6 +961,9 @@ const char* EnumUtil::ToChars(DebugVerificationMode value template<> const char* EnumUtil::ToChars(DecimalBitWidth value); +template<> +const char* EnumUtil::ToChars(DecimalRounding value); + template<> const char* EnumUtil::ToChars(DefaultOrderByNullType value); @@ -1971,6 +1976,9 @@ DebugVerificationMode EnumUtil::FromString(const char *va template<> DecimalBitWidth EnumUtil::FromString(const char *value); +template<> +DecimalRounding EnumUtil::FromString(const char *value); + template<> DefaultOrderByNullType EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/operator/add.hpp b/src/duckdb/src/include/duckdb/common/operator/add.hpp index 0c9b8ce55..1d0b7ba1e 100644 --- a/src/duckdb/src/include/duckdb/common/operator/add.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/add.hpp @@ -15,11 +15,17 @@ namespace duckdb { +struct bignum_t; +class StringHeap; +struct BignumArithmeticState; + struct AddOperator { template static inline TR Operation(TA left, TB right) { return left + right; } + //! BIGNUM-backed values allocate their result in the heap + DUCKDB_API static bignum_t Operation(bignum_t left, bignum_t right, StringHeap &heap, BignumArithmeticState &state); }; template <> @@ -116,6 +122,8 @@ struct AddOperatorOverflowCheck { } }; +//! The fixed-size integer tiers of decimals check their results against the width of the tier; the bignum_t tier above +//! 38 digits binds exact result widths and needs no check struct TryDecimalAdd { template static inline bool Operation(TA left, TB right, TR &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 8b8cc1654..22bfdfff0 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 @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/bignum.hpp" #include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/common/operator/integer_cast_operator.hpp" @@ -17,11 +18,18 @@ namespace duckdb { //===--------------------------------------------------------------------===// // Decimal Casts //===--------------------------------------------------------------------===// +//! Decimals are stored in four fixed-size integer tiers (int16_t, int32_t, int64_t, hugeint_t) and, above 38 digits, +//! as a bignum_t: that tier allocates its results in the result vector, so its operations take the vector as well struct TryCastToDecimal { template static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { NotImplementedException::Throw("Unimplemented type for TryCastToDecimal!"); } + template + static inline bool Operation(SRC input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + NotImplementedException::Throw("Unimplemented type for TryCastToDecimal!"); + } }; struct TryCastToDecimalCommaSeparated { @@ -29,6 +37,11 @@ struct TryCastToDecimalCommaSeparated { static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { NotImplementedException::Throw("Unimplemented type for TryCastToDecimal!"); } + template + static inline bool Operation(SRC input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + NotImplementedException::Throw("Unimplemented type for TryCastToDecimal!"); + } }; struct TryCastFromDecimal { @@ -36,6 +49,25 @@ struct TryCastFromDecimal { static inline bool Operation(SRC input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { NotImplementedException::Throw("Unimplemented type for TryCastFromDecimal!"); } + template + static inline bool Operation(SRC input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + NotImplementedException::Throw("Unimplemented type for TryCastFromDecimal!"); + } +}; + +//! Runs a decimal cast operation whose result is stored in a vector: the fixed-size tiers hold the result in place, +//! the bignum_t tier allocates it in the result vector +struct VectorDecimalCast { + template + static inline bool Operation(SRC input, DST &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale) { + if constexpr (std::is_same::value) { + return OP::template Operation(input, result, result_vector, parameters, width, scale); + } else { + return OP::template Operation(input, result, parameters, width, scale); + } + } }; //===--------------------------------------------------------------------===// @@ -53,6 +85,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(bool input, int64_t &result, CastPar template <> DUCKDB_API bool TryCastToDecimal::Operation(bool input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(bool input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, bool &result, CastParameters ¶meters, uint32_t width, @@ -66,6 +101,9 @@ bool TryCastFromDecimal::Operation(int64_t input, bool &result, CastParameters & template <> bool TryCastFromDecimal::Operation(hugeint_t input, bool &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, bool &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int8_t @@ -82,6 +120,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, int64_t &result, CastP template <> DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(int8_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, int8_t &result, CastParameters ¶meters, uint32_t width, @@ -95,6 +136,9 @@ bool TryCastFromDecimal::Operation(int64_t input, int8_t &result, CastParameters template <> bool TryCastFromDecimal::Operation(hugeint_t input, int8_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int16_t @@ -111,6 +155,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, int64_t &result, Cast template <> DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(int16_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, int16_t &result, CastParameters ¶meters, uint32_t width, @@ -124,6 +171,9 @@ bool TryCastFromDecimal::Operation(int64_t input, int16_t &result, CastParameter template <> bool TryCastFromDecimal::Operation(hugeint_t input, int16_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int32_t @@ -140,6 +190,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, int64_t &result, Cast template <> DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(int32_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, int32_t &result, CastParameters ¶meters, uint32_t width, @@ -153,6 +206,9 @@ bool TryCastFromDecimal::Operation(int64_t input, int32_t &result, CastParameter template <> bool TryCastFromDecimal::Operation(hugeint_t input, int32_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> int64_t @@ -169,6 +225,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, int64_t &result, Cast template <> DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(int64_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, int64_t &result, CastParameters ¶meters, uint32_t width, @@ -182,6 +241,9 @@ bool TryCastFromDecimal::Operation(int64_t input, int64_t &result, CastParameter template <> bool TryCastFromDecimal::Operation(hugeint_t input, int64_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> hugeint_t @@ -198,6 +260,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, int64_t &result, Ca template <> DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(hugeint_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, @@ -211,6 +276,9 @@ bool TryCastFromDecimal::Operation(int64_t input, hugeint_t &result, CastParamet template <> bool TryCastFromDecimal::Operation(hugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uhugeint_t @@ -227,6 +295,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, int64_t &result, C template <> DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(uhugeint_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, @@ -240,6 +311,9 @@ bool TryCastFromDecimal::Operation(int64_t input, uhugeint_t &result, CastParame template <> bool TryCastFromDecimal::Operation(hugeint_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uhugeint_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint8_t @@ -256,6 +330,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, int64_t &result, Cast template <> DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(uint8_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, @@ -269,6 +346,9 @@ bool TryCastFromDecimal::Operation(int64_t input, uint8_t &result, CastParameter template <> bool TryCastFromDecimal::Operation(hugeint_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint8_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint16_t @@ -285,6 +365,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, int64_t &result, Cas template <> DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(uint16_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, @@ -298,6 +381,9 @@ bool TryCastFromDecimal::Operation(int64_t input, uint16_t &result, CastParamete template <> bool TryCastFromDecimal::Operation(hugeint_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint32_t @@ -314,6 +400,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, int64_t &result, Cas template <> DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(uint32_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, @@ -327,6 +416,9 @@ bool TryCastFromDecimal::Operation(int64_t input, uint32_t &result, CastParamete template <> bool TryCastFromDecimal::Operation(hugeint_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> uint64_t @@ -343,6 +435,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, int64_t &result, Cas template <> DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(uint64_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, @@ -356,6 +451,9 @@ bool TryCastFromDecimal::Operation(int64_t input, uint64_t &result, CastParamete template <> bool TryCastFromDecimal::Operation(hugeint_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, uint64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> float @@ -372,6 +470,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(float input, int64_t &result, CastPa template <> DUCKDB_API bool TryCastToDecimal::Operation(float input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(float input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, float &result, CastParameters ¶meters, uint32_t width, @@ -385,6 +486,9 @@ bool TryCastFromDecimal::Operation(int64_t input, float &result, CastParameters template <> bool TryCastFromDecimal::Operation(hugeint_t input, float &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, float &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> double @@ -401,6 +505,9 @@ DUCKDB_API bool TryCastToDecimal::Operation(double input, int64_t &result, CastP template <> DUCKDB_API bool TryCastToDecimal::Operation(double input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(double input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); template <> bool TryCastFromDecimal::Operation(int16_t input, double &result, CastParameters ¶meters, uint32_t width, @@ -414,6 +521,9 @@ bool TryCastFromDecimal::Operation(int64_t input, double &result, CastParameters template <> bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, double &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); //===--------------------------------------------------------------------===// // Cast Decimal <-> VARCHAR @@ -431,6 +541,9 @@ template <> DUCKDB_API bool TryCastToDecimal::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); template <> +DUCKDB_API bool TryCastToDecimal::Operation(string_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, int16_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); template <> @@ -442,6 +555,44 @@ DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, int64_ template <> DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, hugeint_t &result, CastParameters ¶meters, uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimalCommaSeparated::Operation(string_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); + +//===--------------------------------------------------------------------===// +// Cast Decimal <-> bignum_t (BIGNUM, a decimal with scale 0) +//===--------------------------------------------------------------------===// +template <> +DUCKDB_API bool TryCastToDecimal::Operation(bignum_t input, int16_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(bignum_t input, int32_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(bignum_t input, int64_t &result, CastParameters ¶meters, uint32_t width, + uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(bignum_t input, hugeint_t &result, CastParameters ¶meters, + uint32_t width, uint32_t scale); +template <> +DUCKDB_API bool TryCastToDecimal::Operation(bignum_t input, bignum_t &result, Vector &result_vector, + CastParameters ¶meters, uint32_t width, uint32_t scale); + +template <> +bool TryCastFromDecimal::Operation(int16_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(int32_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(int64_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(hugeint_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale); +template <> +bool TryCastFromDecimal::Operation(bignum_t input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, + uint32_t width, uint32_t scale); struct StringCastFromDecimal { template @@ -458,6 +609,8 @@ template <> string_t StringCastFromDecimal::Operation(int64_t input, uint32_t width, uint32_t scale, StringHeap &heap); template <> string_t StringCastFromDecimal::Operation(hugeint_t input, uint32_t width, uint32_t scale, StringHeap &heap); +template <> +string_t StringCastFromDecimal::Operation(bignum_t input, uint32_t width, uint32_t scale, StringHeap &heap); //===--------------------------------------------------------------------===// // Cast VARCHAR <-> Decimal @@ -560,12 +713,12 @@ struct DecimalCastOperation { state.exponent_type = ExponentType::POSITIVE; // Positive exponents need up to 'exponent' amount of digits // Everything beyond that amount needs to be truncated - if (decimal_excess > exponent) { + if (decimal_excess > UnsafeNumericCast(exponent)) { // We've allowed too many decimals state.excessive_decimals = UnsafeNumericCast(decimal_excess - exponent); exponent = 0; } else { - exponent -= decimal_excess; + exponent -= UnsafeNumericCast(decimal_excess); } D_ASSERT(exponent >= 0); } else if (exponent < 0) { diff --git a/src/duckdb/src/include/duckdb/common/operator/multiply.hpp b/src/duckdb/src/include/duckdb/common/operator/multiply.hpp index 13f210df3..1a44749ca 100644 --- a/src/duckdb/src/include/duckdb/common/operator/multiply.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/multiply.hpp @@ -15,6 +15,10 @@ namespace duckdb { +struct bignum_t; +class StringHeap; +struct BignumArithmeticState; + struct interval_t; struct MultiplyOperator { @@ -22,6 +26,8 @@ struct MultiplyOperator { static inline TR Operation(TA left, TB right) { return left * right; } + //! BIGNUM-backed values allocate their result in the heap, the scratch state serves the multiplication + DUCKDB_API static bignum_t Operation(bignum_t left, bignum_t right, StringHeap &heap, BignumArithmeticState &state); }; template <> diff --git a/src/duckdb/src/include/duckdb/common/operator/subtract.hpp b/src/duckdb/src/include/duckdb/common/operator/subtract.hpp index 5f4aeb1fb..922e4fb3b 100644 --- a/src/duckdb/src/include/duckdb/common/operator/subtract.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/subtract.hpp @@ -17,6 +17,10 @@ namespace duckdb { +struct bignum_t; +class StringHeap; +struct BignumArithmeticState; + struct interval_t; struct date_t; @@ -25,6 +29,8 @@ struct SubtractOperator { static inline TR Operation(TA left, TB right) { return left - right; } + //! BIGNUM-backed values allocate their result in the heap + DUCKDB_API static bignum_t Operation(bignum_t left, bignum_t right, StringHeap &heap, BignumArithmeticState &state); }; template <> diff --git a/src/duckdb/src/include/duckdb/common/types.hpp b/src/duckdb/src/include/duckdb/common/types.hpp index bcc4da4c8..ae14f4e14 100644 --- a/src/duckdb/src/include/duckdb/common/types.hpp +++ b/src/duckdb/src/include/duckdb/common/types.hpp @@ -25,6 +25,7 @@ class Value; class TypeCatalogEntry; class Vector; class ClientContext; +class DecimalWidthLimit; class ParsedExpression; class CoordinateReferenceSystem; @@ -482,6 +483,16 @@ struct LogicalType { //! Variant of ForceMaxLogicalType for call-sites that have no ClientContext available; uses only the built-in //! CastRules (no extension-registered casts). DUCKDB_API static LogicalType DefaultForceMaxLogicalType(const LogicalType &left, const LogicalType &right); + //! Variants that bind the width of a combined DECIMAL within the limit instead of the max_decimal_width setting: + //! the binder passes its limit, which is fixed while the keys of an index are bound + DUCKDB_API static LogicalType MaxLogicalType(ClientContext &context, const LogicalType &left, + const LogicalType &right, const DecimalWidthLimit &decimal_width_limit); + DUCKDB_API static bool TryGetMaxLogicalType(ClientContext &context, const LogicalType &left, + const LogicalType &right, LogicalType &result, + const DecimalWidthLimit &decimal_width_limit); + DUCKDB_API static LogicalType ForceMaxLogicalType(ClientContext &context, const LogicalType &left, + const LogicalType &right, + const DecimalWidthLimit &decimal_width_limit); //! Normalize a type - removing literals DUCKDB_API static LogicalType NormalizeType(const LogicalType &type); //! Nested type children with Parquet style names @@ -608,6 +619,7 @@ struct LogicalType { struct DecimalType { DUCKDB_API static uint32_t GetWidth(const LogicalType &type); DUCKDB_API static uint32_t GetScale(const LogicalType &type); + //! The widest DECIMAL: widths above Decimal::MAX_WIDTH_INT128 are stored as BIGNUM blobs and reach the uint32_t range DUCKDB_API static uint32_t MaxWidth(); }; @@ -711,7 +723,9 @@ DUCKDB_API string LogicalTypeIdToString(LogicalTypeId type); DUCKDB_API LogicalTypeId TransformStringToLogicalTypeId(const string &str); -DUCKDB_API LogicalType TransformStringToLogicalType(const string &str, ClientContext &context); +//! Parses and binds a type from its SQL text, binding decimals within the limit, if one is given +DUCKDB_API LogicalType TransformStringToLogicalType(const string &str, ClientContext &context, + optional_ptr decimal_width_limit = nullptr); //! The PhysicalType used by the row identifiers column extern const PhysicalType ROW_TYPE; diff --git a/src/duckdb/src/include/duckdb/common/types/bignum.hpp b/src/duckdb/src/include/duckdb/common/types/bignum.hpp index fe619193f..5cfba415c 100644 --- a/src/duckdb/src/include/duckdb/common/types/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/types/bignum.hpp @@ -25,12 +25,20 @@ struct CastParameters; //! Scratch space of the VARCHAR <-> BIGNUM conversions, reused across the values of a vector struct BignumCastScratch { + //! The context, if any, lets long conversions check for interrupts + explicit BignumCastScratch(optional_ptr context = nullptr) : state(context) { + } + //! Base 2^64 limbs of a magnitude, least significant first unsafe_vector binary; //! Base 10^19 limbs of a magnitude, least significant first unsafe_vector decimal; //! powers[k] holds 2^(64 * 2^k) in base 10^19 limbs, for the divide and conquer conversion of large values vector> powers; + //! powers_of_ten[k] holds 10^(19 * 2^k) in base 2^64 limbs, for the divide and conquer parse of long strings + vector> powers_of_ten; + //! Digit scratch and interrupt checks of the multiplications of the divide and conquer conversions + BignumArithmeticState state; }; //! The Bignum class is a static class that holds helper functions for the Bignum type. @@ -66,10 +74,12 @@ class Bignum { bool &is_zero, bool &should_round_up); //! Encodes a VARCHAR into a BIGNUM blob using formatting information returned by VarcharFormatting. DUCKDB_API static string EncodeBignum(const string_t &value, idx_t start_pos, idx_t end_pos, bool is_negative, - bool is_zero); + bool is_zero, optional_ptr context = nullptr); //! Encodes a VARCHAR into a BIGNUM blob, applying decimal rounding if requested. + //! A long conversion checks for interrupts through the context DUCKDB_API static string EncodeVarcharBignum(const string_t &value, idx_t start_pos, idx_t end_pos, - bool is_negative, bool is_zero, bool should_round_up); + bool is_negative, bool is_zero, bool should_round_up, + optional_ptr context = nullptr); //! Converts a VARCHAR into a BIGNUM allocated in the result vector, returns false if the VARCHAR is invalid DUCKDB_API static bool TryVarcharToBignum(const string_t &value, bignum_t &result_value, Vector &result, BignumCastScratch &scratch); @@ -83,14 +93,14 @@ class Bignum { DUCKDB_API static void GetByteArray(vector &byte_array, bool &is_negative, const string_t &blob); //! Function to create a BIGNUM blob from a byte array containing the absolute value, plus an is_negative bool DUCKDB_API static string FromByteArray(uint8_t *data, idx_t size, bool is_negative); - //! Function to convert BIGNUM blob to a VARCHAR - DUCKDB_API static string BignumToVarchar(const bignum_t &blob); + //! Function to convert BIGNUM blob to a VARCHAR, a long conversion checks for interrupts through the context + DUCKDB_API static string BignumToVarchar(const bignum_t &blob, optional_ptr context = nullptr); //! Writes the decimal representation of a BIGNUM into the string heap of the result vector DUCKDB_API static string_t BignumToVarchar(const bignum_t &blob, Vector &result, BignumCastScratch &scratch); //! The BIGNUM -> VARCHAR cast function DUCKDB_API static bool BignumToVarcharCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters); - //! Function to convert Varchar to BIGNUM blob - DUCKDB_API static string VarcharToBignum(const string_t &value); + //! Function to convert Varchar to BIGNUM blob, a long conversion checks for interrupts through the context + DUCKDB_API static string VarcharToBignum(const string_t &value, optional_ptr context = nullptr); //! ----------------------------------- Double Cast ----------------------------------- // DUCKDB_API static bool BignumToDouble(const bignum_t &blob, double &result, bool &strict); [[noreturn]] DUCKDB_API static void ThrowInvalidBlobSize(idx_t size); diff --git a/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp b/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp new file mode 100644 index 000000000..4b5780b87 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp @@ -0,0 +1,115 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/types/bignum_decimal.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/common.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/hugeint.hpp" + +namespace duckdb { +class ClientContext; +class Context; +class StringHeap; +class Vector; + +//! The operations on the unscaled value of a DECIMAL wider than 38 digits, a bignum_t (the BIGNUM blob): the interface +//! of the fixed-size tiers (see decimal_helper.hpp), whose results are owned blobs here as the values have no fixed +//! size, and the conversions only this tier needs +template <> +struct DecimalHelper { + //! An owned result, a BIGNUM blob + using OWNED = string; + static constexpr bool IS_WIDE = true; + + //! The scratch of TryRound: the heap of the result vector, where the results are allocated, and the buffers of the + //! digit arithmetic + struct RoundState { + DUCKDB_API RoundState(Vector &result, Context &context); + + StringHeap &heap; + BignumArithmeticState state; + }; + + //! 10^exponent as a BIGNUM blob, the powers of everyday widths are cached; a long computation checks for + //! interrupts through the context, as do the other conversions below + DUCKDB_API static string PowerOfTen(idx_t exponent, optional_ptr context = nullptr); + //! 2^exponent as a BIGNUM blob + DUCKDB_API static string PowerOfTwo(idx_t exponent); + //! Whether |value| < 10^width, i.e. the unscaled value fits a DECIMAL of the given width + DUCKDB_API static bool FitsWidth(const bignum_t &value, uint32_t width); + DUCKDB_API static bool FitsWidth(const BignumIntermediate &value, uint32_t width); + //! Whether the unscaled value is zero + DUCKDB_API static bool IsZero(const bignum_t &value); + //! Whether the unscaled value is negative + DUCKDB_API static bool IsNegative(const bignum_t &value); + //! A bignum_t over an owned blob, which must outlive it + static bignum_t Load(const OWNED &owned) { + return bignum_t(string_t(owned)); + } + //! Stores an owned blob in the heap of a vector + DUCKDB_API static bignum_t Store(Vector &result, const OWNED &owned); + //! The BIGNUM blob of an integer + DUCKDB_API static string FromInteger(hugeint_t value); + DUCKDB_API static string FromInteger(uhugeint_t value); + //! Converts an unscaled value to a hugeint, returns false if it does not fit + DUCKDB_API static bool TryToHugeint(const bignum_t &value, hugeint_t &result); + DUCKDB_API static bool TryToUhugeint(const bignum_t &value, uhugeint_t &result); + + //! Formats an unscaled value with the given width and scale, e.g. 12345 with scale 2 -> "123.45" + DUCKDB_API static string ToString(const bignum_t &value, uint32_t width, uint32_t scale, + optional_ptr context = nullptr); + //! Parses a decimal string into the BIGNUM blob of the unscaled value of a DECIMAL(width, scale), rounding half + //! away from zero + DUCKDB_API static bool TryParse(const char *data, idx_t size, uint32_t width, uint32_t scale, string &result, + char decimal_separator = '.', optional_ptr context = nullptr); + + //! Drops drop_digits decimal digits of an unscaled value with the given rounding and appends restore_digits zero + //! digits, i.e. rounds the value at a digit position; returns false if the result does not fit the width. The + //! result is allocated in the heap of the state + DUCKDB_API static bool TryRound(const bignum_t &value, idx_t drop_digits, idx_t restore_digits, + DecimalRounding rounding, uint32_t width, RoundState &state, bignum_t &result); + template + static bool TryRound(const bignum_t &value, idx_t drop_digits, idx_t restore_digits, uint32_t width, + RoundState &state, bignum_t &result) { + return TryRound(value, drop_digits, restore_digits, ROUNDING, width, state, result); + } + //! Rescales an unscaled value to target_scale (rounding half away from zero), the result is the BIGNUM blob of the + //! rescaled value + DUCKDB_API static string Rescale(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, + optional_ptr context = nullptr); + //! Rescales an unscaled value to target_scale (rounding half away from zero) and checks it fits target_width, the + //! result is the BIGNUM blob of the rescaled value + DUCKDB_API static bool TryRescale(const bignum_t &value, uint32_t source_scale, uint32_t target_width, + uint32_t target_scale, string &result, + optional_ptr context = nullptr); + + //! Converts an unscaled value with the given scale to a FLOAT or DOUBLE, rounding once (through the decimal + //! string), returns false if the value is out of range + DUCKDB_API static bool TryToFloating(const bignum_t &value, uint32_t scale, float &result, + optional_ptr context = nullptr); + DUCKDB_API static bool TryToFloating(const bignum_t &value, uint32_t scale, double &result, + optional_ptr context = nullptr); + //! Converts an unscaled value with the given scale to a double, infinite when the value is out of range + DUCKDB_API static double ToDouble(const bignum_t &value, uint32_t scale, + optional_ptr context = nullptr); + //! Converts a double to the BIGNUM blob of the unscaled value of a DECIMAL(width, scale), returns false if it does + //! not fit + DUCKDB_API static bool TryFromDouble(double value, uint32_t width, uint32_t scale, string &result, + optional_ptr context = nullptr); + //! The BIGNUM blob of a finite double with an integral value, every such value converts exactly + DUCKDB_API static string FromDouble(double value); + + //! Converts a two's complement integer of "size" bytes (big- or little-endian) into the BIGNUM blob of its value + DUCKDB_API static string FromTwosComplement(const_data_ptr_t data, idx_t size, bool big_endian); + //! Writes the unscaled value as a two's complement integer of "size" bytes, throws if it does not fit + DUCKDB_API static void ToTwosComplement(const bignum_t &value, data_ptr_t result, idx_t size, bool big_endian); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/decimal.hpp b/src/duckdb/src/include/duckdb/common/types/decimal.hpp index 9d8c2fc55..d85446ca9 100644 --- a/src/duckdb/src/include/duckdb/common/types/decimal.hpp +++ b/src/duckdb/src/include/duckdb/common/types/decimal.hpp @@ -8,7 +8,9 @@ #pragma once +#include "duckdb/common/bignum.hpp" #include "duckdb/common/types.hpp" +#include "duckdb/storage/storage_info.hpp" namespace duckdb { @@ -35,23 +37,77 @@ struct DecimalWidth { static constexpr uint32_t max = 38; }; +class ClientContext; + +//! How the digits a decimal drops when it is rounded, rescaled or parsed are rounded +enum class DecimalRounding : uint8_t { TRUNCATE, FLOOR, CEIL, HALF_AWAY_FROM_ZERO, HALF_TO_EVEN }; + +//! The operations on the unscaled value of a DECIMAL stored as T: specialised for the fixed-size tiers int16_t, +//! int32_t, int64_t and hugeint_t in decimal_helper.hpp and for the bignum_t tier (above 38 digits) in +//! bignum_decimal.hpp, with the same interface, so that code is written once for every tier +template +struct DecimalHelper; + //! The Decimal class is a static class that holds helper functions for the Decimal type class Decimal { public: 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; + //! MAX_WIDTH_INT128 is also the widest decimal that is stored in a fixed-size integer: wider decimals store their + //! unscaled value as a BIGNUM blob and are bounded only by the uint32_t range of the width static constexpr uint32_t MAX_WIDTH_INT128 = DecimalWidth::max; + //! The widest fixed-size decimal tier, kept for extensions; wider decimals are the BIGNUM-backed tier static constexpr uint32_t MAX_WIDTH_DECIMAL = MAX_WIDTH_INT128; + //! The default of the max_decimal_width setting: the widest DECIMAL a session binds unless the setting is raised + static constexpr uint32_t DEFAULT_MAX_WIDTH = 1000000; + //! The storage version from which DECIMAL columns wider than MAX_WIDTH_INT128 digits can be stored: the engines of + //! the versions before it read a DECIMAL width as a single byte and bind decimal arithmetic within 38 digits + static constexpr StorageVersion WIDE_VERSION_ADDED = StorageVersion::V2_1_0; public: - //! Whether width/scale form a valid DECIMAL type: width in [1, MAX_WIDTH_DECIMAL] and scale not exceeding width. + //! Whether width/scale form a valid DECIMAL type: a width of at least 1 and a scale not exceeding the width static bool IsValidWidthScale(uint32_t width, uint32_t scale) { - return width >= 1 && width <= MAX_WIDTH_DECIMAL && scale <= width; + return width >= 1 && scale <= width; + } + //! Whether a decimal of this width is stored as a BIGNUM blob instead of a fixed-size integer + static bool IsWide(uint32_t width) { + return width > MAX_WIDTH_INT128; } 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); + //! Formats the unscaled value of a wide decimal (a BIGNUM blob), a long conversion checks for interrupts + static string ToString(bignum_t value, uint32_t width, uint32_t scale, + optional_ptr context = nullptr); +}; + +//! The widest DECIMAL binding constructs: the max_decimal_width setting of the session, or the width the keys of an +//! index are bound within, which the Binder carries while it binds them so that every session binds a stored key to +//! the same types. The limit bounds the types an operation constructs, never the types of the inputs it already has +class DecimalWidthLimit { +public: + //! The limit of the max_decimal_width setting (at least MAX_WIDTH_INT128, so the fixed-size tiers are never + //! bounded by it), or of the uint32_t range of the width without a context + static DecimalWidthLimit FromSetting(optional_ptr context); + //! The limit a function with the return type was bound within, for rebinding it when it is deserialized: the + //! widest DECIMAL of the type, since a bind constructs no DECIMAL wider than its result beyond the types it casts + //! its arguments to, and no bound for an aggregate state, which records the arguments of its aggregate, not the + //! result + static DecimalWidthLimit FromReturnType(const LogicalType &return_type); + DecimalWidthLimit(uint32_t width, const char *hint); + + //! The widest result of combining decimals, given the widest DECIMAL among the inputs: the limit, or the input + //! width when that is wider + uint32_t ResultWidth(uint32_t max_input_width) const; + //! Narrows a computed result width, throws when the operation needs a DECIMAL beyond ResultWidth + uint32_t CheckedWidth(idx_t width, uint32_t max_input_width, const string &operation) const; + +public: + //! The widest DECIMAL binding constructs + uint32_t width; + //! How to bind a wider DECIMAL, the hint of the errors a wider type raises; a literal or text the owner outlives + const char *hint; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/decimal_helper.hpp b/src/duckdb/src/include/duckdb/common/types/decimal_helper.hpp new file mode 100644 index 000000000..efe01aaa7 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/types/decimal_helper.hpp @@ -0,0 +1,186 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/types/decimal_helper.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/types/bignum_decimal.hpp" +#include "duckdb/common/types/cast_helpers.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/hugeint.hpp" + +namespace duckdb { +class Vector; + +//! The operations on the unscaled value of a fixed-size decimal tier (int16_t, int32_t, int64_t or hugeint_t), the +//! interface DecimalHelper offers for the decimals wider than 38 digits +template +struct FixedSizeDecimalHelper { + //! An owned result is the value itself in these tiers (a BIGNUM blob in the bignum_t tier) + using OWNED = T; + static constexpr bool IS_WIDE = false; + static constexpr uint32_t MAX_WIDTH = DecimalWidth::max; + + //! The scratch of TryRound, nothing in these tiers + struct RoundState { + RoundState(Vector &result, Context &context) { + } + }; + + //! 10^exponent, which is at most 10^MAX_WIDTH + static T PowerOfTen(idx_t exponent) { + D_ASSERT(exponent <= MAX_WIDTH); + return UnsafeNumericCast(POWERS_OF_TEN_CLASS::POWERS_OF_TEN[exponent]); + } + //! Whether |value| < 10^width, i.e. the unscaled value fits a DECIMAL of the given width + static bool FitsWidth(T value, uint32_t width) { + if (width > MAX_WIDTH) { + return true; + } + const T limit = PowerOfTen(width); + return value > -limit && value < limit; + } + static bool IsZero(T value) { + return value == 0; + } + static bool IsNegative(T value) { + return value < 0; + } + //! The value as this tier stores it, and the value stored in a vector: the integer itself in these tiers + static T Load(const OWNED &owned) { + return owned; + } + static T Store(Vector &result, const OWNED &owned) { + return owned; + } + //! The unscaled value of an integer that fits the tier + static OWNED FromInteger(hugeint_t value) { + if constexpr (std::is_same::value) { + return value; + } else { + return Hugeint::Cast(value); + } + } + static bool TryToHugeint(T value, hugeint_t &result) { + result = FromIntegerToHugeint(value); + return true; + } + + //! Formats an unscaled value with the given width and scale, e.g. 12345 with scale 2 -> "123.45" + static string ToString(T value, uint32_t width, uint32_t scale, optional_ptr context = nullptr) { + return Decimal::ToString(value, width, scale); + } + //! Parses a decimal string into the unscaled value of a DECIMAL(width, scale), rounding half away from zero + DUCKDB_API static bool TryParse(const char *data, idx_t size, uint32_t width, uint32_t scale, OWNED &result, + char decimal_separator = '.', optional_ptr context = nullptr); + + //! Drops the digits below power_of_ten (at least ten) with the rounding mode + template + static T RoundDroppedDigits(T value, T power_of_ten) { + D_ASSERT(power_of_ten >= 10); + T quotient; + T remainder; + if constexpr (std::is_same::value) { + // hugeint division and modulo both run a full DivMod and discard half of the result + quotient = Hugeint::DivMod(value, power_of_ten, remainder); + } else { + quotient = UnsafeNumericCast(value / power_of_ten); + remainder = UnsafeNumericCast(value % power_of_ten); + } + if (remainder == 0) { + return quotient; + } + // the quotient is truncated towards zero, the mode decides whether it moves one away from zero + const bool negative = value < 0; + bool away; + switch (ROUNDING) { + case DecimalRounding::TRUNCATE: + away = false; + break; + case DecimalRounding::FLOOR: + away = negative; + break; + case DecimalRounding::CEIL: + away = !negative; + break; + default: { + const T magnitude = UnsafeNumericCast(negative ? -remainder : remainder); + const T half = UnsafeNumericCast(power_of_ten / 2); + away = magnitude > half || + (magnitude == half && (ROUNDING == DecimalRounding::HALF_AWAY_FROM_ZERO || quotient % 2 != 0)); + break; + } + } + if (away) { + quotient = UnsafeNumericCast(negative ? quotient - 1 : quotient + 1); + } + return quotient; + } + //! Drops drop_digits digits of an unscaled value with the rounding and appends restore_digits zero digits, i.e. + //! rounds the value at a digit position; false if the result does not fit the width + template + static bool TryRound(T value, idx_t drop_digits, idx_t restore_digits, uint32_t width, RoundState &state, + T &result) { + T rounded = drop_digits > 0 ? RoundDroppedDigits(value, PowerOfTen(drop_digits)) : value; + if (restore_digits > 0) { + rounded = UnsafeNumericCast(rounded * PowerOfTen(restore_digits)); + } + result = rounded; + return FitsWidth(rounded, width); + } + //! Rescales an unscaled value to target_scale (rounding half away from zero) and checks it fits target_width + static bool TryRescale(T value, uint32_t source_scale, uint32_t target_width, uint32_t target_scale, OWNED &result, + optional_ptr context = nullptr) { + D_ASSERT(target_width <= MAX_WIDTH && target_scale <= target_width); + if (target_scale >= source_scale) { + // the product fits the width when the value fits the width without the appended digits + const idx_t shift = target_scale - source_scale; + if (!FitsWidth(value, target_width - shift)) { + return false; + } + result = UnsafeNumericCast(value * PowerOfTen(shift)); + return true; + } + result = + RoundDroppedDigits(value, PowerOfTen(source_scale - target_scale)); + return FitsWidth(result, target_width); + } + + //! Converts an unscaled value with the given scale to a FLOAT or DOUBLE, which these tiers always fit + DUCKDB_API static bool TryToFloating(T value, uint32_t scale, float &result, + optional_ptr context = nullptr); + DUCKDB_API static bool TryToFloating(T value, uint32_t scale, double &result, + optional_ptr context = nullptr); + static double ToDouble(T value, uint32_t scale, optional_ptr context = nullptr) { + double result; + TryToFloating(value, scale, result, context); + return result; + } + //! Converts a double to the unscaled value of a DECIMAL(width, scale), false if it does not fit + DUCKDB_API static bool TryFromDouble(double value, uint32_t width, uint32_t scale, OWNED &result, + optional_ptr context = nullptr); + +private: + static hugeint_t FromIntegerToHugeint(T value) { + if constexpr (std::is_same::value) { + return value; + } else { + return Hugeint::Convert(value); + } + } +}; + +template <> +struct DecimalHelper : FixedSizeDecimalHelper {}; +template <> +struct DecimalHelper : FixedSizeDecimalHelper {}; +template <> +struct DecimalHelper : FixedSizeDecimalHelper {}; +template <> +struct DecimalHelper : FixedSizeDecimalHelper {}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/type_manager.hpp b/src/duckdb/src/include/duckdb/common/types/type_manager.hpp index 401df3371..4097ccfc3 100644 --- a/src/duckdb/src/include/duckdb/common/types/type_manager.hpp +++ b/src/duckdb/src/include/duckdb/common/types/type_manager.hpp @@ -21,7 +21,9 @@ class TypeManager { const CastFunctionSet &GetCastFunctions() const; //! Try to parse and bind a logical type from a string. Throws an exception if the type could not be parsed. - LogicalType ParseLogicalType(const string &type_str, ClientContext &context) const; + //! Decimals are bound within the limit, if one is given, else within the max_decimal_width setting + LogicalType ParseLogicalType(const string &type_str, ClientContext &context, + optional_ptr decimal_width_limit = nullptr) const; //! Parse and bind a logical type from a string with the default parser, resolving the built-in types only. LogicalType ParseLogicalType(const string &type_str) const; @@ -32,7 +34,7 @@ class TypeManager { private: //! This has to be a function pointer to avoid the compiler inlining the implementation and //! blowing up the binary size of extensions that include type_manager.hpp - LogicalType (*parse_function)(const string &, ClientContext &); + LogicalType (*parse_function)(const string &, ClientContext &, optional_ptr); //! The set of cast functions unique_ptr cast_functions; diff --git a/src/duckdb/src/include/duckdb/common/types/value.hpp b/src/duckdb/src/include/duckdb/common/types/value.hpp index bb837459f..22b8b0e08 100644 --- a/src/duckdb/src/include/duckdb/common/types/value.hpp +++ b/src/duckdb/src/include/duckdb/common/types/value.hpp @@ -31,6 +31,7 @@ class String; class CastFunctionSet; struct GetCastFunctionInput; struct ExtraValueInfo; +struct bignum_t; //! The Value object holds a single arbitrary value of any type that can be //! stored in the database. @@ -171,6 +172,8 @@ class Value { 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 decimal Value from the BIGNUM blob of its unscaled value, the storage of widths above 38 + DUCKDB_API static Value DECIMAL(bignum_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/parquet_variant_iterator.hpp b/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp index dcdbf6495..bbdd85505 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp @@ -116,6 +116,8 @@ class ParquetVariantNode { template T GetData() const; DUCKDB_API string_t GetString() const; + //! Parquet VARIANT decimals have at most 38 digits: there is no BIGNUM blob to return + DUCKDB_API string_t GetWideDecimal() const; DUCKDB_API VariantDecimalProperties GetDecimalProperties() const; DUCKDB_API ParquetObjectIterator GetObjectChildren(VariantIterationOrder order) const; DUCKDB_API ParquetArrayIterator GetArrayChildren() const; 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 68fa67fb5..20e1bda9e 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 @@ -74,7 +74,10 @@ inline uint32_t VariantBuilderGetOrCreateIndex(OrderedOwningStringMap //! The physical storage type of a DECIMAL of the given width (matches VariantDecimalData::GetPhysicalType) inline PhysicalType VariantDecimalPhysicalType(uint32_t width) { - if (width > DecimalWidth::max) { + if (width > DecimalWidth::max) { + // decimals wider than 38 digits are BIGNUM blobs + return PhysicalType::VARCHAR; + } else if (width > DecimalWidth::max) { return PhysicalType::INT128; } else if (width > DecimalWidth::max) { return PhysicalType::INT64; @@ -313,6 +316,13 @@ struct VariantBuilder { case PhysicalType::INT128: VariantBuilderAppendFixed(blob, primitive.GetValueUnsafe()); break; + case PhysicalType::VARCHAR: { + // the BIGNUM blob of a decimal wider than 38 digits + auto bignum = primitive.GetValueUnsafe(); + VariantBuilderAppendVarint(blob, NumericCast(bignum.GetSize())); + VariantBuilderAppendBytes(blob, const_data_ptr_cast(bignum.GetData()), bignum.GetSize()); + break; + } default: throw InternalException("Unexpected physical type for Decimal value: %s", EnumUtil::ToString(type.InternalType())); @@ -449,9 +459,15 @@ struct VariantBuilder { case PhysicalType::INT64: VariantBuilderAppendFixed(blob, it.template GetData()); break; - default: + case PhysicalType::INT128: VariantBuilderAppendFixed(blob, it.template GetData()); break; + default: { + auto bignum = it.GetWideDecimal(); + VariantBuilderAppendVarint(blob, NumericCast(bignum.GetSize())); + VariantBuilderAppendBytes(blob, const_data_ptr_cast(bignum.GetData()), bignum.GetSize()); + break; + } } break; } 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 24b9f1c0a..4012d3184 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp @@ -65,7 +65,7 @@ struct VariantNumberKey { //! 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) + //! and decimals wider than 38 digits can produce magnitudes that large) string digits; //! Set the significant digits from the given span 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 f3a6a1e0f..66fde704d 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp @@ -172,6 +172,8 @@ class VariantNode { } //! Returns the (variable-length) string payload of a VARCHAR/BLOB/BIGNUM/GEOMETRY/BITSTRING value string_t GetString() const; + //! Returns the BIGNUM blob of a DECIMAL value wider than 38 digits + string_t GetWideDecimal() const; //! Returns the (width, scale) of a DECIMAL value VariantDecimalProperties GetDecimalProperties() const { auto decimal = GetDecimal(); 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 abb87fb2e..73e3a01cc 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp @@ -352,7 +352,9 @@ class VariantVisitor { auto &scale = decoded_decimal.scale; auto &ptr = decoded_decimal.value_ptr; if (width > DecimalWidth::max) { - throw InternalException("Can't handle decimal of width: %d", width); + // decimals wider than 38 digits are BIGNUM blobs + auto blob = VariantUtils::DecodeWideDecimalData(variant, row, values_idx); + return Visitor::template VisitDecimal(bignum_t(blob), width, scale, std::forward(args)...); } else if (width > DecimalWidth::max) { return Visitor::template VisitDecimal(Load(ptr), width, scale, std::forward(args)...); @@ -372,7 +374,9 @@ class VariantVisitor { static ReturnType VisitDecimal(const VariantNode &node, Args &&...args) { auto decimal = node.GetDecimal(); if (decimal.width > DecimalWidth::max) { - throw InternalException("Can't handle decimal of width: %d", decimal.width); + // decimals wider than 38 digits are BIGNUM blobs + return Visitor::template VisitDecimal(bignum_t(node.GetWideDecimal()), decimal.width, + decimal.scale, std::forward(args)...); } else if (decimal.width > DecimalWidth::max) { return Visitor::template VisitDecimal(node.GetData(), decimal.width, decimal.scale, std::forward(args)...); diff --git a/src/duckdb/src/include/duckdb/execution/index/unbound_index.hpp b/src/duckdb/src/include/duckdb/execution/index/unbound_index.hpp index 08e7a9510..39a9b545a 100644 --- a/src/duckdb/src/include/duckdb/execution/index/unbound_index.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/unbound_index.hpp @@ -118,7 +118,9 @@ class UnboundIndex : public Index { //! table_chunk uses physical table layout: data[j] holds physical column j. It may be sparse, //! but all columns required by this index must be populated. void BufferChunk(DataChunk &table_chunk, Vector &row_ids, BufferedIndexReplay replay_type); - unique_ptr Bind(IndexBinder &binder, const vector &physical_column_types); + //! Binds the index, or returns nullptr for an index with mismatched stored keys when those are skipped + unique_ptr Bind(IndexBinder &binder, const vector &physical_column_types, + bool skip_mismatched_keys = false); bool HasBufferedReplays() const { return buffered_replays.HasBufferedReplays(); } 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 506bff705..cc9c5fa63 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 @@ -47,7 +47,8 @@ class CSVCast { idx_t cur_line = 0; UnaryExecutor::Execute(input_vector, result_vector, count, [&](string_t input) { T result; - if (!OP::Operation(input, result, parameters, width, scale)) { + if (!VectorDecimalCast::Operation(input, result, result_vector, parameters, width, + scale)) { if (all_converted) { line_error = cur_line; } @@ -148,6 +149,9 @@ class CSVCast { case PhysicalType::INT128: return TemplatedTryCastDecimalVector( options, input_vector, result_vector, count, parameters, width, scale, line_error); + case PhysicalType::VARCHAR: + return TemplatedTryCastDecimalVector( + options, input_vector, result_vector, count, parameters, width, scale, line_error); default: throw InternalException("Unimplemented physical type for decimal"); } diff --git a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp index 82427984c..a476bc054 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp @@ -63,7 +63,8 @@ class BindAggregateFunctionInput : public BindFunctionInput { public: // Defined out-of-line: converting to the BindFunctionInput base requires the complete BoundAggregateFunction. BindAggregateFunctionInput(ClientContext &context_p, BoundAggregateFunction &bound_function_p, - vector> &arguments_p); + vector> &arguments_p, optional_ptr binder_p = nullptr, + optional_ptr decimal_width_limit_p = nullptr); BoundAggregateFunction &GetBoundFunction() const { return bound_function; diff --git a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp index 1962b51b4..92d710fdb 100644 --- a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp @@ -108,6 +108,14 @@ struct CastLocalStateParameters { optional_ptr cast_data; }; +//! The local state of a cast to or from a wide DECIMAL: the context lets long BIGNUM conversions check for interrupts +struct WideDecimalCastState : public FunctionLocalState { + explicit WideDecimalCastState(optional_ptr context_p) : context(context_p) { + } + + optional_ptr context; +}; + typedef bool (*cast_function_t)(Vector &source, Vector &result, idx_t count, CastParameters ¶meters); typedef unique_ptr (*init_cast_local_state_t)(CastLocalStateParameters ¶meters); @@ -181,6 +189,9 @@ struct BoundCastInfo { void SetStatisticsCallback(cast_statistics_t new_statistics) { statistics = new_statistics; } + void SetInitLocalState(init_cast_local_state_t new_init_local_state) { + init_local_state = new_init_local_state; + } DUCKDB_API unique_ptr PropagateStatistics(const LogicalType &source_type, const LogicalType &target_type, const BaseStatistics &child_stats, @@ -223,6 +234,11 @@ struct BindCastInput { struct DefaultCasts { DUCKDB_API static BoundCastInfo GetDefaultCastFunction(BindCastInput &input, const LogicalType &source, const LogicalType &target); + //! Attaches a WideDecimalCastState to a cast whose source or target is a DECIMAL wider than 38 digits + DUCKDB_API static BoundCastInfo WideDecimalCast(BoundCastInfo info, const LogicalType &source, + const LogicalType &target); + //! The client context of a cast with a WideDecimalCastState, null for a cast without one + DUCKDB_API static optional_ptr WideDecimalCastContext(CastParameters ¶meters); DUCKDB_API static bool NopCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters); DUCKDB_API static bool TryVectorNullCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters); diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp index 9e4b5f6f9..f5a73191d 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 @@ -57,15 +57,15 @@ VariantLogicalType GetTypeId(bool val) { //! -------- Write the 'value' data for the Value -------- template -static void WriteData(data_ptr_t ptr, const T &val, uint32_t lengths[3], EmptyConversionPayloadToVariant &) { +static void WriteData(data_ptr_t ptr, const T &val, uint32_t lengths[4], EmptyConversionPayloadToVariant &) { Store(val, ptr); } template <> -void WriteData(data_ptr_t ptr, const bool &val, uint32_t lengths[3], EmptyConversionPayloadToVariant &) { +void WriteData(data_ptr_t ptr, const bool &val, uint32_t lengths[4], EmptyConversionPayloadToVariant &) { return; } template <> -void WriteData(data_ptr_t ptr, const string_t &val, uint32_t lengths[3], EmptyConversionPayloadToVariant &) { +void WriteData(data_ptr_t ptr, const string_t &val, uint32_t lengths[4], EmptyConversionPayloadToVariant &) { auto str_length = val.GetSize(); VarintEncode(str_length, ptr); memcpy(ptr + lengths[0], val.GetData(), str_length); @@ -74,54 +74,63 @@ void WriteData(data_ptr_t ptr, const string_t &val, uint32_t lengths[3], EmptyCo //! decimal template -static void WriteData(data_ptr_t ptr, const T &val, uint32_t lengths[3], DecimalConversionPayloadToVariant &payload) { +static void WriteData(data_ptr_t ptr, const T &val, uint32_t lengths[4], DecimalConversionPayloadToVariant &payload) { InternalException::Throw("WriteData not implemented for this type"); } template <> -void WriteData(data_ptr_t ptr, const int16_t &val, uint32_t lengths[3], DecimalConversionPayloadToVariant &payload) { +void WriteData(data_ptr_t ptr, const int16_t &val, uint32_t lengths[4], DecimalConversionPayloadToVariant &payload) { VarintEncode(payload.width, ptr); VarintEncode(payload.scale, ptr + lengths[0]); Store(val, ptr + lengths[0] + lengths[1]); } template <> -void WriteData(data_ptr_t ptr, const int32_t &val, uint32_t lengths[3], DecimalConversionPayloadToVariant &payload) { +void WriteData(data_ptr_t ptr, const int32_t &val, uint32_t lengths[4], DecimalConversionPayloadToVariant &payload) { VarintEncode(payload.width, ptr); VarintEncode(payload.scale, ptr + lengths[0]); Store(val, ptr + lengths[0] + lengths[1]); } template <> -void WriteData(data_ptr_t ptr, const int64_t &val, uint32_t lengths[3], DecimalConversionPayloadToVariant &payload) { +void WriteData(data_ptr_t ptr, const int64_t &val, uint32_t lengths[4], DecimalConversionPayloadToVariant &payload) { VarintEncode(payload.width, ptr); VarintEncode(payload.scale, ptr + lengths[0]); Store(val, ptr + lengths[0] + lengths[1]); } template <> -void WriteData(data_ptr_t ptr, const hugeint_t &val, uint32_t lengths[3], DecimalConversionPayloadToVariant &payload) { +void WriteData(data_ptr_t ptr, const hugeint_t &val, uint32_t lengths[4], DecimalConversionPayloadToVariant &payload) { VarintEncode(payload.width, ptr); VarintEncode(payload.scale, ptr + lengths[0]); Store(val, ptr + lengths[0] + lengths[1]); } +template <> +void WriteData(data_ptr_t ptr, const string_t &val, uint32_t lengths[4], DecimalConversionPayloadToVariant &payload) { + // the BIGNUM blob of a decimal wider than 38 digits + VarintEncode(payload.width, ptr); + VarintEncode(payload.scale, ptr + lengths[0]); + VarintEncode(val.GetSize(), ptr + lengths[0] + lengths[1]); + memcpy(ptr + lengths[0] + lengths[1] + lengths[2], val.GetData(), val.GetSize()); +} + //! enum template -static void WriteData(data_ptr_t ptr, const T &val, uint32_t lengths[3], EnumConversionPayload &payload) { +static void WriteData(data_ptr_t ptr, const T &val, uint32_t lengths[4], EnumConversionPayload &payload) { InternalException::Throw("WriteData not implemented for this Enum physical type"); } template <> -void WriteData(data_ptr_t ptr, const uint8_t &val, uint32_t lengths[3], EnumConversionPayload &payload) { +void WriteData(data_ptr_t ptr, const uint8_t &val, uint32_t lengths[4], EnumConversionPayload &payload) { EmptyConversionPayloadToVariant empty_payload; auto &str = payload.GetString(val); WriteData(ptr, str, lengths, empty_payload); } template <> -void WriteData(data_ptr_t ptr, const uint16_t &val, uint32_t lengths[3], EnumConversionPayload &payload) { +void WriteData(data_ptr_t ptr, const uint16_t &val, uint32_t lengths[4], EnumConversionPayload &payload) { EmptyConversionPayloadToVariant empty_payload; auto &str = payload.GetString(val); WriteData(ptr, str, lengths, empty_payload); } template <> -void WriteData(data_ptr_t ptr, const uint32_t &val, uint32_t lengths[3], EnumConversionPayload &payload) { +void WriteData(data_ptr_t ptr, const uint32_t &val, uint32_t lengths[4], EnumConversionPayload &payload) { EmptyConversionPayloadToVariant empty_payload; auto &str = payload.GetString(val); WriteData(ptr, str, lengths, empty_payload); @@ -130,15 +139,15 @@ void WriteData(data_ptr_t ptr, const uint32_t &val, uint32_t lengths[3], EnumCon //! -------- Determine size of the 'value' data for the Value -------- template -static void GetValueSize(const T &val, uint32_t lengths[3], idx_t &lengths_size, EmptyConversionPayloadToVariant &) { +static void GetValueSize(const T &val, uint32_t lengths[4], idx_t &lengths_size, EmptyConversionPayloadToVariant &) { lengths[0] = sizeof(T); lengths_size = 1; } template <> -void GetValueSize(const bool &val, uint32_t lengths[3], idx_t &lengths_size, EmptyConversionPayloadToVariant &) { +void GetValueSize(const bool &val, uint32_t lengths[4], idx_t &lengths_size, EmptyConversionPayloadToVariant &) { } template <> -void GetValueSize(const string_t &val, uint32_t lengths[3], idx_t &lengths_size, EmptyConversionPayloadToVariant &) { +void GetValueSize(const string_t &val, uint32_t lengths[4], idx_t &lengths_size, EmptyConversionPayloadToVariant &) { auto value_size = val.GetSize(); lengths[0] = GetVarintSize(value_size); lengths[1] = static_cast(value_size); @@ -148,12 +157,12 @@ void GetValueSize(const string_t &val, uint32_t lengths[3], idx_t &lengths_size, //! decimal template -static void GetValueSize(const T &val, uint32_t lengths[3], idx_t &lengths_size, +static void GetValueSize(const T &val, uint32_t lengths[4], idx_t &lengths_size, DecimalConversionPayloadToVariant &payload) { InternalException::Throw("GetValueSize not implemented for this Decimal physical type"); } template <> -void GetValueSize(const int16_t &val, uint32_t lengths[3], idx_t &lengths_size, +void GetValueSize(const int16_t &val, uint32_t lengths[4], idx_t &lengths_size, DecimalConversionPayloadToVariant &payload) { lengths[0] = GetVarintSize(payload.width); lengths[1] = GetVarintSize(payload.scale); @@ -161,7 +170,7 @@ void GetValueSize(const int16_t &val, uint32_t lengths[3], idx_t &lengths_size, lengths_size = 3; } template <> -void GetValueSize(const int32_t &val, uint32_t lengths[3], idx_t &lengths_size, +void GetValueSize(const int32_t &val, uint32_t lengths[4], idx_t &lengths_size, DecimalConversionPayloadToVariant &payload) { lengths[0] = GetVarintSize(payload.width); lengths[1] = GetVarintSize(payload.scale); @@ -169,7 +178,7 @@ void GetValueSize(const int32_t &val, uint32_t lengths[3], idx_t &lengths_size, lengths_size = 3; } template <> -void GetValueSize(const int64_t &val, uint32_t lengths[3], idx_t &lengths_size, +void GetValueSize(const int64_t &val, uint32_t lengths[4], idx_t &lengths_size, DecimalConversionPayloadToVariant &payload) { lengths[0] = GetVarintSize(payload.width); lengths[1] = GetVarintSize(payload.scale); @@ -177,7 +186,7 @@ void GetValueSize(const int64_t &val, uint32_t lengths[3], idx_t &lengths_size, lengths_size = 3; } template <> -void GetValueSize(const hugeint_t &val, uint32_t lengths[3], idx_t &lengths_size, +void GetValueSize(const hugeint_t &val, uint32_t lengths[4], idx_t &lengths_size, DecimalConversionPayloadToVariant &payload) { lengths[0] = GetVarintSize(payload.width); lengths[1] = GetVarintSize(payload.scale); @@ -185,26 +194,36 @@ void GetValueSize(const hugeint_t &val, uint32_t lengths[3], idx_t &lengths_size lengths_size = 3; } +template <> +void GetValueSize(const string_t &val, uint32_t lengths[4], idx_t &lengths_size, + DecimalConversionPayloadToVariant &payload) { + lengths[0] = GetVarintSize(payload.width); + lengths[1] = GetVarintSize(payload.scale); + lengths[2] = GetVarintSize(val.GetSize()); + lengths[3] = static_cast(val.GetSize()); + lengths_size = 4; +} + //! enum template -static void GetValueSize(const T &val, uint32_t lengths[3], idx_t &lengths_size, EnumConversionPayload &payload) { +static void GetValueSize(const T &val, uint32_t lengths[4], idx_t &lengths_size, EnumConversionPayload &payload) { InternalException::Throw("GetValueSize not implemented for this Enum physical type"); } template <> -void GetValueSize(const uint8_t &val, uint32_t lengths[3], idx_t &lengths_size, EnumConversionPayload &payload) { +void GetValueSize(const uint8_t &val, uint32_t lengths[4], idx_t &lengths_size, EnumConversionPayload &payload) { EmptyConversionPayloadToVariant empty_payload; auto &str = payload.GetString(val); GetValueSize(str, lengths, lengths_size, empty_payload); } template <> -void GetValueSize(const uint16_t &val, uint32_t lengths[3], idx_t &lengths_size, EnumConversionPayload &payload) { +void GetValueSize(const uint16_t &val, uint32_t lengths[4], idx_t &lengths_size, EnumConversionPayload &payload) { EmptyConversionPayloadToVariant empty_payload; auto &str = payload.GetString(val); GetValueSize(str, lengths, lengths_size, empty_payload); } template <> -void GetValueSize(const uint32_t &val, uint32_t lengths[3], idx_t &lengths_size, EnumConversionPayload &payload) { +void GetValueSize(const uint32_t &val, uint32_t lengths[4], idx_t &lengths_size, EnumConversionPayload &payload) { EmptyConversionPayloadToVariant empty_payload; auto &str = payload.GetString(val); GetValueSize(str, lengths, lengths_size, empty_payload); @@ -224,7 +243,7 @@ static bool ConvertPrimitiveTemplated(ToVariantSourceData &source, ToVariantGlob auto source_data = source_format.GetData(source_format); auto &variant = result.variant; - uint32_t lengths[3]; + uint32_t lengths[4]; for (idx_t i = 0; i < count; i++) { auto index = source[i]; // the blob space to reserve for this row - nothing for NULL rows @@ -362,6 +381,10 @@ bool ConvertPrimitiveToVariant(ToVariantSourceData &source, ToVariantGlobalResul case PhysicalType::INT128: return ConvertPrimitiveTemplated( source, result, count, selvec, values_index_selvec, payload, is_root); + case PhysicalType::VARCHAR: + // decimals wider than 38 digits are BIGNUM blobs + return ConvertPrimitiveTemplated( + source, result, count, selvec, values_index_selvec, payload, is_root); default: NotImplementedException::Throw("Can't convert DECIMAL value of physical type: %s", physical_type); }; diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp index bc15f4a4c..3bf35f0b0 100644 --- a/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp @@ -116,9 +116,14 @@ struct VariantToVariantSizeAnalyzer { } template - static uint32_t VisitDecimal(T, uint32_t width, uint32_t scale, AnalyzeState &state) { + static uint32_t VisitDecimal(T val, uint32_t width, uint32_t scale, AnalyzeState &state) { uint32_t size = GetVarintSize(width) + GetVarintSize(scale); - size += sizeof(T); + if constexpr (std::is_same::value) { + // the BIGNUM blob of a decimal wider than 38 digits + size += VisitString(val.data, state); + } else { + size += sizeof(T); + } return size; } @@ -222,8 +227,13 @@ struct VariantToVariantDataWriter { static void VisitDecimal(T val, uint32_t width, uint32_t scale, WriteState &state) { state.blob_size += VarintEncode(width, state.GetDestination()); state.blob_size += VarintEncode(scale, state.GetDestination()); - Store(val, state.GetDestination()); - state.blob_size += sizeof(T); + if constexpr (std::is_same::value) { + // the BIGNUM blob of a decimal wider than 38 digits + VisitString(val.data, state); + } else { + Store(val, state.GetDestination()); + state.blob_size += sizeof(T); + } } static void VisitArray(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, 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 910dc9040..4c954c58a 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 @@ -96,8 +96,9 @@ struct VectorDecimalCastOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, VectorDecimalCastData &data) { RESULT_TYPE result_value; - if (!OP::template Operation(input, result_value, data.vector_cast_data.parameters, - data.width, data.scale)) { + if (!VectorDecimalCast::Operation( + input, result_value, data.vector_cast_data.result, data.vector_cast_data.parameters, data.width, + data.scale)) { return HandleVectorCastError::Operation("Failed to cast decimal value", mask, idx, data.vector_cast_data); } @@ -171,6 +172,8 @@ struct VectorCastHelpers { case PhysicalType::INT128: return TemplatedDecimalCast(source, result, count, parameters, width, scale); + case PhysicalType::VARCHAR: + return TemplatedDecimalCast(source, result, count, parameters, width, scale); default: InternalException::Throw("Unimplemented internal type for decimal"); } diff --git a/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp b/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp index 9393caa4c..4ffd33d01 100644 --- a/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp +++ b/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp @@ -12,17 +12,24 @@ namespace duckdb { class ClientContext; +class DecimalWidthLimit; class LogicalTypeResolver { public: - explicit LogicalTypeResolver(optional_ptr context_p) : context(context_p) { + explicit LogicalTypeResolver(optional_ptr context_p, + optional_ptr decimal_width_limit_p = nullptr) + : context(context_p), decimal_width_limit(decimal_width_limit_p) { } virtual ~LogicalTypeResolver() = default; virtual bool Operation(const LogicalType &left, const LogicalType &right, LogicalType &result) = 0; + //! The widest DECIMAL combining constructs: the limit, or the max_decimal_width setting without one + DecimalWidthLimit GetDecimalWidthLimit() const; public: optional_ptr context; + //! The limit of the DECIMAL widths the binder constructs, if one is given + optional_ptr decimal_width_limit; }; typedef bool (*combine_types_rule_function_t)(LogicalTypeResolver &resolver, const LogicalType &left, diff --git a/src/duckdb/src/include/duckdb/function/function.hpp b/src/duckdb/src/include/duckdb/function/function.hpp index eee977d25..025598466 100644 --- a/src/duckdb/src/include/duckdb/function/function.hpp +++ b/src/duckdb/src/include/duckdb/function/function.hpp @@ -41,6 +41,9 @@ class FunctionProperties; class WindowFunction; class WindowFunctionSet; class BoundSimpleFunction; +class Binder; +class DecimalWidthLimit; +class FunctionBinder; struct PragmaInfo; @@ -712,13 +715,27 @@ class BoundSimpleFunction { class BindFunctionInput { public: BindFunctionInput(ClientContext &context_p, const BoundSimpleFunction &function_p, - const FunctionSignature &signature_p, vector> &arguments_p) - : context(context_p), function(function_p), signature(signature_p), arguments(arguments_p) { + const FunctionSignature &signature_p, vector> &arguments_p, + optional_ptr binder_p = nullptr, + optional_ptr decimal_width_limit_p = nullptr) + : context(context_p), function(function_p), signature(signature_p), arguments(arguments_p), binder(binder_p), + decimal_width_limit(decimal_width_limit_p) { } ClientContext &GetClientContext() const { return context; } + //! The binder of the query the function is bound in, if any: a rebind outside of a query has none + bool HasBinder() const { + return binder != nullptr; + } + DUCKDB_API Binder &GetBinder(); + //! A binder for the functions the bind nests: it binds as this function is bound, within its query or within its + //! fixed decimal width + DUCKDB_API FunctionBinder NestedFunctionBinder(); + //! The widest DECIMAL the bind constructs: the limit of the binder, the fixed limit of a bind outside of a query + //! (a deserialized function is rebound within the width it was bound in), or the max_decimal_width setting + DUCKDB_API DecimalWidthLimit GetDecimalWidthLimit() const; vector> &GetArguments() const { return arguments; } @@ -759,6 +776,9 @@ class BindFunctionInput { const BoundSimpleFunction &function; const FunctionSignature &signature; vector> &arguments; + optional_ptr binder; + //! The fixed limit of a bind outside of a query, if any + optional_ptr decimal_width_limit; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/function_binder.hpp b/src/duckdb/src/include/duckdb/function/function_binder.hpp index 2617759a9..d88395327 100644 --- a/src/duckdb/src/include/duckdb/function/function_binder.hpp +++ b/src/duckdb/src/include/duckdb/function/function_binder.hpp @@ -391,19 +391,29 @@ class FunctionBinder { public: DUCKDB_API explicit FunctionBinder(Binder &binder); DUCKDB_API explicit FunctionBinder(ClientContext &context); + //! Binds outside of a query within a fixed decimal width, if one is given: a deserialized function is rebound + //! within the width it was bound in + DUCKDB_API FunctionBinder(ClientContext &context, optional_ptr decimal_width_limit); optional_ptr binder; ClientContext &context; + //! The fixed limit of the DECIMAL widths a bind outside of a query constructs, if any + optional_ptr decimal_width_limit; //! 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. //! Selection needs no binder - without a ClientContext only the built-in implicit casts are considered. With - //! explicit casts, an argument that cannot be implicitly cast to its parameter is accepted too - DUCKDB_API static FunctionBindResult SelectFunction(optional_ptr context, - const BaseFunctionSet &functions, - const FunctionCallArguments &call, bool explicit_casts = false); + //! explicit casts, an argument that cannot be implicitly cast to its parameter is accepted too. Template types + //! unify decimals within the limit, if one is given, else within the max_decimal_width setting + DUCKDB_API static FunctionBindResult + SelectFunction(optional_ptr context, const BaseFunctionSet &functions, + const FunctionCallArguments &call, bool explicit_casts = false, + optional_ptr decimal_width_limit = nullptr); + //! The fixed limit of the DECIMAL widths the binder constructs, if any: set while the keys of an index are bound, + //! and while a function is deserialized + optional_ptr FixedDecimalWidthLimit() const; //! Bind a table function: select the overload, check the named arguments against its signature, and fold the //! arguments to the constants it is called with, cast to the types it declares. Returns nullptr and sets the error @@ -589,7 +599,8 @@ class FunctionBinder { //! explicit casts, an argument that cannot be implicitly cast to its parameter is accepted too static std::variant MatchOverload(optional_ptr context, idx_t overload, shared_ptr function, - const FunctionCallArguments &call, bool explicit_casts); + const FunctionCallArguments &call, bool explicit_casts, + optional_ptr decimal_width_limit = nullptr); //! How a call binds to a function it is known to call - the arguments are cast explicitly. Throws if the call does //! not fit the signature of the function template diff --git a/src/duckdb/src/include/duckdb/function/function_serialization.hpp b/src/duckdb/src/include/duckdb/function/function_serialization.hpp index 9db57431b..2711e1f86 100644 --- a/src/duckdb/src/include/duckdb/function/function_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/function_serialization.hpp @@ -12,6 +12,7 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/common/serializer/serializer.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/function/function_binder.hpp" @@ -452,10 +453,12 @@ class FunctionSerializer { } } - // Lookup the function (and the correct overload) - FunctionBinder binder(context); + // Lookup the function (and the correct overload), binding within the decimal width the function was bound in + const auto decimal_width_limit = DecimalWidthLimit::FromReturnType(return_type); + FunctionBinder binder(context, &decimal_width_limit); binder.arguments_collated = true; - const auto func_idx = FunctionBinder::SelectFunction(context, functions, {positional_types, keyword_types}); + const auto func_idx = FunctionBinder::SelectFunction(context, functions, {positional_types, keyword_types}, + false, binder.FixedDecimalWidthLimit()); optional_idx overload; if (func_idx.IsSuccess()) { overload = func_idx.GetBinding().GetOverloadIndex(); @@ -490,7 +493,8 @@ class FunctionSerializer { // arguments it is called with std::decay_t overload(functions.name); overload.AddFunction(function); - auto rebind = FunctionBinder::SelectFunction(context, overload, {children, keyword_args}, true); + auto rebind = FunctionBinder::SelectFunction(context, overload, {children, keyword_args}, true, + binder.FixedDecimalWidthLimit()); if (!rebind) { rebind.GetError().Throw(); } diff --git a/src/duckdb/src/include/duckdb/function/pragma/pragma_functions.hpp b/src/duckdb/src/include/duckdb/function/pragma/pragma_functions.hpp index 8b846583a..daa8a9609 100644 --- a/src/duckdb/src/include/duckdb/function/pragma/pragma_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/pragma/pragma_functions.hpp @@ -10,7 +10,6 @@ #include "duckdb/function/pragma_function.hpp" #include "duckdb/function/built_in_functions.hpp" -#include "duckdb/common/optional_idx.hpp" namespace duckdb { @@ -22,8 +21,7 @@ struct PragmaFunctions { static void RegisterFunction(BuiltinFunctions &set); }; -string PragmaShowTables(const string &catalog = "", const string &schema = "", - optional_idx schema_oid = optional_idx()); +string PragmaShowTables(const string &filter); string PragmaShowTablesExpanded(); string PragmaShowDatabases(); string PragmaShowVariables(); diff --git a/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp b/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp index 3bc38cba6..81dfca8d0 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp @@ -120,6 +120,9 @@ struct VariantUtils { DUCKDB_API static bool IsNestedType(const UnifiedVariantVectorData &variant, idx_t row, uint32_t value_index); DUCKDB_API static VariantDecimalData DecodeDecimalData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t value_index); + //! The BIGNUM blob of a DECIMAL value wider than 38 digits, which follows the (width, scale) prefix + DUCKDB_API static string_t DecodeWideDecimalData(const UnifiedVariantVectorData &variant, idx_t row, + uint32_t value_index); DUCKDB_API static VariantNestedData DecodeNestedData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t value_index); DUCKDB_API static string_t DecodeStringData(const UnifiedVariantVectorData &variant, idx_t row, diff --git a/src/duckdb/src/include/duckdb/function/scalar_function.hpp b/src/duckdb/src/include/duckdb/function/scalar_function.hpp index 23113e948..4a7c909de 100644 --- a/src/duckdb/src/include/duckdb/function/scalar_function.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar_function.hpp @@ -103,14 +103,24 @@ struct FunctionModifiedDatabasesInput { struct FunctionBindExpressionInput { FunctionBindExpressionInput(ClientContext &context_p, BoundScalarFunction &bound_function, - optional_ptr bind_data_p, vector> &children_p) - : context(context_p), bound_function(bound_function), bind_data(bind_data_p), children(children_p) { + optional_ptr bind_data_p, vector> &children_p, + optional_ptr binder_p = nullptr, + optional_ptr decimal_width_limit_p = nullptr) + : context(context_p), bound_function(bound_function), bind_data(bind_data_p), children(children_p), + binder(binder_p), decimal_width_limit(decimal_width_limit_p) { } ClientContext &context; BoundScalarFunction &bound_function; optional_ptr bind_data; vector> &children; + //! The binder of the query the function is bound in, if any + optional_ptr binder; + //! The fixed limit of a bind outside of a query, if any + optional_ptr decimal_width_limit; + + //! The widest DECIMAL the expression constructs: the limit of the binder, the fixed limit, or the setting + DUCKDB_API DecimalWidthLimit GetDecimalWidthLimit() const; }; struct FunctionUnbindInput { @@ -666,42 +676,39 @@ class BoundScalarFunction : public BaseScalarFunction, publ class BindScalarFunctionInput : public BindFunctionInput { public: BindScalarFunctionInput(ClientContext &context_p, BoundScalarFunction &bound_function_p, - vector> &arguments_p, optional_ptr binder_p = nullptr) - : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p), - bound_function(bound_function_p), binder(binder_p) { + vector> &arguments_p, optional_ptr binder_p = nullptr, + optional_ptr decimal_width_limit_p = nullptr) + : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p, + binder_p, decimal_width_limit_p), + bound_function(bound_function_p) { } BoundScalarFunction &GetBoundFunction() const { return bound_function; } - bool HasBinder() const { - return binder != nullptr; - } - Binder &GetBinder() { - if (binder == nullptr) { - throw InternalException("Function %s has cannot be bound without a Binder!", bound_function.GetName()); - } - return *binder; - } private: BoundScalarFunction &bound_function; - optional_ptr binder; }; //! Input of the resolve_types callback - the arguments are read-only, the bound function can be modified class ResolveScalarFunctionTypesInput : private BindFunctionInput { public: ResolveScalarFunctionTypesInput(ClientContext &context_p, BoundScalarFunction &bound_function_p, - vector> &arguments_p) - : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p), + vector> &arguments_p, + optional_ptr binder_p = nullptr, + optional_ptr decimal_width_limit_p = nullptr) + : BindFunctionInput(context_p, bound_function_p, bound_function_p.GetDefinition()->GetSignature(), arguments_p, + binder_p, decimal_width_limit_p), bound_function(bound_function_p), arguments(arguments_p) { } using BindFunctionInput::GetArgumentName; using BindFunctionInput::GetClientContext; using BindFunctionInput::GetConstant; + using BindFunctionInput::GetDecimalWidthLimit; using BindFunctionInput::GetNonNullConstant; + using BindFunctionInput::NestedFunctionBinder; using BindFunctionInput::TryGetConstant; BoundScalarFunction &GetBoundFunction() const { diff --git a/src/duckdb/src/include/duckdb/function/type_constructor.hpp b/src/duckdb/src/include/duckdb/function/type_constructor.hpp index 14242f215..395e1e561 100644 --- a/src/duckdb/src/include/duckdb/function/type_constructor.hpp +++ b/src/duckdb/src/include/duckdb/function/type_constructor.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/identifier.hpp" #include "duckdb/common/query_location.hpp" #include "duckdb/common/string_util.hpp" @@ -62,6 +63,12 @@ struct BindLogicalTypeInput { const vector &modifiers; //! Location of the type expression as a whole, for errors that are not about one particular modifier QueryLocation query_location; + //! The limit of the DECIMAL widths the binder constructs, the max_decimal_width setting without one + optional_ptr decimal_width_limit; + + DecimalWidthLimit GetDecimalWidthLimit() const { + return decimal_width_limit ? *decimal_width_limit : DecimalWidthLimit::FromSetting(context); + } //! Location of the given modifier, falling back to the type itself - a modifier filled in from a parameter //! default has no source text of its own. @@ -122,10 +129,10 @@ class TypeConstructorSet : public FunctionSet { //! Select the constructor matching the given arguments and invoke it. The context may be null, in which case only //! the built-in implicit cast rules are available. The location is that of the type expression as a whole, and is - //! only available when the type came from source text. + //! only available when the type came from source text. Decimals are bound within the limit, if one is given DUCKDB_API LogicalType Bind(optional_ptr context, const LogicalType &base_type, - const vector &arguments, - QueryLocation query_location = QueryLocation()) const; + const vector &arguments, QueryLocation query_location = QueryLocation(), + optional_ptr decimal_width_limit = nullptr) const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp index 5b97ec1b9..1a9628271 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp @@ -1,7 +1,10 @@ #pragma once -#include "duckdb/function/scalar/variant_utils.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/serializer/varint.hpp" +#include "duckdb/function/scalar/variant_utils.hpp" + +#include namespace duckdb { @@ -73,8 +76,13 @@ struct VariantNormalizer { static void VisitDecimal(T val, uint32_t width, uint32_t scale, VariantNormalizerState &state) { state.blob_size += VarintEncode(width, state.GetDestination()); state.blob_size += VarintEncode(scale, state.GetDestination()); - Store(val, state.GetDestination()); - state.blob_size += sizeof(T); + if constexpr (std::is_same::value) { + // the BIGNUM blob of a decimal wider than 38 digits + VisitString(val.data, state); + } else { + Store(val, state.GetDestination()); + state.blob_size += sizeof(T); + } } static void VisitArray(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, 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 32b5b763e..e48911771 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 @@ -100,6 +100,8 @@ struct ValueConverter { return Value::DECIMAL(val, width, scale); } else if (std::is_same::value) { return Value::DECIMAL(val, width, scale); + } else if (std::is_same::value) { + return Value::DECIMAL(val, width, scale); } else { throw InternalException("Unhandled decimal type"); } diff --git a/src/duckdb/src/include/duckdb/function/window_function.hpp b/src/duckdb/src/include/duckdb/function/window_function.hpp index dbd14e015..9655a31d2 100644 --- a/src/duckdb/src/include/duckdb/function/window_function.hpp +++ b/src/duckdb/src/include/duckdb/function/window_function.hpp @@ -70,7 +70,7 @@ class BindWindowFunctionInput : public BindFunctionInput { // Defined out-of-line: converting to the BindFunctionInput base requires the complete BoundWindowFunction. BindWindowFunctionInput(ClientContext &context_p, BoundWindowFunction &bound_function_p, vector> &arguments_p, OptionalOrderTypes order_types_p = nullptr, - OptionalOrderTypes arg_order_types_p = nullptr); + OptionalOrderTypes arg_order_types_p = nullptr, optional_ptr binder_p = nullptr); BoundWindowFunction &GetBoundFunction() const { return bound_function; diff --git a/src/duckdb/src/include/duckdb/main/capi/cast/from_decimal.hpp b/src/duckdb/src/include/duckdb/main/capi/cast/from_decimal.hpp index 013978f8e..ff36606eb 100644 --- a/src/duckdb/src/include/duckdb/main/capi/cast/from_decimal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi/cast/from_decimal.hpp @@ -8,7 +8,9 @@ #pragma once +#include "duckdb/common/type_util.hpp" #include "duckdb/main/capi/cast/utils.hpp" +#include "duckdb/main/query_result.hpp" namespace duckdb { @@ -35,6 +37,19 @@ bool CastDecimalCInternal(duckdb_result *source, RESULT_TYPE &result, idx_t col, case duckdb::PhysicalType::INT128: return duckdb::TryCastFromDecimal::Operation(source_value, result, parameters, width, scale); + case duckdb::PhysicalType::VARCHAR: { + // the materialized duckdb_decimal only holds 128-bit values, so convert the original value instead + auto value = query_result->Collection().GetValue(col, row); + if (value.IsNull()) { + return false; + } + auto converted = value.DefaultTryCastAs(PrimitiveToLogicalType()); + if (!converted) { + return false; + } + result = converted->template GetValue(); + return true; + } default: InternalException::Throw("Unimplemented internal type for decimal"); } diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index 50319b328..04cfbd2ae 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -1665,15 +1665,34 @@ static constexpr ExtensionEntry EXTENSION_LOG_TYPES[] = { {"Iceberg", "iceberg"}, {"PostgresQueryLog", "postgres_scanner"}, {"Quack", "quack"}, }; // END_OF_EXTENSION_LOG_TYPES -static constexpr const char *AUTOLOADABLE_EXTENSIONS[] = {"autocomplete", "avro", "aws", - "azure", "core_functions", "delta", - "ducklake", "encodings", "excel", - "fts", "httpfs", "iceberg", - "icu", "inet", "json", - "legacy_parser", "motherduck", "mysql_scanner", - "odbc_scanner", "parquet", "postgres_scanner", - "quack", "sqlite_scanner", "sqlsmith", - "tpcds", "tpch", "ui", +static constexpr const char *AUTOLOADABLE_EXTENSIONS[] = {"autocomplete", + "avro", + "aws", + "azure", + "core_functions", + "delta", + "ducklake", + "encodings", + "excel", + "fts", + "glue", + "httpfs", + "iceberg", + "icu", + "inet", + "json", + "legacy_parser", + "motherduck", + "mysql_scanner", + "odbc_scanner", + "parquet", + "postgres_scanner", + "quack", + "sqlite_scanner", + "sqlsmith", + "tpcds", + "tpch", + "ui", "unity_catalog"}; // END_OF_AUTOLOADABLE_EXTENSIONS } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index fb52ac070..06103698e 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -2225,6 +2225,24 @@ struct MatchRecognizeMaxStatesSetting { static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; +struct MaxDecimalWidthSetting { + using RETURN_TYPE = idx_t; + static constexpr const char *Name = "max_decimal_width"; + static constexpr const char *Description = + "The maximum width (number of digits) of a DECIMAL type, at least 38. Decimals wider than 38 digits are " + "computed on BIGNUM blobs whose cost grows with the width, so the bound limits the time and memory a single " + "value can take: a type declaration, a cast or a literal wider than the bound raises an error, and above 38 so " + "does an arithmetic result that would need a wider DECIMAL. At 38, the setting preserves the types of the " + "versions before wide decimals: arithmetic results stay within 38 digits, as they did there. Index keys are " + "bound independently of the setting."; + static constexpr const char *InputType = "UBIGINT"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "1000000"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct MaxExecutionTimeSetting { using RETURN_TYPE = int64_t; static constexpr const char *Name = "max_execution_time"; diff --git a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp index c71e97e15..76a07b725 100644 --- a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp @@ -111,6 +111,12 @@ class StatisticsPropagator { //! Return statistics from a constant value unique_ptr StatisticsFromValue(const Value &input); + //! The min/max of numeric statistics: the fixed-size types and the bignum_t tier of decimals + static bool HasNumericMinMax(const BaseStatistics &stats); + static Value NumericMin(const BaseStatistics &stats); + static Value NumericMax(const BaseStatistics &stats); + static void SetNumericMin(BaseStatistics &stats, const Value &val); + static void SetNumericMax(BaseStatistics &stats, const Value &val); //! Update filter statistics from a filter with a constant void UpdateFilterStatistics(BaseStatistics &input, ExpressionType comparison_type, const Value &constant); //! Update statistics from a filter between two stats @@ -124,7 +130,9 @@ class StatisticsPropagator { //! Reset additive statistics of bindings whose rows an operator can emit more than once void ResetAdditiveStatistics(const vector &bindings); //! Reset additive statistics in the verification statistics of an expression tree - void ResetAdditiveVerificationStats(Expression &expr); + //! Join conditions are evaluated over candidate pairs that repeat rows and still hold NULLs: their verification + //! statistics carry neither additive totals nor the absence of NULLs + void RelaxJoinConditionVerificationStats(Expression &expr); //! Determine whether a propagated condition can be pruned FilterPropagateResult ClassifyFilter(Expression &condition); //! Simplify conjunctions using filter truth semantics diff --git a/src/duckdb/src/include/duckdb/parser/constraints/foreign_key_constraint.hpp b/src/duckdb/src/include/duckdb/parser/constraints/foreign_key_constraint.hpp index 372c4ef9b..96a06b13f 100644 --- a/src/duckdb/src/include/duckdb/parser/constraints/foreign_key_constraint.hpp +++ b/src/duckdb/src/include/duckdb/parser/constraints/foreign_key_constraint.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/parser/constraint.hpp" +#include "duckdb/parser/qualified_name.hpp" #include "duckdb/common/vector.hpp" namespace duckdb { @@ -25,6 +26,8 @@ class ForeignKeyConstraint : public Constraint { //! The set of foreign key table's columns vector fk_columns; ForeignKeyInfo info; + //! The referenced table, including its schema path + QualifiedName referenced_table; public: DUCKDB_API string ToString() const override; diff --git a/src/duckdb/src/include/duckdb/parser/literal.hpp b/src/duckdb/src/include/duckdb/parser/literal.hpp index f0df3d5f0..577a51404 100644 --- a/src/duckdb/src/include/duckdb/parser/literal.hpp +++ b/src/duckdb/src/include/duckdb/parser/literal.hpp @@ -71,6 +71,8 @@ struct Literal { void Verify() const; //! Converts the literal into a Value Value ToValue() const; + //! Converts the literal into a Value, a numeric literal wider than max_decimal_width digits becomes a DOUBLE + Value ToValue(uint32_t max_decimal_width) const; //! Renders the literal as SQL text that parses back to the same literal string ToString() const; 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 6115a963d..922adee9d 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -1114,7 +1114,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 85, 115, 105, 110, 103, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 39, 85, 83, 73, 78, 71, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 65, 108, 116, 101, 114, 86, 105, 101, 119, 83, 116, 109, 116, 32, 60, 45, 32, 39, 86, 73, 69, 87, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 66, 97, 115, 101, 84, 97, 98, 108, 101, 78, 97, 109, 101, 32, 82, 101, 110, 97, 109, 101, 65, 108, 116, 101, 114, 10, 65, 108, 116, 101, 114, 83, 101, 113, 117, 101, 110, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 83, 69, 81, 85, 69, 78, 67, 69, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 32, 65, 108, 116, 101, 114, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 115, 10, - 81, 117, 97, 108, 105, 102, 105, 101, 100, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 32, 60, 45, 32, 67, 97, 116, 97, 108, 111, 103, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 63, 32, 83, 99, 104, 101, 109, 97, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 63, 32, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 10, + 81, 117, 97, 108, 105, 102, 105, 101, 100, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 32, 60, 45, 32, 67, 97, 116, 97, 108, 111, 103, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 63, 32, 83, 99, 104, 101, 109, 97, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 42, 32, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 10, 65, 108, 116, 101, 114, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 115, 32, 60, 45, 32, 82, 101, 110, 97, 109, 101, 65, 108, 116, 101, 114, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 115, 32, 47, 32, 83, 101, 116, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 10, 82, 101, 110, 97, 109, 101, 65, 108, 116, 101, 114, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 115, 32, 60, 45, 32, 82, 101, 110, 97, 109, 101, 65, 108, 116, 101, 114, 10, 83, 101, 116, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 32, 60, 45, 32, 83, 101, 113, 117, 101, 110, 99, 101, 79, 112, 116, 105, 111, 110, 43, 10, @@ -1476,7 +1476,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 81, 117, 97, 108, 105, 102, 105, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 32, 60, 45, 32, 67, 97, 116, 97, 108, 111, 103, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 73, 110, 100, 101, 120, 32, 47, 32, 83, 99, 104, 101, 109, 97, 82, 101, 115, 101, 114, 118, 101, 100, 73, 110, 100, 101, 120, 32, 47, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 83, 116, 114, 105, 110, 103, 10, 81, 117, 97, 108, 105, 102, 105, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 83, 116, 114, 105, 110, 103, 32, 60, 45, 32, 73, 110, 100, 101, 120, 78, 97, 109, 101, 10, 83, 99, 104, 101, 109, 97, 82, 101, 115, 101, 114, 118, 101, 100, 73, 110, 100, 101, 120, 32, 60, 45, 32, 83, 99, 104, 101, 109, 97, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 32, 82, 101, 115, 101, 114, 118, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 10, - 67, 97, 116, 97, 108, 111, 103, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 73, 110, 100, 101, 120, 32, 60, 45, 32, 67, 97, 116, 97, 108, 111, 103, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 32, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 32, 82, 101, 115, 101, 114, 118, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 10, + 67, 97, 116, 97, 108, 111, 103, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 73, 110, 100, 101, 120, 32, 60, 45, 32, 67, 97, 116, 97, 108, 111, 103, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 32, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 43, 32, 82, 101, 115, 101, 114, 118, 101, 100, 73, 110, 100, 101, 120, 78, 97, 109, 101, 10, 68, 114, 111, 112, 83, 101, 113, 117, 101, 110, 99, 101, 32, 60, 45, 32, 39, 83, 69, 81, 85, 69, 78, 67, 69, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 81, 117, 97, 108, 105, 102, 105, 101, 100, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 41, 10, 68, 114, 111, 112, 67, 111, 108, 108, 97, 116, 105, 111, 110, 32, 60, 45, 32, 39, 67, 79, 76, 76, 65, 84, 73, 79, 78, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 67, 111, 108, 108, 97, 116, 105, 111, 110, 78, 97, 109, 101, 41, 10, 68, 114, 111, 112, 84, 121, 112, 101, 32, 60, 45, 32, 39, 84, 89, 80, 69, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 76, 105, 115, 116, 40, 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 121, 112, 101, 78, 97, 109, 101, 41, 10, 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 c60f260a8..3f05977c0 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 @@ -2799,7 +2799,7 @@ class PEGTransformerFactory { unique_ptr alter_sequence_options); static QualifiedName TransformQualifiedSequenceName(PEGTransformer &transformer, const optional &catalog_qualification, - const optional &schema_qualification, + const optional> &schema_qualification, const Identifier &sequence_name); static unique_ptr TransformRenameAlterSequenceOptions(PEGTransformer &transformer, unique_ptr rename_alter); @@ -3417,7 +3417,7 @@ class PEGTransformerFactory { const Identifier &reserved_index_name); static QualifiedName TransformCatalogReservedSchemaIndex(PEGTransformer &transformer, const Identifier &catalog_qualification, - const Identifier &reserved_schema_qualification, + const vector &reserved_schema_qualification, const Identifier &reserved_index_name); static unique_ptr TransformDropSequence(PEGTransformer &transformer, const optional &if_exists, const vector &qualified_sequence_name); diff --git a/src/duckdb/src/include/duckdb/planner/binder.hpp b/src/duckdb/src/include/duckdb/planner/binder.hpp index 4ebe14b0c..2a52e56b5 100644 --- a/src/duckdb/src/include/duckdb/planner/binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/binder.hpp @@ -17,6 +17,7 @@ #include "duckdb/common/reference_map.hpp" #include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/parser/column_definition.hpp" #include "duckdb/parser/tableref/match_recognize_ref.hpp" #include "duckdb/parser/query_node.hpp" @@ -442,6 +443,12 @@ class Binder : public enable_shared_from_this { //! Set while binding the key expressions of an index void SetBindingIndexKey(bool binding_index_key); bool IsBindingIndexKey() const; + //! The widest DECIMAL the binder constructs: the max_decimal_width setting, or the fixed limit of the keys of an + //! index while they are bound + DecimalWidthLimit GetDecimalWidthLimit() const; + optional_ptr GetFixedDecimalWidthLimit() const; + //! Binds decimals within the limit instead of the setting while it is set, the limit outlives the binding + void SetDecimalWidthLimit(optional_ptr limit); void SetBindingTrySubquery(); bool IsBindingTrySubquery() const; const TrySubqueryPlanIndexes &GetTrySubqueryPlanIndexes() const; @@ -480,6 +487,8 @@ class Binder : public enable_shared_from_this { bool inside_subquery = false; //! Whether the key expressions of an index are being bound bool binding_index_key = false; + //! The fixed limit of the DECIMAL widths this binder constructs, set while the keys of an index are bound + optional_ptr decimal_width_limit; //! 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 diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp index ad3ec5b8b..03021b19a 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp @@ -11,6 +11,8 @@ #include "duckdb/planner/expression/bound_function_expression.hpp" namespace duckdb { +class DecimalWidthLimit; + //! The BoundComparisonExpression has been moved to a function expression //! This class exists only as a set of helper methods struct BoundComparisonExpression { @@ -24,9 +26,10 @@ struct BoundComparisonExpression { static unique_ptr &RightMutable(BoundFunctionExpression &between_expr); static unique_ptr Create(ExpressionType type, unique_ptr left, unique_ptr right); - //! Create a comparison, casting both sides to a common type - throws if they cannot be compared + //! Create a comparison, casting both sides to a common type within the limit of the binder, if any - throws if + //! they cannot be compared static unique_ptr Bind(ClientContext &context, ExpressionType type, unique_ptr left, - unique_ptr right); + unique_ptr right, optional_ptr binder = nullptr); //! Flip the comparison type, updating both the expression type and the bind data. //! Use instead of SetExpressionTypeUnsafe to keep the two in sync. @@ -39,5 +42,9 @@ struct BoundComparisonExpression { const LogicalType &right_type, ExpressionType comparison_type); static bool TryBindComparison(ClientContext &context, const LogicalType &left_type, const LogicalType &right_type, LogicalType &result_type, ExpressionType comparison_type); + //! Binds the width of a DECIMAL result within the limit instead of the max_decimal_width setting + static bool TryBindComparison(ClientContext &context, const LogicalType &left_type, const LogicalType &right_type, + LogicalType &result_type, ExpressionType comparison_type, + const DecimalWidthLimit &decimal_width_limit); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/expression_binder/index_binder.hpp b/src/duckdb/src/include/duckdb/planner/expression_binder/index_binder.hpp index fae9d560a..9e636a1b7 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_binder/index_binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_binder/index_binder.hpp @@ -18,15 +18,28 @@ namespace duckdb { class BoundColumnRefExpression; +class ConstantExpression; class LogicalOperator; +//! The keys of an index while they are bound +struct IndexKeyBinding { + //! The storage version the keys are stored at + StorageVersion version; + //! Whether the keys are stored keys, bound as the engines of their version bound them, rather than new keys + bool stored; + //! The first cast between BIGNUM and DECIMAL that the engines before wide decimals compute otherwise, if any + string legacy_cast; +}; + //! The IndexBinder binds indexes and expressions within index statements. class IndexBinder : public ExpressionBinder { public: IndexBinder(Binder &binder, ClientContext &context, optional_ptr table = nullptr, optional_ptr info = nullptr); - unique_ptr BindIndex(const UnboundIndex &index); + //! Binds a stored index. An index whose stored keys the engines of its storage version compute otherwise is + //! refused, or left unbound (nullptr) when skip_mismatched_keys is set, for a read that can do without it + unique_ptr BindIndex(const UnboundIndex &index, bool skip_mismatched_keys = false); unique_ptr BindCreateIndex(ClientContext &context, unique_ptr create_index_info, TableCatalogEntry &table_entry, unique_ptr plan, unique_ptr alter_table_info); @@ -40,10 +53,19 @@ class IndexBinder : public ExpressionBinder { bool root_expression = false) override; string UnsupportedAggregateMessage() override; +private: + //! Binds a literal of a stored key as the engines before wide decimals bound it + BindResult BindLegacyConstant(ConstantExpression &expr); + //! Binds the casts between BIGNUM and DECIMAL of a bound key node as the engines before wide decimals bound them + void BindLegacyCasts(unique_ptr &expr); + void BindLegacyCast(unique_ptr &expr); + private: // Only for WAL replay. optional_ptr table; optional_ptr info; + //! The keys being bound, set while BindIndex or BindCreateIndex binds them + optional_ptr keys; }; } // namespace duckdb 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 59401e69b..a0571d3f8 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp @@ -18,6 +18,7 @@ #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/bignum_stats.hpp" #include "duckdb/storage/statistics/stats_merge_type.hpp" namespace duckdb { @@ -44,7 +45,8 @@ enum class StatisticsType : uint8_t { BASE_STATS, ARRAY_STATS, GEOMETRY_STATS, - VARIANT_STATS + VARIANT_STATS, + BIGNUM_STATS }; struct ExtraStatsData { @@ -70,6 +72,7 @@ class BaseStatistics { friend struct ArrayStats; friend struct GeometryStats; friend struct VariantStats; + friend struct BignumStats; public: DUCKDB_API ~BaseStatistics(); @@ -190,6 +193,8 @@ class BaseStatistics { GeometryStatsData geometry_data; //! Variant stats data, for variant stats VariantStatsData variant_data; + //! Bignum stats data, for values stored as BIGNUM blobs (decimals wider than 38 digits) + BignumStatsData bignum_data; } stats_union; //! Extra stats data, used for e.g. string data if required unique_ptr extra_data; diff --git a/src/duckdb/src/include/duckdb/storage/statistics/bignum_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/bignum_stats.hpp new file mode 100644 index 000000000..f30af7e10 --- /dev/null +++ b/src/duckdb/src/include/duckdb/storage/statistics/bignum_stats.hpp @@ -0,0 +1,94 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/storage/statistics/bignum_stats.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/array_ptr.hpp" +#include "duckdb/common/enums/expression_type.hpp" +#include "duckdb/common/enums/filter_propagate_result.hpp" +#include "duckdb/common/types/string_type.hpp" +#include "duckdb/common/types/value.hpp" + +namespace duckdb { +class BaseStatistics; +struct SelectionVector; +class Vector; +class Serializer; +class Deserializer; + +//! Statistics of values stored as BIGNUM blobs (decimals wider than 38 digits). The byte order of the BIGNUM encoding +//! is the numeric order, so the bounds are blobs compared bytewise. A bound keeps at most MAX_BOUND_SIZE bytes: a +//! longer blob is cut after the header and the first magnitude bytes, which makes the bound inexact. The bytes a cut +//! min bound omits read as 0x00 and those of a cut max bound as 0xFF, so a cut min is below the value it was cut from +//! and a cut max above it: the bounds always enclose every value, they are only not attained when inexact. +struct BignumStatsData { + //! The magnitude bytes a bound keeps (256 bits): decimals of up to 77 digits keep exact bounds + static constexpr uint32_t MAX_BOUND_DATA_BYTES = 32; + + //! Whether the min/max are known - unknown bounds cannot prune anything + bool has_min; + bool has_max; + //! Whether the bound is the exact min/max of the values, false when it was cut + bool min_exact; + bool max_exact; + //! The minimum and maximum bound - empty (zero bytes) while no value has been seen + string_t min; + string_t max; +}; + +struct BignumStats { + //! Unknown statistics - the bounds are not known + DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type); + //! Empty statistics - the bounds are known, no value has been seen yet + DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type); + + //! Whether the stats have a known min and max that cover at least one value + DUCKDB_API static bool HasMinMax(const BaseStatistics &stats); + //! Whether the min/max is attained by a value, i.e. was not cut to the bound size + DUCKDB_API static bool MinIsExact(const BaseStatistics &stats); + DUCKDB_API static bool MaxIsExact(const BaseStatistics &stats); + //! The min/max bound as a value of the type of the statistics - throws if there is none + DUCKDB_API static Value Min(const BaseStatistics &stats); + DUCKDB_API static Value Max(const BaseStatistics &stats); + //! The min/max bound as a complete BIGNUM blob (a cut bound is padded) - only valid if HasMinMax + DUCKDB_API static string MinBlob(const BaseStatistics &stats); + DUCKDB_API static string MaxBlob(const BaseStatistics &stats); + //! Sets the min/max to a value of the type of the statistics (a NULL value makes the bound unknown) + DUCKDB_API static void SetMin(BaseStatistics &stats, const Value &val); + DUCKDB_API static void SetMax(BaseStatistics &stats, const Value &val); + //! Sets the min/max to a value, which is cut when it is longer than a bound + DUCKDB_API static void SetMin(BaseStatistics &stats, string_t blob); + DUCKDB_API static void SetMax(BaseStatistics &stats, string_t blob); + + //! Extends the bounds with a value + DUCKDB_API static void Update(BaseStatistics &stats, string_t blob); + DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other); + //! Merges exact bounds (empty when no value was seen), as collected by a StatsWriter + DUCKDB_API static void Merge(BaseStatistics &stats, string_t min, string_t max); + DUCKDB_API static void Copy(BaseStatistics &stats, const BaseStatistics &other); + + //! Whether a comparison with the constants can be satisfied by values within the bounds + DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type, + array_ptr constants); + + DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); + DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &stats); + + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static void Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, + idx_t count); + +private: + static BignumStatsData &GetDataUnsafe(BaseStatistics &stats); + static const BignumStatsData &GetDataUnsafe(const BaseStatistics &stats); + //! Stores a copy of the blob in the statistics, cut to the bound size, and returns a reference to it + static string_t AssignBound(BaseStatistics &stats, string_t blob, bool is_min, bool &exact); + static void MergeBound(BaseStatistics &stats, string_t blob, bool exact, bool is_min); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp b/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp index d4be2a15b..2970dc18e 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp @@ -131,7 +131,8 @@ struct StatsWriter : public BaseStatsWriter { friend struct StringStats; explicit StatsWriter(const LogicalType &type) - : is_varchar(type.id() == LogicalTypeId::VARCHAR), is_geometry(type.id() == LogicalTypeId::GEOMETRY) { + : is_varchar(type.id() == LogicalTypeId::VARCHAR), is_geometry(type.id() == LogicalTypeId::GEOMETRY), + is_bignum(BaseStatistics::GetStatsType(type) == StatisticsType::BIGNUM_STATS) { Clear(); } @@ -139,6 +140,9 @@ struct StatsWriter : public BaseStatsWriter { ClearBase(); if (is_geometry) { geometry_stats.SetEmpty(); + } else if (is_bignum) { + bignum_min.clear(); + bignum_max.clear(); } else { is_set = false; min_size = 0; @@ -156,6 +160,10 @@ struct StatsWriter : public BaseStatsWriter { geometry_stats.Update(value); return; } + if (is_bignum) { + UpdateBignum(value); + return; + } auto data = const_data_ptr_cast(value.GetData()); auto size = value.GetSize(); #ifdef DUCKDB_DEBUG_NO_INLINE @@ -233,18 +241,34 @@ struct StatsWriter : public BaseStatsWriter { return; } SetHasValid(); - total_string_length += value.GetSize(); + if (!is_bignum) { + total_string_length += value.GetSize(); + } } void Merge(BaseStatistics &other) const { MergeBase(other); if (is_geometry) { GeometryStats::GetDataUnsafe(other).Merge(geometry_stats); + } else if (is_bignum) { + BignumStats::Merge(other, string_t(bignum_min), string_t(bignum_max)); } else { StringStats::Merge(other, *this); } } +private: + //! The byte order of the BIGNUM encoding is the numeric order; the exact min/max blobs are kept while a vector is + //! written, the statistics they are merged into cut them to the bound size + inline void UpdateBignum(const string_t &value) { + if (bignum_min.empty() || LessThan::Operation(value, string_t(bignum_min))) { + bignum_min.assign(value.GetData(), value.GetSize()); + } + if (bignum_max.empty() || GreaterThan::Operation(value, string_t(bignum_max))) { + bignum_max.assign(value.GetData(), value.GetSize()); + } + } + private: data_t min[StringStatsData::CURRENT_MAX_STRING_MINMAX_SIZE]; data_t max[StringStatsData::CURRENT_MAX_STRING_MINMAX_SIZE]; @@ -257,7 +281,10 @@ struct StatsWriter : public BaseStatsWriter { idx_t total_string_length; bool is_varchar; bool is_geometry; + bool is_bignum; GeometryStatsData geometry_stats; + string bignum_min; + string bignum_max; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp index 16f6f9c3f..09489b653 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp @@ -19,6 +19,8 @@ namespace duckdb { struct AttachOptions; class ActiveCheckpointWrapper; +class ParsedExpression; +class QueryNode; class BlockManager; class Catalog; class CheckpointWriter; @@ -140,6 +142,24 @@ class StorageManager { D_ASSERT(HasStorageVersion()); return StorageVersionInfo::GetStorageVersionString(storage_version); } + //! Why a column type cannot be stored at the storage version of this database, empty when it can + string GetUnsupportedTypeReason(const LogicalType &type) const; + //! Why something that needs the required storage version is not supported by this database, which is prior to it + string GetUnsupportedPriorToVersionReason(const string &what, StorageVersion required) const; + //! Throws when a column type cannot be stored at the storage version of this database + void CheckTypeIsSupported(const LogicalType &type) const; + //! Whether a type holds a DECIMAL stored as a BIGNUM blob, the argument types of aggregate states included + static bool ContainsWideDecimal(const LogicalType &type); + //! Why a type written to the catalog holds a DECIMAL wider than this storage version stores, empty when it does + //! not; the subject names what is stored (columns, index keys) + string GetUnsupportedDecimalWidthReason(const LogicalType &type, const string &subject = "columns") const; + //! Throws when a type written to the catalog holds a DECIMAL wider than this storage version stores + void CheckDecimalWidthIsSupported(const LogicalType &type) const; + //! Throws when a stored expression casts to a DECIMAL wider than this storage version stores: below v2.0.0 a CAST + //! serializes its target as a LogicalType, which the engines of that version read as a fixed-size decimal + void CheckExpressionDecimalsAreSupported(const ParsedExpression &expression) const; + //! The same check over every expression of a stored query (a view or a table macro) + void CheckQueryDecimalsAreSupported(QueryNode &node) const; bool CompressionIsEnabled() const { return storage_options.compress_in_memory == CompressInMemory::COMPRESS; } diff --git a/src/duckdb/src/include/duckdb/storage/table/data_table_info.hpp b/src/duckdb/src/include/duckdb/storage/table/data_table_info.hpp index 9331af9d9..cb09a48d4 100644 --- a/src/duckdb/src/include/duckdb/storage/table/data_table_info.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/data_table_info.hpp @@ -26,8 +26,10 @@ struct DataTableInfo { Identifier table); //! Bind unknown indexes throwing an exception if binding fails. - //! Only binds the specified index type, or all if no type is specified. - void BindIndexes(ClientContext &context, const optional &index_type = {}); + //! Only binds the specified index type, or all if no type is specified. With skip_mismatched_keys, an index + //! whose stored keys bind to other types here is left unbound instead of refused. + void BindIndexes(ClientContext &context, const optional &index_type = {}, + bool skip_mismatched_keys = false); //! Whether or not the table is temporary bool IsTemporary() const; diff --git a/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp b/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp index fe9783e5b..ca481ca90 100644 --- a/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp @@ -141,8 +141,9 @@ class IndexEntry : public enable_shared_from_this { bool HasBufferedReplays() const; //! Destroys the physical index. void Retire(); - //! Binds the unbound physical index without replacing it. - unique_ptr Bind(IndexBinder &binder, const vector &table_types); + //! Binds the unbound physical index without replacing it (nullptr for skipped mismatched keys). + unique_ptr Bind(IndexBinder &binder, const vector &table_types, + bool skip_mismatched_keys = false); //! Replaces the unbound physical index with its bound representation. void CommitBind(unique_ptr bound_index); //! Verifies that rows can be appended to the bound physical index. diff --git a/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp b/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp index 92d22a4ca..d42458803 100644 --- a/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp @@ -64,8 +64,10 @@ class TableIndexList { //! Returns the entry matching the index OID. shared_ptr FindEntry(const IndexEntry &index) const; shared_ptr FindEntry(idx_t index_oid) const; - //! Binds unbound indexes possibly present after loading an extension. - void Bind(ClientContext &context, DataTableInfo &table_info, const optional &index_type = {}); + //! Binds unbound indexes possibly present after loading an extension. An index whose stored keys bind to other + //! types here is refused, or left unbound when skip_mismatched_keys is set, for a read that can do without it. + void Bind(ClientContext &context, DataTableInfo &table_info, const optional &index_type = {}, + bool skip_mismatched_keys = false); //! Returns true, if there are no index entries. bool Empty() const { return Count() == 0; diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index 853ec5d32..c72c236a0 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -9920,7 +9920,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_lo * out_name receives a borrowed view of the parameter name — a STRUCT field name, a UNION member name, "collation" — or * 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 + * value_get_type), DECIMAL width and scale as UINTEGER, 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: @@ -15732,7 +15732,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a byte string: a BLOB, or the storage bytes of a BIT or BIGNUM. + * Returns the value as a byte string: a BLOB, or the storage bytes of a BIT, a BIGNUM, or a DECIMAL wider than 38 + * digits (the BIGNUM storage of its unscaled value, for bignum_decode). * * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return @@ -16049,7 +16050,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle val * The integer is the value scaled by 10^scale — the dual of value_create_decimal — widened to 128 bits from whatever * storage tier the width selects. The integer getters convert, so a DECIMAL read through value_get_bigint is its * numeric value with the fraction dropped; this one always reports storage instead, together with the scale needed to - * interpret it. A value of any other type id, and a NULL value, return ERROR_INPUT_INVALID. + * interpret it. A value of any other type id, and a NULL value, return ERROR_INPUT_INVALID. A DECIMAL wider than 38 + * digits (stored as BIGNUM) is reported the same way as long as its backing integer fits in 128 bits; beyond that the + * call fails and the exact storage is available through value_get_blob and bignum_decode, or through value_cast. * * history: * - unstable: v2.0.0 @@ -16673,17 +16676,19 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_h /*! * Creates a DECIMAL value from its backing integer. * - * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be 1..38; scale - * is the number of digits after the point and must not exceed width. Violating either returns ERROR_INPUT_INVALID, as - * does a value too wide for the storage tier the width selects. The value itself is not range-checked against the - * width; value_cast is the validating path. + * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be 1..255, the + * range of the uint8_t parameter; scale is the number of digits after the point and must not exceed width. Violating + * either returns ERROR_INPUT_INVALID, as does a value too wide for the storage tier the width selects. Widths above 38 + * build a wide decimal stored as BIGNUM, for which the 128-bit backing integer always fits. The value itself is not + * range-checked against the width; value_cast is the validating path, and the one that reaches decimals wider than 255 + * digits. * * history: * - unstable: v2.0.0 * * @param factory The factory to create with. * @param in_value The backing integer, scaled by 10^scale. - * @param width Total digit count, 1..38. + * @param width Total digit count, 1..255 (the range of the uint8_t). * @param scale Digits after the decimal point; must not exceed width. * @param out_value Receives the new DECIMAL value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. diff --git a/src/duckdb/src/main/appender.cpp b/src/duckdb/src/main/appender.cpp index 41401f1fe..7b3c29140 100644 --- a/src/duckdb/src/main/appender.cpp +++ b/src/duckdb/src/main/appender.cpp @@ -5,6 +5,8 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/operator/decimal_cast_operators.hpp" +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/operator/string_cast.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" @@ -101,11 +103,17 @@ void BaseAppender::AppendDecimalValueInternal(Vector &col, SRC input) { auto scale = DecimalType::GetScale(type); CastParameters parameters; auto &result = FlatVector::GetDataMutable(col)[chunk.size()]; - TryCastToDecimal::Operation(input, result, parameters, width, scale); + VectorDecimalCast::Operation(input, result, col, parameters, width, scale); return; } case AppenderType::PHYSICAL: { - AppendValueInternal(col, input); + if constexpr (std::is_same::value) { + // the bignum_t tier has no physical representation among the appended types + throw InternalException("Physical appends are not supported for DECIMAL types wider than %d digits", + Decimal::MAX_WIDTH_INT128); + } else { + AppendValueInternal(col, input); + } return; } default: @@ -173,6 +181,9 @@ void BaseAppender::AppendValueInternal(T input) { case PhysicalType::INT128: AppendDecimalValueInternal(col, input); break; + case PhysicalType::VARCHAR: + AppendDecimalValueInternal(col, input); + break; default: InternalException::Throw("Internal type not recognized for Decimal"); } 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 d76f0bce3..ab30ada3e 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 @@ -1,5 +1,6 @@ #include "duckdb/main/capi/cast/from_decimal.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/decimal_helper.hpp" namespace duckdb { @@ -30,6 +31,15 @@ bool CastDecimalCInternal(duckdb_result *source, duckdb_string &result, idx_t co case duckdb::PhysicalType::INT128: result_string = duckdb::StringCastFromDecimal::Operation(source_value, width, scale, heap); break; + case duckdb::PhysicalType::VARCHAR: { + // the materialized duckdb_decimal only holds 128-bit values, so format the original value instead + auto value = query_result->Collection().GetValue(col, row); + if (value.IsNull()) { + return false; + } + result_string = heap.AddString(value.ToString()); + break; + } default: InternalException::Throw("Unimplemented internal type for decimal"); } @@ -110,6 +120,11 @@ bool CastDecimalCInternal(duckdb_result *source, duckdb_decimal &result, idx_t c auto result_data = (duckdb::DuckDBResultData *)source->internal_data; uint32_t width, scale; result_data->result->GetTypes()[col].GetDecimalProperties(width, scale); + if (width > duckdb::NumericLimits::Maximum()) { + // a duckdb_decimal holds widths up to 255 + result = FetchDefaultValue::Operation(); + return false; + } result.width = duckdb::NumericCast(width); result.scale = duckdb::NumericCast(scale); auto source_address = UnsafeFetchPtr(source, col, row); 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 d63f537b1..23dbc928d 100644 --- a/src/duckdb/src/main/capi/v1/duckdb_value-c.cpp +++ b/src/duckdb/src/main/capi/v1/duckdb_value-c.cpp @@ -7,6 +7,8 @@ #include "duckdb/common/types/value.hpp" #include "duckdb/common/types/bignum.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/decimal_helper.hpp" +#include "duckdb/main/capi/cast/utils.hpp" #include "duckdb/main/capi/capi_internal.hpp" using duckdb::LogicalTypeId; @@ -165,7 +167,19 @@ 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); + if (v.IsNull() || width > duckdb::NumericLimits::Maximum()) { + // a duckdb_decimal holds widths up to 255 + return {0, 0, {0, 0}}; + } + duckdb::hugeint_t hugeint; + if (type.InternalType() == duckdb::PhysicalType::VARCHAR) { + // the BIGNUM blob of a wide decimal is only representable if it fits in 128 bits + if (!duckdb::DecimalHelper::TryToHugeint(v.GetValueUnsafe(), hugeint)) { + return duckdb::FetchDefaultValue::Operation(); + } + } else { + hugeint = duckdb::IntegralValue::Get(v); + } return {duckdb::NumericCast(width), duckdb::NumericCast(scale), {hugeint.lower, hugeint.upper}}; } duckdb_value duckdb_create_float(float input) { diff --git a/src/duckdb/src/main/capi/v1/hugeint-c.cpp b/src/duckdb/src/main/capi/v1/hugeint-c.cpp index 5ac7120f1..46312cdc8 100644 --- a/src/duckdb/src/main/capi/v1/hugeint-c.cpp +++ b/src/duckdb/src/main/capi/v1/hugeint-c.cpp @@ -1,7 +1,10 @@ #include "duckdb/main/capi/capi_internal.hpp" #include "duckdb/common/types/hugeint.hpp" + +#include #include "duckdb/common/types/uhugeint.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/operator/decimal_cast_operators.hpp" #include "duckdb/main/capi/cast/utils.hpp" #include "duckdb/main/capi/cast/to_decimal.hpp" @@ -40,9 +43,19 @@ static duckdb_decimal to_decimal_cast(double val, uint8_t width, uint8_t scale) } duckdb_decimal duckdb_double_to_decimal(double val, uint8_t width, uint8_t scale) { - if (scale > width || width > duckdb::Decimal::MAX_WIDTH_INT128) { + if (!duckdb::Decimal::IsValidWidthScale(width, scale)) { return duckdb::FetchDefaultValue::Operation(); } + if (duckdb::Decimal::IsWide(width)) { + // wide decimals convert exactly and are only representable if they fit in 128 bits + std::string blob; + duckdb::hugeint_t hugeint; + if (!duckdb::DecimalHelper::TryFromDouble(val, width, scale, blob) || + !duckdb::DecimalHelper::TryToHugeint(duckdb::bignum_t(duckdb::string_t(blob)), hugeint)) { + return duckdb::FetchDefaultValue::Operation(); + } + return {width, scale, {hugeint.lower, hugeint.upper}}; + } return to_decimal_cast(val, width, scale); } @@ -77,6 +90,10 @@ double duckdb_decimal_to_double(duckdb_decimal val) { hugeint_t value; value.lower = val.value.lower; value.upper = val.value.upper; + if (value == duckdb::NumericLimits::Minimum()) { + // a wide decimal can hold -2^127, which the signed conversion cannot negate + return -std::ldexp(1.0, 127) / std::pow(10.0, val.scale); + } duckdb::CastParameters parameters; duckdb::TryCastFromDecimal::Operation(value, result, parameters, val.width, val.scale); return result; 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 540e3ba3b..21c09dede 100644 --- a/src/duckdb/src/main/capi/v1/logical_types-c.cpp +++ b/src/duckdb/src/main/capi/v1/logical_types-c.cpp @@ -193,12 +193,17 @@ void duckdb_destroy_logical_type(duckdb_logical_type *type) { } } +//! The uint8_t of the C API holds widths up to 255, wider decimals report 0 +static uint8_t DecimalPropertyToC(uint32_t value) { + return value > duckdb::NumericLimits::Maximum() ? 0 : static_cast(value); +} + uint8_t duckdb_decimal_width(duckdb_logical_type type) { if (!AssertLogicalTypeId(type, duckdb::LogicalTypeId::DECIMAL)) { return 0; } auto &logical_type = *(reinterpret_cast(type)); - return duckdb::NumericCast(duckdb::DecimalType::GetWidth(logical_type)); + return DecimalPropertyToC(duckdb::DecimalType::GetWidth(logical_type)); } uint8_t duckdb_decimal_scale(duckdb_logical_type type) { @@ -206,7 +211,10 @@ uint8_t duckdb_decimal_scale(duckdb_logical_type type) { return 0; } auto &logical_type = *(reinterpret_cast(type)); - return duckdb::NumericCast(duckdb::DecimalType::GetScale(logical_type)); + if (duckdb::DecimalType::GetWidth(logical_type) > duckdb::NumericLimits::Maximum()) { + return 0; + } + return DecimalPropertyToC(duckdb::DecimalType::GetScale(logical_type)); } duckdb_type duckdb_decimal_internal_type(duckdb_logical_type type) { @@ -223,6 +231,9 @@ duckdb_type duckdb_decimal_internal_type(duckdb_logical_type type) { return DUCKDB_TYPE_BIGINT; case duckdb::PhysicalType::INT128: return DUCKDB_TYPE_HUGEINT; + case duckdb::PhysicalType::VARCHAR: + // decimals wider than 38 digits store their unscaled value as BIGNUM storage + return DUCKDB_TYPE_BIGNUM; default: return DUCKDB_TYPE_INVALID; } diff --git a/src/duckdb/src/main/capi/v1/result-c.cpp b/src/duckdb/src/main/capi/v1/result-c.cpp index 9ccc60f2a..f67054694 100644 --- a/src/duckdb/src/main/capi/v1/result-c.cpp +++ b/src/duckdb/src/main/capi/v1/result-c.cpp @@ -1,6 +1,7 @@ #include "duckdb/main/capi/capi_internal.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/allocator.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/vector/vector_iterator.hpp" namespace duckdb { @@ -130,6 +131,23 @@ struct CDecimalConverter : public CBaseConverter { } }; +//! The deprecated duckdb_decimal only holds 128-bit values, wider BIGNUM-backed decimals report the default of zero +struct CWideDecimalConverter : public CBaseConverter { + template + static DST Convert(SRC input) { + duckdb_hugeint result; + hugeint_t value; + if (!DecimalHelper::TryToHugeint(input, value)) { + result.lower = 0; + result.upper = 0; + return result; + } + result.lower = value.lower; + result.upper = value.upper; + return result; + } +}; + template void WriteData(duckdb_column *column, ColumnDataCollection &source, const vector &column_ids) { idx_t row = 0; @@ -290,6 +308,10 @@ duckdb_state deprecated_duckdb_translate_column(QueryResult &result, duckdb_colu WriteData(column, collection, column_ids); break; } + case PhysicalType::VARCHAR: { + WriteData(column, collection, column_ids); + break; + } default: throw std::runtime_error("Unsupported physical type for Decimal" + TypeIdToString(result.GetTypes()[col].InternalType())); 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 c237dd766..9baa2b367 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 @@ -181,8 +181,7 @@ idx_t TypeParamCount(const LogicalType &type) { Value TypeParamValue(const LogicalType &type, idx_t index, std::string_view &out_name) { switch (type.id()) { case LogicalTypeId::DECIMAL: - return index == 0 ? Value::UTINYINT(NumericCast(DecimalType::GetWidth(type))) - : Value::UTINYINT(NumericCast(DecimalType::GetScale(type))); + return index == 0 ? Value::UINTEGER(DecimalType::GetWidth(type)) : Value::UINTEGER(DecimalType::GetScale(type)); case LogicalTypeId::LIST: return Value::TYPE(ListType::GetChildType(type)); case LogicalTypeId::ARRAY: 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 fc059b7bd..a0cec44f9 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/hugeint.hpp" #include "duckdb/common/types/bignum.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/interval.hpp" #include "duckdb/common/types/uuid.hpp" #include "duckdb/common/types/value.hpp" @@ -105,18 +106,19 @@ LogicalType RequireValueType(duckdb_v2_logical_type_handle type) { // The DECIMAL storage tier follows from the width, and the engine's hugeint // constructor covers only the widest one, so the narrower tiers go through the // int64 form. Width and scale are gated here: an out-of-range pair would build -// a broken type rather than a bad value. +// a broken type rather than a bad value. The uint8_t parameters reach widths +// up to 255; wider decimals are built through value_cast. Value BuildDecimal(const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t scale) { - if (width < 1 || width > Decimal::MAX_WIDTH_DECIMAL) { - throw InvalidInputException(": DECIMAL width must be between 1 and " + - std::to_string(Decimal::MAX_WIDTH_DECIMAL)); + if (width < 1) { + throw InvalidInputException(": DECIMAL width must be at least 1"); } if (scale > width) { throw InvalidInputException(": DECIMAL scale cannot exceed the width"); } auto value = Convert(in_value); auto type = LogicalType::DECIMAL(width, scale); - if (type.InternalType() == PhysicalType::INT128) { + if (type.InternalType() == PhysicalType::INT128 || type.InternalType() == PhysicalType::VARCHAR) { + // the hugeint constructor also builds the BIGNUM storage of a wide decimal (width > 38) return Value::DECIMAL(value, width, scale); } int64_t narrow = 0; @@ -294,9 +296,12 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, const cha // The byte-string reader: BLOB plus the kinds whose payload is opaque // storage bytes (BIT's padding header + data, BIGNUM's bignum_decode // input). VARCHAR is text, and has its own getter. + // a DECIMAL wider than 38 digits also stores its exact unscaled value as BIGNUM bytes auto id = v.type().id(); + const bool wide_decimal = + id == duckdb::LogicalTypeId::DECIMAL && v.type().InternalType() == duckdb::PhysicalType::VARCHAR; if (id != duckdb::LogicalTypeId::BLOB && id != duckdb::LogicalTypeId::BIT && - id != duckdb::LogicalTypeId::BIGNUM) { + id != duckdb::LogicalTypeId::BIGNUM && !wide_decimal) { throw duckdb::InvalidInputException("duckdb_v2_value_get_blob: value is not of the expected type"); } if (v.IsNull()) { @@ -341,6 +346,12 @@ 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(); + if (duckdb::DecimalType::GetWidth(type) > duckdb::NumericLimits::Maximum()) { + throw duckdb::OutOfRangeException( + "duckdb_v2_value_get_decimal: the width of %s does not fit the uint8_t of the API; read its storage " + "with value_get_blob and bignum_decode, or convert it with value_cast", + type.ToString()); + } *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 @@ -355,6 +366,18 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb case duckdb::PhysicalType::INT64: *out = Convert(duckdb::hugeint_t(v.GetValueUnsafe())); break; + case duckdb::PhysicalType::VARCHAR: { + // the BIGNUM storage of a wide decimal may not fit in 128 bits + duckdb::hugeint_t unscaled; + if (!duckdb::DecimalHelper::TryToHugeint(v.GetValueUnsafe(), + unscaled)) { + throw duckdb::OutOfRangeException( + "duckdb_v2_value_get_decimal: the value does not fit in 128 bits; read its storage with " + "value_get_blob and bignum_decode, or convert it with value_cast"); + } + *out = Convert(unscaled); + break; + } default: *out = Convert(v.GetValueUnsafe()); break; diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index 897c0305f..5ab0b5cd7 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -224,6 +224,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_GLOBAL(LoggingSink), DUCKDB_GLOBAL(LoggingStorage), DUCKDB_SETTING(MatchRecognizeMaxStatesSetting), + DUCKDB_SETTING(MaxDecimalWidthSetting), DUCKDB_SETTING(MaxExecutionTimeSetting), DUCKDB_SETTING(MaxExpressionDepthSetting), DUCKDB_GLOBAL(MaxMemorySetting), diff --git a/src/duckdb/src/main/extension/extension_helper.cpp b/src/duckdb/src/main/extension/extension_helper.cpp index bb64c4e88..45f24d1b3 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -94,6 +94,8 @@ static const DefaultExtension internal_extensions[] = { {"lance", "Adds support for querying Lance datasets"}, {"avro", "Adds support for reading Avro files"}, {"unity_catalog", "Adds support for connecting to Unity Catalog"}, + {"glue", "Adds support for the AWS Glue Data Catalog"}, + {"legacy_parser", "Adds the SQL parser DuckDB used up to 1.5"}, {nullptr, nullptr}}; idx_t ExtensionHelper::DefaultExtensionCount() { diff --git a/src/duckdb/src/main/extension/extension_repository_manager.cpp b/src/duckdb/src/main/extension/extension_repository_manager.cpp index 3aec461a1..1c44ee509 100644 --- a/src/duckdb/src/main/extension/extension_repository_manager.cpp +++ b/src/duckdb/src/main/extension/extension_repository_manager.cpp @@ -15,6 +15,7 @@ #include "mbedtls_wrapper.hpp" #include "yyjson.hpp" +#include #include using namespace duckdb_yyjson; // NOLINT @@ -670,6 +671,47 @@ ExtensionRepository ExtensionRepositoryManager::ReadRepository(FileSystem &fs, c return result; } +//! How a stored repository differs from what a plain CREATE asks for, or empty when the request describes the stored +//! repository: a repeated CREATE then passes without fetching anything. Without a prefix the request only names a host, +//! so it describes the stored repository when that was resolved from the host; with a prefix, the prefix must match +//! and so must the keys when the request gives any (keys that were not given were fetched from the prefix, and are not +//! fetched again to compare). Nothing here reaches the network: what the host or the prefix serve today is checked +//! only by OR REPLACE +static string DescribeDifference(const ExtensionRepository &stored, const ExtensionRepository &requested, + bool from_host) { + if (from_host) { + if (!stored.host.empty()) { + return string(); + } + return StringUtil::Format("added with prefix '%s' rather than resolved from its host", stored.path); + } + if (!stored.host.empty()) { + return StringUtil::Format("resolved from its host (prefix '%s') rather than added with a prefix", stored.path); + } + auto requested_path = requested.path; + StringUtil::RTrim(requested_path, "/"); + auto stored_path = stored.path; + StringUtil::RTrim(stored_path, "/"); + if (requested_path != stored_path) { + return StringUtil::Format("with prefix '%s'", stored.path); + } + if (requested.public_keys.empty()) { + return string(); + } + auto requested_keys = ExtensionRepositoryManager::NormalizePublicKeys(requested.public_keys); + std::sort(requested_keys.begin(), requested_keys.end()); + auto stored_keys = stored.public_keys; + std::sort(stored_keys.begin(), stored_keys.end()); + if (requested_keys != stored_keys) { + vector fingerprints; + for (auto &key : stored.public_keys) { + fingerprints.push_back(ExtensionRepositoryManager::GetPublicKeyFingerprint(key)); + } + return StringUtil::Format("with other public keys (%s)", StringUtil::Join(fingerprints, ", ")); + } + return string(); +} + ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstance &db, FileSystem &fs, optional_ptr context, const ExtensionRepository &requested, @@ -677,7 +719,9 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc // no prefix: the name is the host, and the host names the prefix. The host is derived here, never taken from the // caller, so a stored host always means the repository was resolved from it bool from_host = requested.path.empty(); - CheckCanCreate(db, from_host); + // a locked configuration freezes the trust store, whatever the statement; the opt-in is checked once it is known + // that the statement would add something (see below) + CheckNotLocked(db); auto name = NormalizeRepositoryName(requested.name); if (!ExtensionRepository::TryGetRepositoryUrl(name).empty()) { @@ -694,21 +738,32 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc name); } - // the conflict is decided before anything is fetched: IF NOT EXISTS returns the stored definition, a plain CREATE - // reports the duplicate, and only OR REPLACE goes on to resolve - keeping the old definition if that fails + // the conflict is decided before anything is fetched, and before the opt-in: IF NOT EXISTS returns the stored + // definition, a plain CREATE returns it too when it asks for the same repository and reports the difference + // otherwise, and only OR REPLACE goes on to resolve - keeping the old definition if that fails. Returning what is + // stored adds no trust, so it needs no opt-in, and a difference is a difference whatever the access level auto directory = GetRepositoryDirectory(db, fs); auto file_path = fs.JoinPath(directory, name + FILE_EXTENSION); if (fs.FileExists(file_path)) { switch (on_conflict) { - case OnCreateConflict::ERROR_ON_CONFLICT: - throw CatalogException( - "Extension repository with name \"%s\" already exists!\nUse CREATE OR REPLACE to overwrite it", name); + case OnCreateConflict::ERROR_ON_CONFLICT: { + auto stored = ReadRepository(fs, file_path); + auto difference = DescribeDifference(stored, requested, from_host); + if (difference.empty()) { + return stored; + } + throw CatalogException("Extension repository with name \"%s\" already exists, %s\nUse CREATE OR REPLACE to " + "overwrite it", + name, difference); + } case OnCreateConflict::IGNORE_ON_CONFLICT: return ReadRepository(fs, file_path); default: break; } } + // from here on something is added: the opt-in applies + CheckCanCreate(db, from_host); ExtensionRepository repository(name, requested.path, requested.public_keys); vector public_keys; diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index 85d60f2ff..60101b6f1 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -9,6 +9,7 @@ // //===----------------------------------------------------------------------===// +#include "duckdb/common/types/decimal.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/common/algorithm.hpp" @@ -1566,7 +1567,7 @@ void SchemaSetting::ResetLocal(ClientContext &context) { Value SchemaSetting::GetSetting(const ClientContext &context) { auto &client_data = ClientData::Get(context); - return client_data.catalog_search_path->GetDefault().GetSchema(); + return Value(client_data.catalog_search_path->GetDefault().GetSchemaName()); } //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp b/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp index c7eabd99a..2585cea40 100644 --- a/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp +++ b/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/aggregate_function_rewriter.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" #include "duckdb/function/function_binder.hpp" @@ -93,6 +94,11 @@ class AvgRewriteRule : public AggregateRewriteRule { } bool ShouldRewrite(const LogicalAggregate &aggr, Expression &expr) override { + auto &child_type = expr.Cast().GetChildren()[0]->GetReturnType(); + if (child_type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(child_type))) { + // the wide avg divides its exact sum before the result becomes a DOUBLE, SUM / COUNT would overflow it + return false; + } if (aggr.groups.empty()) { return true; } diff --git a/src/duckdb/src/optimizer/partitioned_execution.cpp b/src/duckdb/src/optimizer/partitioned_execution.cpp index d15040a95..390b9ccb7 100644 --- a/src/duckdb/src/optimizer/partitioned_execution.cpp +++ b/src/duckdb/src/optimizer/partitioned_execution.cpp @@ -165,6 +165,8 @@ static bool PartitionedExecutionCanUseStats(const unique_ptr &st switch (stats->GetStatsType()) { case StatisticsType::NUMERIC_STATS: return NumericStats::HasMinMax(*stats); + case StatisticsType::BIGNUM_STATS: + return BignumStats::HasMinMax(*stats); case StatisticsType::STRING_STATS: // Let's not mess with BLOB for now if (stats->GetType() != LogicalType::VARCHAR) { @@ -188,6 +190,10 @@ static bool PartitionedExecutionMinMaxEqual(const BaseStatistics &stats) { min = NumericStats::Min(stats); max = NumericStats::Max(stats); break; + case StatisticsType::BIGNUM_STATS: + min = BignumStats::Min(stats); + max = BignumStats::Max(stats); + break; case StatisticsType::STRING_STATS: min = Value::BLOB_RAW(StringStats::Min(stats)); max = Value::BLOB_RAW(StringStats::Max(stats)); @@ -243,6 +249,10 @@ static void PartitionedExecutionAddStatsNodes(const BaseStatistics &stats, const min = NumericStats::Min(stats); max = NumericStats::Max(stats); break; + case StatisticsType::BIGNUM_STATS: + min = BignumStats::Min(stats); + max = BignumStats::Max(stats); + break; case StatisticsType::STRING_STATS: min = StringStats::Min(stats); max = StringStats::Max(stats); diff --git a/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp index 8c02ad5ff..a4af565f9 100644 --- a/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp @@ -144,7 +144,7 @@ bool RemotePushdownOptimizer::EntryExistsInLocalCatalog(const EntryLookupInfo &l const vector &schema_path) { for (auto &local_entry : pushdown_state.local_catalogs_in_search_path) { // if the name specifies a schema use it, otherwise use the search path schema - vector schema = schema_path.empty() ? vector {local_entry.GetSchema()} : schema_path; + auto schema = schema_path.empty() ? local_entry.GetSchemaPath() : schema_path; if (LookupEntry(local_entry.GetCatalog(), lookup, schema)) { return true; } @@ -724,6 +724,10 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteStatement(CreateStatement auto &schema_info = info.Cast(); target = ResolveDDLTarget(QualifiedName(schema_info.SchemaCatalog(), Identifier(), schema_info.SchemaName()), DDLTarget::NEW_ENTRY, info.type); + if (target.catalog && !target.catalog->SupportsNestedSchemas()) { + target.catalog->CheckNestedSchemaSupport(binder.ResolveCatalog(binder.context, info.GetQualifiedName()), + info.type); + } } else { target = ResolveDDLTarget(info.GetQualifiedName(), DDLTarget::NEW_ENTRY, info.type); } @@ -748,6 +752,10 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteStatement(DropStatement &s return CatalogPushdownResult::Unknown(); } auto target = ResolveDDLTarget(info.GetQualifiedName(), DDLTarget::EXISTING_ENTRY, info.type); + if (info.type == CatalogType::SCHEMA_ENTRY && target.catalog && !target.catalog->SupportsNestedSchemas()) { + target.catalog->CheckNestedSchemaSupport(binder.ResolveCatalog(binder.context, info.GetQualifiedName()), + info.type); + } return VerifyStatementSupport(statement, std::move(target)); } @@ -878,7 +886,7 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteTableFunctionOnly(TableFun FindRemoteCatalogsInSearchPath(); EntryLookupInfo func_lookup(CatalogType::TABLE_FUNCTION_ENTRY, QualifiedName(func_expr.FunctionName())); for (auto &local_entry : pushdown_state.local_catalogs_in_search_path) { - vector schema = schema_path.empty() ? vector {local_entry.GetSchema()} : schema_path; + auto schema = schema_path.empty() ? local_entry.GetSchemaPath() : schema_path; auto entry = LookupEntry(local_entry.GetCatalog(), func_lookup, schema); if (entry && entry->type == CatalogType::TABLE_FUNCTION_ENTRY) { auto &tf_entry = entry->Cast(); diff --git a/src/duckdb/src/optimizer/rule/move_constants.cpp b/src/duckdb/src/optimizer/rule/move_constants.cpp index 857e0e6ac..81f78e317 100644 --- a/src/duckdb/src/optimizer/rule/move_constants.cpp +++ b/src/duckdb/src/optimizer/rule/move_constants.cpp @@ -1,7 +1,9 @@ #include "duckdb/optimizer/rule/move_constants.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/common/value_operations/value_operations.hpp" #include "duckdb/function/function_binder.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" @@ -314,6 +316,14 @@ unique_ptr MoveUnaryMinusRule::Apply(LogicalOperator &op, vector(); + const BignumIntermediate intermediate(unscaled); + StringHeap heap; + auto negated = bignum_t(intermediate.Negate(heap)); + new_constant = + Value::DECIMAL(negated, DecimalType::GetWidth(constant_type), DecimalType::GetScale(constant_type)); } else if (constant_type.id() == LogicalTypeId::DECIMAL) { // negate the unscaled integer and reconstruct with the same width/scale hugeint_t negated_value; diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp index 64ef44f0b..c6583e503 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp @@ -118,6 +118,17 @@ FilterPropagateResult StatisticsPropagator::PropagateComparison(const BaseStatis return PropagateValueComparison(lmin, lmax, rmin, rmax, comparison, has_null); } + if (lstats.GetStatsType() == StatisticsType::BIGNUM_STATS && + rstats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + if (lstats.GetType() != rstats.GetType() || !BignumStats::HasMinMax(lstats) || + !BignumStats::HasMinMax(rstats)) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + bool has_null = lstats.CanHaveNull() || rstats.CanHaveNull(); + return PropagateValueComparison(BignumStats::Min(lstats), BignumStats::Max(lstats), BignumStats::Min(rstats), + BignumStats::Max(rstats), comparison, has_null); + } + switch (lstats.GetType().InternalType()) { case PhysicalType::BOOL: case PhysicalType::UINT8: diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp index 8b36f8831..927958946 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp @@ -129,7 +129,8 @@ unique_ptr StatisticsPropagator::PropagateMonotoneBounds(ClientC if (func.Function().GetStability() == FunctionStability::VOLATILE) { return nullptr; } - if (BaseStatistics::GetStatsType(func.GetReturnType()) != StatisticsType::NUMERIC_STATS || + const auto result_stats_type = BaseStatistics::GetStatsType(func.GetReturnType()); + if ((result_stats_type != StatisticsType::NUMERIC_STATS && result_stats_type != StatisticsType::BIGNUM_STATS) || func.GetReturnType().InternalType() == PhysicalType::BOOL) { return nullptr; } @@ -158,11 +159,12 @@ unique_ptr StatisticsPropagator::PropagateMonotoneBounds(ClientC if (cs.CanHaveNull()) { output_can_have_null = true; } - if (cs.GetStatsType() != StatisticsType::NUMERIC_STATS || !NumericStats::HasMinMax(cs)) { + if ((cs.GetStatsType() != StatisticsType::NUMERIC_STATS && cs.GetStatsType() != StatisticsType::BIGNUM_STATS) || + !HasNumericMinMax(cs)) { return nullptr; } - Value lo = NumericStats::Min(cs); - Value hi = NumericStats::Max(cs); + Value lo = NumericMin(cs); + Value hi = NumericMax(cs); if (!IsKnownMonotonic(m)) { return nullptr; @@ -212,9 +214,9 @@ unique_ptr StatisticsPropagator::PropagateMonotoneBounds(ClientC func.Function().GetName()); } - auto result = NumericStats::CreateEmpty(func.GetReturnType()); - NumericStats::SetMin(result, out_lo); - NumericStats::SetMax(result, out_hi); + auto result = BaseStatistics::CreateEmpty(func.GetReturnType()); + SetNumericMin(result, out_lo); + SetNumericMax(result, out_hi); result.Set(StatsInfo::CAN_HAVE_VALID_VALUES); if (output_can_have_null) { diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp index 98e71c566..6bf0c4fca 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp @@ -80,6 +80,8 @@ unique_ptr GetComparator(const Identifier &fun_name) { unique_ptr GetComparator(const Identifier &fun_name, const LogicalType &type) { if (type == LogicalType::VARCHAR) { return GetComparator(fun_name); + } else if (BaseStatistics::GetStatsType(type) == StatisticsType::BIGNUM_STATS) { + return GetComparator(fun_name); } else if (type.IsNumeric() || type.IsTemporal()) { return GetComparator(fun_name); } @@ -140,6 +142,11 @@ bool TryGetValueFromStats(Context &context, const PartitionStatistics &stats, co // TODO: This also returns if an entire row group is null. In that case, we could skip/compare null return false; } + } else if (column_stats->GetStatsType() == StatisticsType::BIGNUM_STATS) { + if (!BignumStats::MinIsExact(*column_stats) || !BignumStats::MaxIsExact(*column_stats)) { + // a cut bound is not attained by a value + return false; + } } else { D_ASSERT(column_stats->GetStatsType() == StatisticsType::STRING_STATS); if (!StringStats::HasMinMax(*column_stats)) { diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp index 7cd786e97..446265b8b 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp @@ -18,6 +18,37 @@ static bool IsCompareDistinct(ExpressionType type) { return type == ExpressionType::COMPARE_DISTINCT_FROM || type == ExpressionType::COMPARE_NOT_DISTINCT_FROM; } +bool StatisticsPropagator::HasNumericMinMax(const BaseStatistics &stats) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + return BignumStats::HasMinMax(stats); + } + return NumericStats::HasMinMax(stats); +} + +Value StatisticsPropagator::NumericMin(const BaseStatistics &stats) { + return stats.GetStatsType() == StatisticsType::BIGNUM_STATS ? BignumStats::Min(stats) : NumericStats::Min(stats); +} + +Value StatisticsPropagator::NumericMax(const BaseStatistics &stats) { + return stats.GetStatsType() == StatisticsType::BIGNUM_STATS ? BignumStats::Max(stats) : NumericStats::Max(stats); +} + +void StatisticsPropagator::SetNumericMin(BaseStatistics &stats, const Value &val) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + BignumStats::SetMin(stats, val); + } else { + NumericStats::SetMin(stats, val); + } +} + +void StatisticsPropagator::SetNumericMax(BaseStatistics &stats, const Value &val) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + BignumStats::SetMax(stats, val); + } else { + NumericStats::SetMax(stats, val); + } +} + bool StatisticsPropagator::ExpressionIsConstant(Expression &expr, const Value &val) { Value expr_value; if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { @@ -59,7 +90,7 @@ void StatisticsPropagator::UpdateFilterStatistics(BaseStatistics &stats, Express // don't handle non-numeric columns here (yet) return; } - if (!NumericStats::HasMinMax(stats)) { + if (!HasNumericMinMax(stats)) { // no stats available: skip this return; } @@ -68,19 +99,19 @@ void StatisticsPropagator::UpdateFilterStatistics(BaseStatistics &stats, Express case ExpressionType::COMPARE_LESSTHANOREQUALTO: // X < constant OR X <= constant // max becomes the constant - NumericStats::SetMax(stats, constant); + SetNumericMax(stats, constant); break; case ExpressionType::COMPARE_GREATERTHAN: case ExpressionType::COMPARE_GREATERTHANOREQUALTO: // X > constant OR X >= constant // min becomes the constant - NumericStats::SetMin(stats, constant); + SetNumericMin(stats, constant); break; case ExpressionType::COMPARE_EQUAL: // X = constant // both min and max become the constant - NumericStats::SetMin(stats, constant); - NumericStats::SetMax(stats, constant); + SetNumericMin(stats, constant); + SetNumericMax(stats, constant); break; default: break; @@ -99,7 +130,7 @@ void StatisticsPropagator::UpdateFilterStatistics(BaseStatistics &lstats, BaseSt // don't handle non-numeric columns here (yet) return; } - if (!NumericStats::HasMinMax(lstats) || !NumericStats::HasMinMax(rstats)) { + if (!HasNumericMinMax(lstats) || !HasNumericMinMax(rstats)) { // no stats available: skip this return; } @@ -112,14 +143,14 @@ void StatisticsPropagator::UpdateFilterStatistics(BaseStatistics &lstats, BaseSt // we know that left.max is AT MOST equal to right.max // because any value in left that is BIGGER than right.max will not pass the filter - if (NumericStats::Max(lstats) > NumericStats::Max(rstats)) { - NumericStats::SetMax(lstats, NumericStats::Max(rstats)); + if (NumericMax(lstats) > NumericMax(rstats)) { + SetNumericMax(lstats, NumericMax(rstats)); } // we also know that right.min is AT MOST equal to left.min // because any value in right that is SMALLER than left.min will not pass the filter - if (NumericStats::Min(rstats) < NumericStats::Min(lstats)) { - NumericStats::SetMin(rstats, NumericStats::Min(lstats)); + if (NumericMin(rstats) < NumericMin(lstats)) { + SetNumericMin(rstats, NumericMin(lstats)); } // so in our example, the bounds get updated as follows: // left: [-50, 100], right: [-50, 100] @@ -129,11 +160,11 @@ void StatisticsPropagator::UpdateFilterStatistics(BaseStatistics &lstats, BaseSt // LEFT > RIGHT OR LEFT >= RIGHT // we know that every value of left is bigger (or equal to) every value in right // this is essentially the inverse of the less than (or equal to) scenario - if (NumericStats::Max(rstats) > NumericStats::Max(lstats)) { - NumericStats::SetMax(rstats, NumericStats::Max(lstats)); + if (NumericMax(rstats) > NumericMax(lstats)) { + SetNumericMax(rstats, NumericMax(lstats)); } - if (NumericStats::Min(lstats) < NumericStats::Min(rstats)) { - NumericStats::SetMin(lstats, NumericStats::Min(rstats)); + if (NumericMin(lstats) < NumericMin(rstats)) { + SetNumericMin(lstats, NumericMin(rstats)); } break; case ExpressionType::COMPARE_EQUAL: @@ -143,16 +174,16 @@ void StatisticsPropagator::UpdateFilterStatistics(BaseStatistics &lstats, BaseSt // so if we have e.g. left = [-50, 250] and right = [-100, 100] // the tighest bounds are [-50, 100] // select the highest min - if (NumericStats::Min(lstats) > NumericStats::Min(rstats)) { - NumericStats::SetMin(rstats, NumericStats::Min(lstats)); + if (NumericMin(lstats) > NumericMin(rstats)) { + SetNumericMin(rstats, NumericMin(lstats)); } else { - NumericStats::SetMin(lstats, NumericStats::Min(rstats)); + SetNumericMin(lstats, NumericMin(rstats)); } // select the lowest max - if (NumericStats::Max(lstats) < NumericStats::Max(rstats)) { - NumericStats::SetMax(rstats, NumericStats::Max(lstats)); + if (NumericMax(lstats) < NumericMax(rstats)) { + SetNumericMax(rstats, NumericMax(lstats)); } else { - NumericStats::SetMax(lstats, NumericStats::Max(rstats)); + SetNumericMax(lstats, NumericMax(rstats)); } break; default: diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp index d28678277..fe4fae892 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp @@ -268,14 +268,15 @@ void StatisticsPropagator::PropagateStatistics(LogicalComparisonJoin &join, uniq } } - // join conditions can be evaluated over candidate pairs that repeat rows of either side, - // so their verification statistics must not carry additive totals + // join conditions are evaluated over candidate pairs that repeat rows of either side and that still hold the + // NULLs rejected by the earlier conditions, so their verification statistics carry neither additive totals nor + // the absence of NULLs for (auto &condition : join.conditions) { if (condition.IsComparison()) { - ResetAdditiveVerificationStats(condition.GetLHS()); - ResetAdditiveVerificationStats(condition.GetRHS()); + RelaxJoinConditionVerificationStats(condition.GetLHS()); + RelaxJoinConditionVerificationStats(condition.GetRHS()); } else { - ResetAdditiveVerificationStats(condition.GetJoinExpression()); + RelaxJoinConditionVerificationStats(condition.GetJoinExpression()); } } } @@ -284,9 +285,9 @@ void StatisticsPropagator::PropagateStatistics(LogicalAnyJoin &join, unique_ptr< // propagate the expression into the join condition // note that a condition that is TRUE_OR_NULL does not always match: a NULL condition rejects the pair PropagateExpression(join.condition); - // the condition is evaluated over candidate pairs that repeat rows of either side, - // so its verification statistics must not carry additive totals - ResetAdditiveVerificationStats(*join.condition); + // the condition is evaluated over candidate pairs that repeat rows of either side and hold NULLs, + // so its verification statistics carry neither additive totals nor the absence of NULLs + RelaxJoinConditionVerificationStats(*join.condition); switch (ClassifyFilter(*join.condition)) { case FilterPropagateResult::FILTER_ALWAYS_TRUE: HandleJoinAlwaysMatches(join, node_ptr); @@ -493,16 +494,16 @@ void StatisticsPropagator::CreateFilterFromJoinStats(unique_ptr } // Match the numeric types supported by UpdateFilterStatistics. auto column = GetFilterColumn(context, *expr); - if (!column || !expr->GetReturnType().IsNumeric() || !NumericStats::HasMinMax(stats_before) || - !NumericStats::HasMinMax(stats_after)) { + if (!column || !expr->GetReturnType().IsNumeric() || !HasNumericMinMax(stats_before) || + !HasNumericMinMax(stats_after)) { return; } // Retrieve min/max - auto min_before = NumericStats::Min(stats_before); - auto max_before = NumericStats::Max(stats_before); - auto min_after = NumericStats::Min(stats_after); - auto max_after = NumericStats::Max(stats_after); + auto min_before = NumericMin(stats_before); + auto max_before = NumericMax(stats_before); + auto min_after = NumericMin(stats_after); + auto max_after = NumericMax(stats_after); vector> filter_exprs; auto add_filter = [&](ExpressionType comparison_type, const Value &bound) { diff --git a/src/duckdb/src/optimizer/statistics_propagator.cpp b/src/duckdb/src/optimizer/statistics_propagator.cpp index e7ea8a27e..27a4cf29a 100644 --- a/src/duckdb/src/optimizer/statistics_propagator.cpp +++ b/src/duckdb/src/optimizer/statistics_propagator.cpp @@ -62,12 +62,14 @@ void StatisticsPropagator::ResetAdditiveStatistics(const vector & } } -void StatisticsPropagator::ResetAdditiveVerificationStats(Expression &expr) { +void StatisticsPropagator::RelaxJoinConditionVerificationStats(Expression &expr) { auto &stats = expr.GetVerificationStats(); if (stats) { stats->ResetAdditiveStatistics(); + // the candidate pairs still hold the NULLs that the comparison rejects + stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES); } - ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { ResetAdditiveVerificationStats(child); }); + ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { RelaxJoinConditionVerificationStats(child); }); } unique_ptr StatisticsPropagator::PropagateStatistics(LogicalOperator &node, diff --git a/src/duckdb/src/parser/constraints/foreign_key_constraint.cpp b/src/duckdb/src/parser/constraints/foreign_key_constraint.cpp index 282204ea3..6ec458b33 100644 --- a/src/duckdb/src/parser/constraints/foreign_key_constraint.cpp +++ b/src/duckdb/src/parser/constraints/foreign_key_constraint.cpp @@ -26,11 +26,9 @@ string ForeignKeyConstraint::ToString() const { base += SQLIdentifier(fk_columns[i]); } base += ") REFERENCES "; - if (!info.schema.empty() && info.schema != DEFAULT_SCHEMA) { - base += SQLIdentifier(info.schema); - base += "."; - } - base += SQLIdentifier(info.table); + auto table_name = + referenced_table.Path().empty() ? QualifiedName(Identifier(), info.schema, info.table) : referenced_table; + base += table_name.ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA); if (!pk_columns.empty()) { base += "("; diff --git a/src/duckdb/src/parser/expression/constant_expression.cpp b/src/duckdb/src/parser/expression/constant_expression.cpp index 19f2b8f97..00ef47317 100644 --- a/src/duckdb/src/parser/expression/constant_expression.cpp +++ b/src/duckdb/src/parser/expression/constant_expression.cpp @@ -1,5 +1,6 @@ #include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/value.hpp" namespace duckdb { @@ -16,7 +17,8 @@ string ConstantExpression::ToString() const { } Value ConstantExpression::GetValueForSerialization() const { - return literal.ToValue(); + // the Value form is written for storage versions before v2.0.0, whose engines type a wider literal as DOUBLE + return literal.ToValue(Decimal::MAX_WIDTH_INT128); } unique_ptr ConstantExpression::DeserializeConstant(const Value &value, Literal literal) { diff --git a/src/duckdb/src/parser/expression/value_expression.cpp b/src/duckdb/src/parser/expression/value_expression.cpp index a845e06ce..49cb3a0d3 100644 --- a/src/duckdb/src/parser/expression/value_expression.cpp +++ b/src/duckdb/src/parser/expression/value_expression.cpp @@ -368,7 +368,12 @@ unique_ptr ConstantExpression::FromValue(const Value &value) { case LogicalTypeId::UBIGINT: case LogicalTypeId::UHUGEINT: case LogicalTypeId::BIGNUM: + return LiteralOrCast(Literal::Number(value.ToString()), value); case LogicalTypeId::DECIMAL: + // a literal with a fractional part re-binds to DOUBLE and loses precision, so cast the exact decimal string + if (value.type().InternalType() == PhysicalType::VARCHAR) { + return StringCast(value); + } return LiteralOrCast(Literal::Number(value.ToString()), value); case LogicalTypeId::BLOB: { auto &bytes = StringValue::Get(value); diff --git a/src/duckdb/src/parser/literal.cpp b/src/duckdb/src/parser/literal.cpp index 3f4a50e91..74ae41438 100644 --- a/src/duckdb/src/parser/literal.cpp +++ b/src/duckdb/src/parser/literal.cpp @@ -94,7 +94,7 @@ Literal Literal::Negate() const { return Literal(kind, "-" + text); } -static Value NumberToValue(const string &val) { +static Value NumberToValue(const string &val, uint32_t max_decimal_width) { string_t str_val(val); bool try_cast_as_integer = true; bool try_cast_as_decimal = true; @@ -149,21 +149,20 @@ static Value NumberToValue(const string &val) { } idx_t decimal_offset = val[0] == '-' ? 3 : 2; if (try_cast_as_decimal && decimal_position.IsValid() && - str_val.GetSize() - num_underscores < Decimal::MAX_WIDTH_DECIMAL + decimal_offset) { + str_val.GetSize() - num_underscores < max_decimal_width + decimal_offset) { // figure out the width/scale based on the decimal position 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) { + if (decimal_position.GetIndex() > 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); if (val[0] == '-') { width--; } - if (width <= Decimal::MAX_WIDTH_DECIMAL) { - return Value(str_val).DefaultCastAs(LogicalType::DECIMAL(width, scale)); - } + // a literal up to the maximum width is an exact decimal, which keeps every digit + return Value(str_val).DefaultCastAs(LogicalType::DECIMAL(width, scale)); } // there is an exponent, or the value is too wide for a decimal double dbl_value = Cast::Operation(str_val); @@ -171,6 +170,10 @@ static Value NumberToValue(const string &val) { } Value Literal::ToValue() const { + return ToValue(NumericLimits::Maximum()); +} + +Value Literal::ToValue(uint32_t max_decimal_width) const { switch (kind) { case LiteralKind::NULL_LITERAL: return Value(); @@ -178,7 +181,7 @@ Value Literal::ToValue() const { return Value::BOOLEAN(text == "true"); case LiteralKind::INTEGER: case LiteralKind::NUMERIC: - return NumberToValue(text); + return NumberToValue(text, max_decimal_width); case LiteralKind::STRING: return Value(text); case LiteralKind::HEX: { diff --git a/src/duckdb/src/parser/peg/transformer/transform_alter.cpp b/src/duckdb/src/parser/peg/transformer/transform_alter.cpp index 347ba2b24..b5864b73e 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_alter.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_alter.cpp @@ -156,10 +156,9 @@ unique_ptr PEGTransformerFactory::TransformAlterSequenceStmt(PEGTrans return alter_sequence_options; } -QualifiedName PEGTransformerFactory::TransformQualifiedSequenceName(PEGTransformer &transformer, - const optional &catalog_qualification, - const optional &schema_qualification, - const Identifier &sequence_name) { +QualifiedName PEGTransformerFactory::TransformQualifiedSequenceName( + PEGTransformer &transformer, const optional &catalog_qualification, + const optional> &schema_qualification, const Identifier &sequence_name) { // The grammar greedily fills the catalog qualifier first, so a 2-part name "a.b" arrives as catalog="a" // with no schema. Store the qualifiers as a plain schema path: a lone qualifier becomes the schema, and the // binder's BindSchemaOrCatalog promotes it to a catalog if it names an attached database. @@ -168,7 +167,7 @@ QualifiedName PEGTransformerFactory::TransformQualifiedSequenceName(PEGTransform schema_path.push_back(*catalog_qualification); } if (schema_qualification) { - schema_path.push_back(*schema_qualification); + schema_path.insert(schema_path.end(), schema_qualification->begin(), schema_qualification->end()); } return QualifiedName(std::move(schema_path), sequence_name); } diff --git a/src/duckdb/src/parser/peg/transformer/transform_create_table.cpp b/src/duckdb/src/parser/peg/transformer/transform_create_table.cpp index 2069fb8a9..49d697a89 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_create_table.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_create_table.cpp @@ -425,7 +425,9 @@ ColumnConstraintEntry PEGTransformerFactory::TransformForeignKeyConstraint(PEGTr if (column_list) { columns = StringsToIdentifiers(*column_list); } - entry.constraint = make_uniq(columns, vector(), fk_info); + auto constraint = make_uniq(columns, vector(), fk_info); + constraint->referenced_table = base_table_name->GetQualifiedName(); + entry.constraint = std::move(constraint); return entry; } diff --git a/src/duckdb/src/parser/peg/transformer/transform_describe.cpp b/src/duckdb/src/parser/peg/transformer/transform_describe.cpp index 5ff313174..19ab56f87 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_describe.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_describe.cpp @@ -53,16 +53,7 @@ unique_ptr PEGTransformerFactory::TransformShowTables(PEGTransformer const QualifiedName &qualified_name) { auto showref = make_uniq(); showref->show_type = ShowType::SHOW_FROM; - if (!IsInvalidCatalog(qualified_name.Catalog())) { - throw ParserException("Expected \"SHOW TABLES FROM database\", \"SHOW TABLES FROM schema\", or " - "\"SHOW TABLES FROM database.schema\""); - } - if (IsInvalidSchema(qualified_name.Schema())) { - showref->SetSchemaName(qualified_name.Name()); - } else { - showref->SetCatalogName(qualified_name.Schema()); - showref->SetSchemaName(qualified_name.Name()); - } + showref->qualified_name = QualifiedName(qualified_name.Path(), Identifier()); return WrapShowRef(std::move(showref)); } diff --git a/src/duckdb/src/parser/peg/transformer/transform_drop.cpp b/src/duckdb/src/parser/peg/transformer/transform_drop.cpp index 9a1cdfea5..5d81cfefd 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_drop.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_drop.cpp @@ -173,9 +173,10 @@ QualifiedName PEGTransformerFactory::TransformSchemaReservedIndex(PEGTransformer QualifiedName PEGTransformerFactory::TransformCatalogReservedSchemaIndex( PEGTransformer &transformer, const Identifier &catalog_qualification, - const Identifier &reserved_schema_qualification, const Identifier &reserved_index_name) { - QualifiedName result(catalog_qualification, reserved_schema_qualification, reserved_index_name); - return result; + const vector &reserved_schema_qualification, const Identifier &reserved_index_name) { + vector path {catalog_qualification}; + path.insert(path.end(), reserved_schema_qualification.begin(), reserved_schema_qualification.end()); + return QualifiedName(std::move(path), reserved_index_name); } unique_ptr 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 49a218578..936dc01ae 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -326,7 +326,7 @@ static const TransformChildPlan FRAME_CHILDREN_20[] = {{PEGRuleId::AlterSequence {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, + TransformChildKind::OPTIONAL_REPEAT, 1, 1, false, @@ -339,7 +339,7 @@ static const TransformChildPlan FRAME_CHILDREN_21[] = {{PEGRuleId::SchemaQualifi 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 TransformFramePlan FRAME_PLAN_24 = {FRAME_CHILDREN_21, 2, 2, true, 0, {}}; static const TransformChildPlan FRAME_CHILDREN_22[] = {{PEGRuleId::RenameAlter, TransformChildKind::REQUIRED, 0, @@ -2644,22 +2644,7 @@ static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::QualifiedInd {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::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_196 = {FRAME_CHILDREN_182, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::QualifiedSequenceName, +static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::QualifiedSequenceName, TransformChildKind::LIST, 2, 1, @@ -2673,8 +2658,8 @@ static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::QualifiedSeq false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::CollationName, +static const TransformFramePlan FRAME_PLAN_196 = {FRAME_CHILDREN_182, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::CollationName, TransformChildKind::LIST, 2, 1, @@ -2688,8 +2673,8 @@ static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::CollationNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::QualifiedTypeName, +static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::QualifiedTypeName, TransformChildKind::LIST, 2, 1, @@ -2703,8 +2688,8 @@ static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::QualifiedTyp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::DropSecretStorage, +static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::DropSecretStorage, TransformChildKind::OPTIONAL, 4, 3, @@ -2732,8 +2717,8 @@ static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::DropSecretSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_200 = {FRAME_CHILDREN_186, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::TableFunctionArguments, +static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::TableFunctionArguments, TransformChildKind::OPTIONAL, 2, 1, @@ -2747,8 +2732,8 @@ static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::TableFunctio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_201 = {FRAME_CHILDREN_187, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExplainableStatements, +static const TransformFramePlan FRAME_PLAN_200 = {FRAME_CHILDREN_186, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::ExplainableStatements, TransformChildKind::REQUIRED, 3, 2, @@ -2769,16 +2754,16 @@ static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExplainableS false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_188, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::ExplainOption, +static const TransformFramePlan FRAME_PLAN_201 = {FRAME_CHILDREN_187, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExplainOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_189, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_188, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 1, 1, @@ -2792,9 +2777,9 @@ static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_204 = {FRAME_CHILDREN_190, 2, 2, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_189, 2, 2, false, 0, {}}; static const char *const FRAME_NAMES_8[] = {"FuncNameKeyword", "TypeNameKeyword"}; -static const TransformFramePlan FRAME_PLAN_205 = {nullptr, +static const TransformFramePlan FRAME_PLAN_204 = {nullptr, 0, 1, false, @@ -2803,15 +2788,15 @@ static const TransformFramePlan FRAME_PLAN_205 = {nullptr, ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING), 0, true, false, 2, FRAME_NAMES_8}}; -static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::SelectStatementInternal, +static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_206 = {FRAME_CHILDREN_191, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::ExportOptions, +static const TransformFramePlan FRAME_PLAN_205 = {FRAME_CHILDREN_190, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::ExportOptions, TransformChildKind::OPTIONAL, 4, 1, @@ -2825,8 +2810,8 @@ static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::ExportOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_206 = {FRAME_CHILDREN_191, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::REPEAT, 3, 3, @@ -2854,8 +2839,8 @@ static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedTableQualification, +static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ReservedTableQualification, TransformChildKind::REQUIRED, 2, 2, @@ -2876,8 +2861,8 @@ static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedTabl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::ReservedTableQualification, +static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedTableQualification, TransformChildKind::REQUIRED, 1, 1, @@ -2891,16 +2876,16 @@ static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::ReservedTabl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::TableQualification, +static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::TableQualification, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::OverClause, +static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::OverClause, TransformChildKind::OPTIONAL, 5, 4, @@ -2935,16 +2920,16 @@ static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::OverClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::FunctionExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::FunctionExpressionArgumentList, TransformChildKind::REQUIRED, 0, 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::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -2972,16 +2957,16 @@ static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_213 = {FRAME_CHILDREN_198, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::FunctionArgument, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -2995,32 +2980,32 @@ static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::OrderByClause, +static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::FilterClauseExpression, +static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::FilterClauseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::FilterClauseContents, +static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::FilterClauseContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::CastArguments, +static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::CastArguments, TransformChildKind::REQUIRED, 1, 1, @@ -3034,8 +3019,8 @@ static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::CastArgument false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::Type, +static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::Type, TransformChildKind::REQUIRED, 2, 1, @@ -3049,8 +3034,8 @@ static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::Type, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::RenameList, +static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::RenameList, TransformChildKind::OPTIONAL, 4, 3, @@ -3078,72 +3063,72 @@ static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::RenameList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::ColIdDot, +static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::ColIdDot, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_223 = {FRAME_CHILDREN_208, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_209[] = {{PEGRuleId::ExcludeNames, +static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::ExcludeNames, 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::ExcludeName, +static const TransformFramePlan FRAME_PLAN_223 = {FRAME_CHILDREN_208, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_209[] = {{PEGRuleId::ExcludeName, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_225 = {FRAME_CHILDREN_210, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_211[] = {{PEGRuleId::ExcludeName, +static const TransformFramePlan FRAME_PLAN_224 = {FRAME_CHILDREN_209, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_210[] = {{PEGRuleId::ExcludeName, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::DottedIdentifier, +static const TransformFramePlan FRAME_PLAN_225 = {FRAME_CHILDREN_210, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_211[] = {{PEGRuleId::DottedIdentifier, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::ReplaceEntries, +static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::ReplaceEntries, 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::ReplaceEntry, +static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::ReplaceEntry, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_229 = {FRAME_CHILDREN_214, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ReplaceEntry, +static const TransformFramePlan FRAME_PLAN_228 = {FRAME_CHILDREN_213, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_214[] = {{PEGRuleId::ReplaceEntry, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::ColumnReference, +static const TransformFramePlan FRAME_PLAN_229 = {FRAME_CHILDREN_214, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ColumnReference, TransformChildKind::REQUIRED, 2, 1, @@ -3157,32 +3142,32 @@ static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::ColumnRefere false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::RenameEntries, +static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::RenameEntries, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::RenameEntry, +static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::RenameEntry, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::RenameEntry, +static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::RenameEntry, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 2, 2, @@ -3203,8 +3188,8 @@ static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::CaseElse, +static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::CaseElse, TransformChildKind::OPTIONAL, 3, 2, @@ -3225,8 +3210,8 @@ static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::CaseElse, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::CaseElse, +static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::CaseElse, TransformChildKind::OPTIONAL, 2, 1, @@ -3240,8 +3225,8 @@ static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::CaseElse, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -3255,8 +3240,8 @@ static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_238 = {FRAME_CHILDREN_223, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -3270,8 +3255,8 @@ static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Expression, 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::Interval, +static const TransformFramePlan FRAME_PLAN_238 = {FRAME_CHILDREN_223, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 1, @@ -3285,8 +3270,8 @@ static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::Interval, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::WindowExcludeClause, +static const TransformFramePlan FRAME_PLAN_239 = {FRAME_CHILDREN_224, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::WindowExcludeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3307,16 +3292,16 @@ static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::WindowExclud false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::FrameBound, +static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::FrameBound, TransformChildKind::REQUIRED, 0, 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::FrameBound, +static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::FrameBound, TransformChildKind::REQUIRED, 3, 1, @@ -3330,16 +3315,16 @@ static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::FrameBound, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_243 = {FRAME_CHILDREN_228, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::PrecedingOrFollowing, +static const TransformFramePlan FRAME_PLAN_242 = {FRAME_CHILDREN_227, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::PrecedingOrFollowing, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_244 = {FRAME_CHILDREN_229, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::PrecedingOrFollowing, +static const TransformFramePlan FRAME_PLAN_243 = {FRAME_CHILDREN_228, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::PrecedingOrFollowing, TransformChildKind::REQUIRED, 1, 1, @@ -3353,24 +3338,24 @@ static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::PrecedingOrF false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_245 = {FRAME_CHILDREN_230, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::WindowExcludeElement, +static const TransformFramePlan FRAME_PLAN_244 = {FRAME_CHILDREN_229, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::WindowExcludeElement, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowFrameNameContents, +static const TransformFramePlan FRAME_PLAN_245 = {FRAME_CHILDREN_230, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::WindowFrameNameContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameContents, +static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowFrameContents, TransformChildKind::REQUIRED, 1, 1, @@ -3384,16 +3369,16 @@ static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameC false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_248 = {FRAME_CHILDREN_233, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::WindowFrameContents, +static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::FrameClause, +static const TransformFramePlan FRAME_PLAN_248 = {FRAME_CHILDREN_233, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::FrameClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3414,40 +3399,40 @@ static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::FrameClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_250 = {FRAME_CHILDREN_235, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::BoundedListExpression, +static const TransformFramePlan FRAME_PLAN_250 = {FRAME_CHILDREN_235, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::BoundedListExpression, 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::Expression, +static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::Expression, 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::StructField, +static const TransformFramePlan FRAME_PLAN_252 = {FRAME_CHILDREN_237, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_238[] = {{PEGRuleId::StructField, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_254 = {FRAME_CHILDREN_239, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::Expression, +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, @@ -3461,24 +3446,24 @@ static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::MapStructExpression, +static const TransformFramePlan FRAME_PLAN_254 = {FRAME_CHILDREN_239, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::MapStructExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::MapStructField, +static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::MapStructField, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_257 = {FRAME_CHILDREN_242, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -3492,8 +3477,8 @@ static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_257 = {FRAME_CHILDREN_242, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -3507,8 +3492,8 @@ static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::ListComprehensionFilter, +static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::ListComprehensionFilter, TransformChildKind::OPTIONAL, 6, 3, @@ -3536,16 +3521,16 @@ static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::ListComprehe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::FunctionExpression, +static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::FunctionExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3559,24 +3544,24 @@ static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::FunctionExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::LogicalOrExpression, +static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::LogicalOrExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::ColDefOrExpr, +static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::ColDefOrExpr, TransformChildKind::REQUIRED, 0, 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::LogicalOrExpressionTail, +static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3590,16 +3575,16 @@ static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalOrExp 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::LogicalAndExpression, +static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalAndExpression, 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::ColDefOrExpressionTail, +static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::ColDefOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3613,16 +3598,16 @@ static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefOrExpr 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::ColDefAndExpr, +static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefAndExpr, 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::LogicalAndExpressionTail, +static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::LogicalAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3636,16 +3621,16 @@ static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::LogicalAndEx 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::LogicalNotExpression, +static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::LogicalNotExpression, 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::ColDefAndExpressionTail, +static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::ColDefAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3659,16 +3644,16 @@ static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::ColDefAndExp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsDistinctFromExpression, +static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsDistinctFromExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3682,16 +3667,16 @@ static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsExpression 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::NotKeyword, +static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::NotKeyword, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsExpressionContinuation, +static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpressionContinuation, TransformChildKind::OPTIONAL, 1, 1, @@ -3705,8 +3690,8 @@ static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsExpressionTail, +static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3720,64 +3705,64 @@ static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::IsTest, +static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsTest, 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::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::IsDistinctFromTail, 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::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::ComparisonExpressionTail, 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::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::CastOperator, 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::IsLiteralValue, +static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::IsLiteralValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsNullOperator, +static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::IsNullOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3791,8 +3776,8 @@ static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsDistinctFr 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::ComparisonExpression, +static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::ComparisonExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3806,8 +3791,8 @@ static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3821,8 +3806,8 @@ static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::ComparisonOperand, +static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonOperand, TransformChildKind::REQUIRED, 1, 1, @@ -3836,8 +3821,8 @@ static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::ComparisonOp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3851,8 +3836,8 @@ static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::BetweenLikeOp, +static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::BetweenLikeOp, TransformChildKind::OPTIONAL, 2, 2, @@ -3873,8 +3858,8 @@ static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::BetweenLikeO false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::CastOperator, TransformChildKind::OPTIONAL_REPEAT, 2, 1, @@ -3888,16 +3873,16 @@ static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::CastOperator false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::BetweenLikeOpExpression, +static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::BetweenLikeOpExpression, 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::EscapeClause, +static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::EscapeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3918,48 +3903,48 @@ static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::EscapeClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::InExpression, +static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::InExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {1, 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::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 4, 1, @@ -3973,16 +3958,16 @@ static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::InfixOtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::InfixOtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3996,8 +3981,8 @@ static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -4011,8 +3996,8 @@ static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4026,16 +4011,16 @@ static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::SingleArrowBody, +static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::SingleArrowBody, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::ArrowChainTail, +static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::ArrowChainTail, TransformChildKind::REPEAT, 1, 1, @@ -4049,48 +4034,48 @@ static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::ArrowChainTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::AnyAllOperator, +static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::AnyAllOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AnyOrAll, +static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::AnyOrAll, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::QualifiedOperatorContents, +static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::QualifiedOperatorContents, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::ColIdDot, +static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::ColIdDot, TransformChildKind::OPTIONAL_REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::BitwiseExpressionTail, +static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::BitwiseExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4104,8 +4089,8 @@ static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::BitwiseExpre 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::TildeExpression, +static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4119,8 +4104,8 @@ static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::TildeExpress 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::AdditiveExpression, +static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::AdditiveExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4134,8 +4119,8 @@ static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::AdditiveExpressionTail, +static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::AdditiveExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4149,8 +4134,8 @@ static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::MultiplicativeExpression, +static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::MultiplicativeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4164,8 +4149,8 @@ static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::Multiplicati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::MultiplicativeExpressionTail, +static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::MultiplicativeExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4179,8 +4164,8 @@ static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::Multiplicati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::ExponentiationExpression, +static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::ExponentiationExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4194,8 +4179,8 @@ static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::ExponentiationExpressionTail, +static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::ExponentiationExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4209,8 +4194,8 @@ static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::CollateExpression, +static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::CollateExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4224,8 +4209,8 @@ static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::CollateExpressionTail, +static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::CollateExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4239,16 +4224,16 @@ static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::AtTimeZoneExpression, +static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::AtTimeZoneExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::AtTimeZoneExpressionTail, +static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::AtTimeZoneExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4262,24 +4247,24 @@ static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::AtTimeZoneEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::UnaryExpression, +static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::UnaryExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, 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::IndirectionList, +static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::IndirectionList, TransformChildKind::OPTIONAL, 1, 1, @@ -4293,24 +4278,24 @@ static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::IndirectionL false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::Indirection, +static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::Indirection, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::MethodExpression, +static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::MethodExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpressionArguments, +static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::MethodExpressionArguments, TransformChildKind::REQUIRED, 1, 1, @@ -4324,16 +4309,16 @@ static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpres false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::MethodExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpressionArgumentList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -4361,16 +4346,16 @@ static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::SliceBound, +static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::SliceBound, TransformChildKind::REQUIRED, 1, 0, false, {0, 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::SliceUpperBound, +static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::SliceUpperBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4384,16 +4369,16 @@ static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::SliceUpperBo false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::StepSliceBound, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::StepSliceBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4407,32 +4392,32 @@ static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::StepSliceBou false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 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::ExtractArguments, +static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::ExtractArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4446,8 +4431,8 @@ static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -4461,24 +4446,24 @@ static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::NullIfArguments, +static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::NullIfArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::PositionArguments, +static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::PositionArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4492,32 +4477,32 @@ static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::Expression, 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::Expression, +static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::SubstringArguments, +static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::SubstringArguments, 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, +static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::SubstringFromFor, +static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::SubstringFromFor, TransformChildKind::REQUIRED, 1, 1, @@ -4531,8 +4516,8 @@ static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::SubstringFro false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 1, 1, @@ -4546,24 +4531,24 @@ static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::ForExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::TrimArguments, +static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::TrimArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, 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::Expression, +static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 2, @@ -4584,24 +4569,24 @@ static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::OverlayArguments, +static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::OverlayArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, 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::ForExpression, +static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 4, 3, @@ -4629,16 +4614,16 @@ static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::ExtractDatePart, +static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::ExtractDatePart, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, 1, @@ -4652,8 +4637,8 @@ static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExternalReso false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 5, 1, @@ -4667,16 +4652,16 @@ static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::ColId, +static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ColId, TransformChildKind::REQUIRED, 2, 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::AttachOptions, +static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 4, 2, @@ -4697,8 +4682,8 @@ static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::AttachOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::AttachOptions, +static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 3, 1, @@ -4712,16 +4697,16 @@ static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::AttachOption 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::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 10, 7, @@ -4777,24 +4762,24 @@ static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 8, 8, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::InsertByName, +static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::InsertByName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::InsertByPosition, +static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::InsertByPosition, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::InsertAlias, +static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::InsertAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -4808,8 +4793,8 @@ static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::InsertAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::OnConflictAction, +static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::OnConflictAction, TransformChildKind::REQUIRED, 3, 1, @@ -4823,8 +4808,8 @@ static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::OnConflictAc false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 1, 1, @@ -4838,16 +4823,16 @@ static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::ConstraintName, +static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::ConstraintName, TransformChildKind::REQUIRED, 2, 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::WhereClause, +static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 4, 1, @@ -4861,16 +4846,16 @@ static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::ExtensionAlias, +static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ExtensionAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -4891,8 +4876,8 @@ static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::ExtensionAli false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::VersionNumber, +static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::VersionNumber, TransformChildKind::OPTIONAL, 5, 3, @@ -4920,17 +4905,17 @@ static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::VersionNumbe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::FromSourceName, +static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::FromSourceName, TransformChildKind::REQUIRED, 1, 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 TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 1, 1, false, 0, {}}; static const char *const FRAME_NAMES_9[] = {"Identifier"}; -static const TransformFramePlan FRAME_PLAN_372 = {nullptr, +static const TransformFramePlan FRAME_PLAN_371 = {nullptr, 0, 1, false, @@ -4939,15 +4924,15 @@ static const TransformFramePlan FRAME_PLAN_372 = {nullptr, ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING), 0, true, true, 1, FRAME_NAMES_9}}; -static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::IdentifierOrStringLiteral, +static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::IdentifierOrStringLiteral, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_357, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::RepositoryPublicKey, +static const TransformFramePlan FRAME_PLAN_372 = {FRAME_CHILDREN_356, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::RepositoryPublicKey, TransformChildKind::OPTIONAL, 7, 4, @@ -4982,8 +4967,8 @@ static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::RepositoryPu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_374 = {FRAME_CHILDREN_358, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::ExtensionRepositoryName, +static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_357, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::ExtensionRepositoryName, TransformChildKind::REQUIRED, 5, 2, @@ -5004,8 +4989,8 @@ static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::ExtensionRep false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_359, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::ExtensionRepositoryName, +static const TransformFramePlan FRAME_PLAN_374 = {FRAME_CHILDREN_358, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::ExtensionRepositoryName, TransformChildKind::REQUIRED, 4, 1, @@ -5019,8 +5004,8 @@ static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::ExtensionRep false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_360, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::DotColLabel, +static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_359, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::DotColLabel, TransformChildKind::REPEAT, 1, 1, @@ -5034,8 +5019,8 @@ static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::DotColLabel, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_361, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_360, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -5049,16 +5034,24 @@ static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_362, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::MatchRecognizeClause, +static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_361, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::MatchRecognizeClause, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_363, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::WindowPartition, +static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_362, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::WindowPartition, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_363, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 0, 0, @@ -5066,7 +5059,7 @@ static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::WindowPartit {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_364, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::OrderByClause, +static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::MeasuresClause, TransformChildKind::REQUIRED, 0, 0, @@ -5074,7 +5067,7 @@ static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::OrderByClaus {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_365, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::MeasuresClause, +static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::RowsPerMatch, TransformChildKind::REQUIRED, 0, 0, @@ -5082,7 +5075,7 @@ static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::MeasuresClau {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::RowsPerMatch, +static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::AfterMatchSkip, TransformChildKind::REQUIRED, 0, 0, @@ -5090,7 +5083,7 @@ static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::RowsPerMatch {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::AfterMatchSkip, +static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::PatternClause, TransformChildKind::REQUIRED, 0, 0, @@ -5098,7 +5091,7 @@ static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::AfterMatchSk {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::PatternClause, +static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::SubsetClause, TransformChildKind::REQUIRED, 0, 0, @@ -5106,7 +5099,7 @@ static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::PatternClaus {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::SubsetClause, +static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::DefineClause, TransformChildKind::REQUIRED, 0, 0, @@ -5114,23 +5107,15 @@ static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::SubsetClause {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::DefineClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_371, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::MeasuresElement, +static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::MeasuresElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_372, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_371, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 1, @@ -5144,48 +5129,48 @@ static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_373, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::AllRowsEmptyMatches, +static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_372, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::AllRowsEmptyMatches, TransformChildKind::OPTIONAL, 4, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_374, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::AfterMatchSkipTarget, +static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_373, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::AfterMatchSkipTarget, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_375, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_374, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_375, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPatternAlternative, +static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPatternAlternative, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5199,24 +5184,24 @@ static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPatternAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_379, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::RowPatternTerm, +static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_378, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPatternTerm, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_380, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternFactor, +static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_379, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::RowPatternFactor, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_381, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPatternQuantifier, +static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_380, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternQuantifier, TransformChildKind::OPTIONAL, 1, 1, @@ -5230,40 +5215,40 @@ static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPatternQu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_382, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_381, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPattern, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_383, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_382, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_384, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_383, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_385, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_384, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_386, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::QuantifierReluctant, +static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_385, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::QuantifierReluctant, TransformChildKind::OPTIONAL, 1, 1, @@ -5277,24 +5262,24 @@ static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::QuantifierRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_387, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::QuantifierBounds, +static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_386, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::QuantifierBounds, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_388, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::SubsetElement, +static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_387, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::SubsetElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_389, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_388, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::LIST, 2, 1, @@ -5308,16 +5293,16 @@ static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_390, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::DefineElement, +static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_389, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::DefineElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_391, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_390, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -5331,8 +5316,8 @@ static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_392, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_391, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 7, 5, @@ -5374,16 +5359,16 @@ static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_393, 6, 6, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::TableRef, +static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_392, 6, 6, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::TableRef, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_394, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_393, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 4, 1, @@ -5397,48 +5382,48 @@ static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_395, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::UpdateMatchInfo, +static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_394, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::UpdateMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_396, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::UpdateMatchSetClause, +static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_395, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::UpdateMatchSetClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_396, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_398, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::InsertMatchInfo, +static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::InsertMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_399, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_398, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_400, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_399, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 1, @@ -5452,16 +5437,16 @@ static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_401, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::UpdateMatchSetInfo, +static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_400, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::UpdateMatchSetInfo, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_402, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_401, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 6, 2, @@ -5482,24 +5467,24 @@ static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_403, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::PivotColumnList, +static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_402, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::PivotColumnList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_404, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::PivotColumnEntry, +static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::PivotColumnEntry, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_405, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_404, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 2, 1, @@ -5513,8 +5498,8 @@ static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::SelectStatem false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_406, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_405, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 4, 1, @@ -5528,48 +5513,48 @@ static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::OptionalPare false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_407, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_406, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_408, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_407, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_409, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::PragmaAssignOrFunction, +static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_408, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::PragmaAssignOrFunction, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_410, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_409, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::PragmaParameters, +static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_410, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::PragmaParameters, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_412, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 4, 2, @@ -5590,11 +5575,11 @@ static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::Statement, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_413, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_414[] = { +static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_412, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_413[] = { {PEGRuleId::Type, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_414, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::SelectSetOpChainTail, +static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_413, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::SelectSetOpChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5608,8 +5593,8 @@ static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::SelectSetOpC false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_415, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::IntersectChain, +static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_414, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::IntersectChain, TransformChildKind::REQUIRED, 1, 1, @@ -5623,8 +5608,8 @@ static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_416, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::IntersectChainTail, +static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_415, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::IntersectChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5638,8 +5623,8 @@ static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_417, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::SelectAtom, +static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_416, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::SelectAtom, TransformChildKind::REQUIRED, 1, 1, @@ -5653,16 +5638,16 @@ static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::SelectAtom, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_418, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_419, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_418, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 1, @@ -5676,8 +5661,8 @@ static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::DistinctOrAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_420, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::LimitOffset, +static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_419, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::LimitOffset, TransformChildKind::OPTIONAL, 1, 1, @@ -5691,8 +5676,8 @@ static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::LimitOffset, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_420, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::OffsetClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5706,8 +5691,8 @@ static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::LimitClause, +static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::LimitClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5721,8 +5706,8 @@ static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::LimitClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 1, 1, @@ -5736,8 +5721,8 @@ static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::FetchClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_424, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::OffsetClause, TransformChildKind::REQUIRED, 1, 1, @@ -5751,32 +5736,32 @@ static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_425, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_424, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_426, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_425, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_427, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::SimpleSelect, +static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_426, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::SimpleSelect, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_428, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::FromClause, +static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_427, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::FromClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5790,8 +5775,8 @@ static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::FromClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_429, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SelectClause, +static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_428, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SelectClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5805,8 +5790,8 @@ static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SelectClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_430, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::CTEBody, +static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_429, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::CTEBody, TransformChildKind::REQUIRED, 5, 4, @@ -5841,24 +5826,24 @@ static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::CTEBody, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_431, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_430, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_432, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_431, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_433, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_432, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TargetList, TransformChildKind::OPTIONAL, 2, 1, @@ -5872,24 +5857,24 @@ static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TargetList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_434, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::AliasedExpression, +static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_433, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::AliasedExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_435, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::DistinctOnTargets, +static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_434, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::DistinctOnTargets, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_436, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_435, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5924,8 +5909,8 @@ static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_437, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_436, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5960,8 +5945,8 @@ static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_438, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_437, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -5989,8 +5974,8 @@ static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_439, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_438, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -6018,8 +6003,8 @@ static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_440, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::JoinOrPivot, +static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_439, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::JoinOrPivot, TransformChildKind::REPEAT, 1, 1, @@ -6033,8 +6018,8 @@ static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::JoinOrPivot, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_441, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_440, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -6048,8 +6033,8 @@ static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_442, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::PivotGroupByList, +static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_441, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::PivotGroupByList, TransformChildKind::OPTIONAL, 3, 2, @@ -6070,16 +6055,16 @@ static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::PivotGroupBy false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_443, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_442, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_444, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_443, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -6100,8 +6085,8 @@ static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::TableAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_445, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::UnpivotValueList, +static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_444, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::UnpivotValueList, TransformChildKind::REPEAT, 2, 1, @@ -6115,16 +6100,16 @@ static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::UnpivotValue false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_446, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::BaseExpression, +static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_445, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::BaseExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_447, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::PivotValueTarget, +static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_446, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::PivotValueTarget, TransformChildKind::REQUIRED, 2, 1, @@ -6138,16 +6123,16 @@ static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::PivotValueTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_448, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::PivotTargetList, +static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_447, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::PivotTargetList, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_449, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::UnpivotTargetList, +static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_448, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::UnpivotTargetList, TransformChildKind::REQUIRED, 2, 1, @@ -6161,16 +6146,16 @@ static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::UnpivotTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_450, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_449, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_451, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_450, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 5, 5, @@ -6212,8 +6197,8 @@ static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_452, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_451, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -6248,8 +6233,8 @@ static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_453, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::SchemaQualification, +static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_452, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -6263,16 +6248,16 @@ static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::SchemaQualif false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_454, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_453, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::FunctionArgument, TransformChildKind::OPTIONAL_LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_455, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_454, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6286,8 +6271,8 @@ static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_456, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_455, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 2, @@ -6308,8 +6293,8 @@ static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_457, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_456, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 2, 1, @@ -6323,24 +6308,24 @@ static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::ColumnAliase false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_458, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_457, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_459, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::AtSpecifier, +static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_458, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::AtSpecifier, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_460, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_459, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6354,8 +6339,8 @@ static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_461, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_460, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6390,8 +6375,8 @@ static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_462, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_461, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6426,16 +6411,16 @@ static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_463, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::ValuesClause, +static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_462, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::ValuesClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_464, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::WithOrdinality, +static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_463, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::WithOrdinality, TransformChildKind::OPTIONAL, 3, 3, @@ -6463,8 +6448,8 @@ static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::WithOrdinali false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_465, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_464, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -6478,8 +6463,8 @@ static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_466, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_465, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 2, 2, @@ -6500,8 +6485,8 @@ static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_467, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_466, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 1, 1, @@ -6515,8 +6500,8 @@ static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleClause false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_468, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::JoinQualifier, +static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_467, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, 3, @@ -6544,8 +6529,8 @@ static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::JoinQualifie false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_469, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_470[] = { +static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_468, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_469[] = { {PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, @@ -6561,8 +6546,8 @@ static const TransformChildPlan FRAME_CHILDREN_470[] = { {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_486 = {FRAME_CHILDREN_470, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::InnerTableRef, +static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_469, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::InnerTableRef, TransformChildKind::REQUIRED, 2, 1, @@ -6576,48 +6561,48 @@ static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::InnerTableRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_471, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::UsingColumnName, +static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_470, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::UsingColumnName, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_472, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::JoinType, +static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_471, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::JoinType, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_473, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::GroupByExpressions, +static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_472, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::GroupByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_474, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::SampleEntry, +static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_473, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::SampleEntry, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_475, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::WindowDefinition, +static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_474, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::WindowDefinition, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_476, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::SampleProperties, +static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_475, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::SampleProperties, TransformChildKind::OPTIONAL, 1, 1, @@ -6631,8 +6616,8 @@ static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::SampleProper false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_477, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::RepeatableSample, +static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_476, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::RepeatableSample, TransformChildKind::OPTIONAL, 2, 2, @@ -6653,8 +6638,8 @@ static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::RepeatableSa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_478, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_479[] = { +static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_477, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_478[] = { {PEGRuleId::SampleSeed, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, 1, 0}}, {PEGRuleId::ColId, TransformChildKind::REQUIRED, @@ -6663,16 +6648,16 @@ static const TransformChildPlan FRAME_CHILDREN_479[] = { false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_479, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::SampleSeed, +static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_478, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::SampleSeed, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_480, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::SampleUnit, +static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_479, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::SampleUnit, TransformChildKind::OPTIONAL, 1, 1, @@ -6686,16 +6671,16 @@ static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::SampleUnit, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_481, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_480, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_482, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_481, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -6709,32 +6694,32 @@ static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_483, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_482, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_484, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::OrderByExpressions, +static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_483, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::OrderByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_485, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::OrderByExpression, +static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_484, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::OrderByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_486, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::NullsFirstOrLast, +static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_485, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::NullsFirstOrLast, TransformChildKind::OPTIONAL, 2, 1, @@ -6748,32 +6733,32 @@ static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::NullsFirstOr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_487, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::LimitValue, +static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_486, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::LimitValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::OffsetValue, +static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_487, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::OffsetValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::FetchValue, +static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::FetchValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_490, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6787,56 +6772,56 @@ static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_491, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::ValuesExpressions, +static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_490, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::ValuesExpressions, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_492, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::SetAssignmentOrTimeZone, +static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_491, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::SetAssignmentOrTimeZone, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_492, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::ResetTarget, +static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::ResetTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::SettingScope, +static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::SettingScope, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SetVariableOrSetting, +static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::SetVariableOrSetting, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_497, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::SetAssignment, +static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SetAssignment, TransformChildKind::REQUIRED, 1, 1, @@ -6850,8 +6835,8 @@ static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::SetAssignmen false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_498, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::ZoneValue, +static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_497, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::ZoneValue, TransformChildKind::REQUIRED, 3, 1, @@ -6865,48 +6850,48 @@ static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::ZoneValue, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_499, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::Interval, +static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_498, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_500, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::VariableScope, +static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_499, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::VariableScope, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_500, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::ReadOrWrite, +static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::ReadOrWrite, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_503, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReadOnlyOrReadWrite, +static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::ReadOnlyOrReadWrite, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_504, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_503, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 6, 5, @@ -6948,8 +6933,8 @@ static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_505, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::UpdateAlias, +static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_504, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::UpdateAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -6963,16 +6948,16 @@ static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::UpdateAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_506, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::UpdateSetClause, +static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_505, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::UpdateSetClause, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_523 = {FRAME_CHILDREN_507, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_506, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6986,32 +6971,32 @@ static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_524 = {FRAME_CHILDREN_508, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_509[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_523 = {FRAME_CHILDREN_507, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_525 = {FRAME_CHILDREN_509, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_510[] = {{PEGRuleId::UseTarget, +static const TransformFramePlan FRAME_PLAN_524 = {FRAME_CHILDREN_508, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_509[] = {{PEGRuleId::UseTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_526 = {FRAME_CHILDREN_510, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_525 = {FRAME_CHILDREN_509, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_510[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_527 = {FRAME_CHILDREN_511, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::AnalyzeTarget, +static const TransformFramePlan FRAME_PLAN_526 = {FRAME_CHILDREN_510, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::AnalyzeTarget, TransformChildKind::OPTIONAL, 2, 1, @@ -7025,16 +7010,16 @@ static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::AnalyzeTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_528 = {FRAME_CHILDREN_512, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::VacuumOption, +static const TransformFramePlan FRAME_PLAN_527 = {FRAME_CHILDREN_511, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::VacuumOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_529 = {FRAME_CHILDREN_513, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::OptAnalyze, +static const TransformFramePlan FRAME_PLAN_528 = {FRAME_CHILDREN_512, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::OptAnalyze, TransformChildKind::OPTIONAL, 3, 3, @@ -7062,15 +7047,15 @@ static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::OptAnalyze, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_530 = {FRAME_CHILDREN_514, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_515[] = {{PEGRuleId::AnalyzeKeyword, +static const TransformFramePlan FRAME_PLAN_529 = {FRAME_CHILDREN_513, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::AnalyzeKeyword, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_531 = {FRAME_CHILDREN_515, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_530 = {FRAME_CHILDREN_514, 1, 1, false, 0, {}}; static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, @@ -7968,15 +7953,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SchemaReservedIndex", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline, &FRAME_PLAN_56}, {"CatalogReservedSchemaIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_196}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_55}, {"DropSequence", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_197}, + &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_196}, {"DropCollation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_198}, + &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_197}, {"DropType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_199}, + &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_198}, {"DropSecret", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_200}, + &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_199}, {"TableOrView", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MaterializedViewEntry", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7998,21 +7983,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DropSecretStorage", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline, &FRAME_PLAN_12}, {"ExecuteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_201}, + &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_200}, {"ExplainStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_202}, + &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_201}, {"ExplainOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_203}, + &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_202}, {"ExplainOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_204}, + &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_203}, {"ExplainOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_205}, + &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_204}, {"ExplainSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_206}, + &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_205}, {"ExplainableStatements", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_207}, + &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_206}, {"ExportSource", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExportSourceTrampoline, &FRAME_PLAN_12}, {"ExportOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8022,27 +8007,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ColumnReference", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeColumnReferenceTrampoline, &FRAME_PLAN_1}, {"NestedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_208}, + &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_207}, {"CatalogReservedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_209}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_208}, {"SchemaReservedTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_210}, + &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_209}, {"TableReservedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_211}, + &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_210}, {"FunctionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_212}, + &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_211}, {"FunctionExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_213}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_212}, {"FunctionExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_214}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_213}, {"FunctionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_215}, + &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_214}, {"FunctionIdentifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"CatalogReservedSchemaFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_216}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_215}, {"SchemaReservedFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline, &FRAME_PLAN_56}, {"DistinctOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8052,11 +8037,11 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AllKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAllKeywordTrampoline, &FRAME_PLAN_12}, {"WithinGroupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_217}, + &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_216}, {"FilterClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_218}, + &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_217}, {"FilterClauseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_219}, + &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_218}, {"FilterClauseContents", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline, &FRAME_PLAN_21}, {"IgnoreOrRespectNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8078,9 +8063,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FalseLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFalseLiteralTrampoline, &FRAME_PLAN_12}, {"CastExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_220}, + &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_219}, {"CastArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_221}, + &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_220}, {"CastOrTryCast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8090,45 +8075,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ColIdDot", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeColIdDotTrampoline, &FRAME_PLAN_83}, {"StarExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_222}, + &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_221}, {"StarQualifierList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_223}, + &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_222}, {"ExcludeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_224}, + &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_223}, {"ExcludeNames", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_225}, + &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_224}, {"ExcludeNameSingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_226}, + &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_225}, {"ExcludeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeDottedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_227}, + &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_226}, {"ExcludeColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline, &FRAME_PLAN_38}, {"ReplaceList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_228}, + &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_227}, {"ReplaceEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReplaceEntrySingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_229}, + &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_228}, {"ReplaceEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_230}, + &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_229}, {"ReplaceEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_231}, + &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_230}, {"RenameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_232}, + &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_231}, {"RenameEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RenameEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_233}, + &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_232}, {"SingleRenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_234}, + &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_233}, {"RenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_226}, + &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_225}, {"SubqueryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_235}, + &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_234}, {"SubqueryNot", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryNotTrampoline, &FRAME_PLAN_12}, {"SubqueryExists", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8136,29 +8121,29 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CaseExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_236}, + &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_235}, {"SearchedCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_237}, + &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_236}, {"SimpleCaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_238}, + &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_237}, {"SimpleCaseWhenOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleCaseWhenEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline, &FRAME_PLAN_31}, {"CaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_239}, + &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_238}, {"CaseElse", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCaseElseTrampoline, &FRAME_PLAN_21}, {"TypeLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTypeLiteralTrampoline, &FRAME_PLAN_162}, {"IntervalLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_240}, + &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_239}, {"IntervalParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IntervalStringParameter", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline, &FRAME_PLAN_12}, {"FrameClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_241}, + &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_240}, {"Framing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeFramingTrampoline, &FRAME_PLAN_19}, {"RowsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8170,15 +8155,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FrameExtent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SingleFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_242}, + &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_241}, {"BetweenFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_243}, + &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_242}, {"FrameBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FrameUnbounded", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_244}, + &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_243}, {"FrameExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_245}, + &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_244}, {"FrameCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline, &FRAME_PLAN_12}, {"PrecedingOrFollowing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8188,7 +8173,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FollowingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFollowingFrameTrampoline, &FRAME_PLAN_12}, {"WindowExcludeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_246}, + &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_245}, {"WindowExcludeElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8210,37 +8195,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WindowFrameDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"WindowFrameNameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_247}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_246}, {"WindowFrameNameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_248}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_247}, {"WindowFrameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_249}, + &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_248}, {"WindowFrameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_250}, + &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_249}, {"BaseWindowName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline, &FRAME_PLAN_12}, {"WindowPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_251}, + &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_250}, {"ListExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ArrayBoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_252}, + &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_251}, {"ArrayParensSelect", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline, &FRAME_PLAN_163}, {"BoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_253}, + &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_252}, {"StructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_254}, + &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_253}, {"StructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_255}, + &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_254}, {"MapExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_256}, + &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_255}, {"MapStructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_257}, + &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_256}, {"MapStructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_258}, + &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_257}, {"GroupingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_259}, + &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_258}, {"GroupingOrGroupingId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupingKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8262,61 +8247,61 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DefaultExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline, &FRAME_PLAN_12}, {"ListComprehensionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_260}, + &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_259}, {"ListComprehensionFilter", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline, &FRAME_PLAN_21}, {"ParensExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_261}, + &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_260}, {"MeasureSemanticsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_262}, + &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_261}, {"SingleExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"Expression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_263}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_262}, {"ColumnDefaultExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_264}, + &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_263}, {"LogicalOrExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_265}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_264}, {"LogicalOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_266}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_265}, {"ColDefOrExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_267}, + &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_266}, {"ColDefOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_268}, + &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_267}, {"LogicalAndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_269}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_268}, {"LogicalAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_270}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_269}, {"ColDefAndExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_271}, + &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_270}, {"ColDefAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_272}, + &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_271}, {"LogicalNotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_273}, + &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_272}, {"NotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_274}, + &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_273}, {"NotKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_12}, {"IsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_275}, + &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_274}, {"IsExpressionContinuation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_276}, + &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_275}, {"IsExpressionTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsTestTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_277}, + &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_276}, {"IsDistinctTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_278}, + &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_277}, {"IsComparisonTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_279}, + &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_278}, {"IsOtherOperatorTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_280}, + &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_279}, {"IsCastTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_281}, + &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_280}, {"IsTest", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_282}, + &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_281}, {"IsLiteralValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UnknownLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8328,23 +8313,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsNull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullTrampoline, - &FRAME_PLAN_283}, + &FRAME_PLAN_282}, {"IsNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsDistinctFromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_284}, + &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_283}, {"IsDistinctFromTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_285}, + &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_284}, {"IsDistinctFromOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_12}, {"ComparisonExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_286}, + &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_285}, {"ComparisonExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_287}, + &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_286}, {"ComparisonOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NotComparisonOperand", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_288}, + &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_287}, {"ComparisonOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OperatorEqual", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8360,17 +8345,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OperatorGreaterThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_12}, {"BetweenInLikeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_289}, + &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_288}, {"InPredicate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_290}, + &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_289}, {"BetweenLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_291}, + &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_290}, {"BetweenLikeOpExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LikeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_291}, {"EscapeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_292}, {"LikeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, &FRAME_PLAN_19}, {"LikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8394,43 +8379,43 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotSimilarToOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_12}, {"InClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_293}, {"InExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InContainsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_294}, {"InExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_295}, {"InSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_296}, {"BetweenClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_297}, {"OtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_299}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_298}, {"InfixOtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_300}, + &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_299}, {"OtherOperatorTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllSubqueryTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_301}, + &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_300}, {"OtherOperatorExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_302}, + &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_301}, {"SingleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_303}, + &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_302}, {"SingleArrowBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ArrowChainBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_304}, + &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_303}, {"ArrowChainTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DoubleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_305}, + &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_304}, {"ArrowFullBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_263}, + &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_262}, {"OtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllParsedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_306}, + &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_305}, {"NamedOtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, &FRAME_PLAN_54}, {"OperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8438,7 +8423,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AnyOperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_12}, {"AnyAllOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_307}, + &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_306}, {"AnyOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubqueryAny", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8446,49 +8431,49 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SubqueryAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_12}, {"QualifiedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_308}, + &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_307}, {"QualifiedOperatorContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_309}, + &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_308}, {"BitwiseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_310}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_309}, {"BitwiseExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_311}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_310}, {"BitOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_12}, {"TildeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_312}, + &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_311}, {"AdditiveExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_313}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_312}, {"AdditiveExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_314}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_313}, {"Term", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTermTrampoline, &FRAME_PLAN_12}, {"MultiplicativeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_315}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_314}, {"MultiplicativeExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_316}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_315}, {"Factor", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFactorTrampoline, &FRAME_PLAN_12}, {"ExponentiationExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_317}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_316}, {"ExponentiationExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_318}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_317}, {"ExponentOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_12}, {"CollateExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_319}, + &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_318}, {"CollateExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_320}, + &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_319}, {"AtTimeZoneExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_321}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_320}, {"AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_322}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_321}, {"UnaryExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_323}, + &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_322}, {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_19}, {"MinusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8498,9 +8483,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TildePrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_12}, {"BaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_324}, + &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_323}, {"IndirectionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_325}, + &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_324}, {"Indirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8508,27 +8493,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DotOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DotMethodOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_326}, + &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_325}, {"DotColumnOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_147}, {"MethodExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_327}, + &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_326}, {"MethodExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_328}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_327}, {"MethodExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_329}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_328}, {"MethodFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_215}, + &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_214}, {"SliceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_330}, + &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_329}, {"SliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_331}, + &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_330}, {"SliceUpperBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MinusStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_332}, + &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_331}, {"EndStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_333}, + &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_332}, {"EndSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_66}, {"StepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8538,47 +8523,47 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SpecialFunctionExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CoalesceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_334}, + &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_333}, {"UnpackExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_134}, {"TryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_134}, {"ColumnsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_335}, + &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_334}, {"ExtractExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_336}, + &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_335}, {"ExtractArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_337}, + &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_336}, {"LambdaExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_338}, + &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_337}, {"NullIfExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_338}, {"NullIfArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_258}, + &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_257}, {"PositionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_339}, {"PositionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_341}, + &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_340}, {"RowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_342}, + &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_341}, {"SubstringExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_342}, {"SubstringArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_343}, {"SubstringParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_344}, {"SubstringFromFor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringFromOptionalFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_346}, + &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_345}, {"SubstringFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_347}, + &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_346}, {"TrimExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_348}, + &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_347}, {"TrimArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_349}, + &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_348}, {"TrimDirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, &FRAME_PLAN_19}, {"TrimBoth", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8588,23 +8573,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TrimTrailing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_12}, {"TrimSource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_350}, + &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_349}, {"OverlayExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_351}, + &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_350}, {"OverlayArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OverlayParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_352}, + &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_351}, {"FromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_21}, {"ForExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_21}, {"OverlayExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_343}, {"ExtractArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExtractDatePartArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_353}, + &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_352}, {"ExtractIdentifierArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_12}, {"ExtractStringArgument", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8614,25 +8599,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ExternalResourceStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_354}, + &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_353}, {"RegisterExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_355}, + &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_354}, {"DestroyExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_356}, + &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_355}, {"ExternalResourceCreationOptions", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_33}, {"AttachToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_357}, + &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_356}, {"ConnectToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_358}, + &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_357}, {"ExternalResourceSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExternalResourceCreateClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_359}, + &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_358}, {"ExternalResourceReferenceClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_32}, {"InsertStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_360}, + &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_359}, {"OrAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertOrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8642,15 +8627,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ByNameOrPosition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertByNameOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_361}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_360}, {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_362}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_361}, {"InsertByName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_12}, {"InsertByPosition", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_12}, {"InsertTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_363}, + &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_362}, {"InsertAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_12}, {"ColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8660,31 +8645,31 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"InsertValues", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectInsertValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_206}, + &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_205}, {"DefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_12}, {"OnConflictClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_364}, + &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_363}, {"OnConflictTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictExpressionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_365}, + &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_364}, {"OnConflictIndexTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_366}, + &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_365}, {"OnConflictAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_367}, + &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_366}, {"OnConflictNothing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_12}, {"ReturningClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_368}, + &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_367}, {"LoadStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_369}, + &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_368}, {"ExtensionAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_12}, {"InstallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_370}, + &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_369}, {"InstallAndLoad", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_12}, {"UpdateExtensionsStatement", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8692,57 +8677,57 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FromSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FromSourceIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_371}, + &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_370}, {"FromSourceString", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_12}, {"FromSourceName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_372}, + &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_371}, {"VersionNumber", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_373}, + &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_372}, {"ExtensionRepositoryStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_374}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_373}, {"RepositoryPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_12}, {"RepositoryPublicKey", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_12}, {"CreateExtensionRepositoryFromHostStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, &FRAME_PLAN_375}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, &FRAME_PLAN_374}, {"DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_376}, + &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_375}, {"ExtensionRepositoryName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline, &FRAME_PLAN_149}, {"ExtensionRepositoryHostName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtensionRepositoryHostNameTrampoline, &FRAME_PLAN_377}, + &PEGTransformerFactory::FinalizeExtensionRepositoryHostNameTrampoline, &FRAME_PLAN_376}, {"TableMatchRecognizeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_378}, + &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_377}, {"MatchRecognizeBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_379}, + &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_378}, {"MatchRecognizeClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MRPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_380}, + &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_379}, {"MROrderBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_381}, + &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_380}, {"MRMeasures", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_382}, + &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_381}, {"MRRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRRowsTrampoline, - &FRAME_PLAN_383}, + &FRAME_PLAN_382}, {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, - &FRAME_PLAN_384}, + &FRAME_PLAN_383}, {"MRPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_385}, + &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_384}, {"MRSubset", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_386}, + &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_385}, {"MRDefineAuto", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_12}, {"MRDefine", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_387}, + &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_386}, {"MeasuresClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_388}, + &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_387}, {"MeasuresElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_389}, + &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_388}, {"MeasureSemantics", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RunningSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8754,7 +8739,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OneRowPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_12}, {"AllRowsPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_390}, + &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_389}, {"AllRowsEmptyMatches", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ShowEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8764,7 +8749,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WithUnmatchedRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_12}, {"AfterMatchSkip", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_391}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_390}, {"AfterMatchSkipTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SkipToNextRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8772,25 +8757,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SkipPastLastRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_12}, {"SkipToFirstVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_392}, + &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_391}, {"SkipToLastVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_392}, + &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_391}, {"SkipToVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_393}, + &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_392}, {"PatternClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_394}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_393}, {"RowPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_395}, + &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_394}, {"RowPatternAlternative", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_396}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_395}, {"RowPatternTerm", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_397}, + &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_396}, {"RowPatternFactor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_398}, + &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_397}, {"RowPatternPrimary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RowPatternPermute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_399}, + &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_398}, {"RowPatternAnchor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PatternStart", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8798,15 +8783,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PatternEnd", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_12}, {"RowPatternGroup", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_400}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_399}, {"RowPatternEmpty", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_12}, {"RowPatternExclusion", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_401}, + &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_400}, {"RowPatternLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_402}, + &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_401}, {"RowPatternQuantifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_403}, + &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_402}, {"RowPatternQuantifierKind", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierReluctant", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8818,7 +8803,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierOptional", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_12}, {"QuantifierRange", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_404}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_403}, {"QuantifierBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8830,55 +8815,55 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierExact", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_12}, {"SubsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_405}, + &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_404}, {"SubsetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_406}, + &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_405}, {"DefineClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_407}, + &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_406}, {"DefineElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_408}, + &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_407}, {"MergeIntoStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_409}, + &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_408}, {"MergeIntoUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_410}, + &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_409}, {"MergeMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_411}, + &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_410}, {"MatchedClauseAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_412}, + &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_411}, {"UpdateMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchSetAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_413}, + &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_412}, {"UpdateByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_414}, + &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_413}, {"DeleteMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_12}, {"InsertMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_414}, {"InsertMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertDefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_12}, {"InsertByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_415}, {"InsertValuesList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_417}, + &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_416}, {"DoNothingMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_12}, {"ErrorMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_66}, {"UpdateMatchSetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_418}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_417}, {"UpdateMatchSetInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_80}, {"AndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_21}, {"NotMatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_419}, + &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_418}, {"BySourceOrTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BySource", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8888,27 +8873,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PivotStatement", &PEGTransformerFactory::InitializePivotStatementTrampoline, &PEGTransformerFactory::FinalizePivotStatementTrampoline, nullptr}, {"PivotOn", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotOnTrampoline, - &FRAME_PLAN_420}, + &FRAME_PLAN_419}, {"PivotUsing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_368}, + &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_367}, {"PivotColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_421}, + &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_420}, {"PivotColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotColumnExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_31}, {"PivotColumnSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_422}, + &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_421}, {"UnpivotStatement", &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline, nullptr}, {"IntoNameValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_422}, {"OptionalParensNameList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ParenthesizedNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_423}, {"BareNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_424}, {"IncludeOrExcludeNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IncludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8920,41 +8905,41 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"UnpivotHeaderSingle", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_38}, {"UnpivotHeaderList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_423}, {"PragmaStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_426}, + &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_425}, {"PragmaAssignOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PragmaAssign", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_427}, + &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_426}, {"PragmaFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_428}, + &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_427}, {"PragmaParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_295}, {"PrepareStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_429}, + &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_428}, {"TypeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_430}, + &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_429}, {"SelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_206}, + &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_205}, {"SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline, nullptr}, {"SelectSetOpChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_431}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_430}, {"SelectSetOpChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_432}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_431}, {"IntersectChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_433}, + &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_432}, {"IntersectChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_434}, + &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_433}, {"SetIntersectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_435}, + &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_434}, {"SelectAtom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_296}, {"SetopClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_436}, + &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_435}, {"SetopType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetopUnion", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8964,107 +8949,107 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SelectStatementType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResultModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_437}, + &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_436}, {"LimitOffset", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LimitOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_438}, + &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_437}, {"OffsetLimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_439}, + &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_438}, {"OffsetFetchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_440}, + &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_439}, {"FetchOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_441}, + &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_440}, {"FetchOnlyClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_442}, + &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_441}, {"TableStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_443}, + &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_442}, {"OptionalParensSimpleSelect", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleSelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_444}, + &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_443}, {"SimpleSelect", &PEGTransformerFactory::InitializeSimpleSelectTrampoline, &PEGTransformerFactory::FinalizeSimpleSelectTrampoline, nullptr}, {"SelectFrom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectFromClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_445}, + &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_444}, {"FromSelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_446}, + &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_445}, {"WithStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_447}, + &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_446}, {"CTEBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CTESelectBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_296}, {"CTEDMLBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_448}, + &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_447}, {"UsingKey", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_449}, + &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_448}, {"Materialized", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_12}, {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, &PEGTransformerFactory::FinalizeWithClauseTrampoline, nullptr}, {"SelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_450}, + &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_449}, {"TargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_451}, + &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_450}, {"ColumnAliases", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_423}, {"DistinctClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DistinctAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_12}, {"DistinctOn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_452}, + &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_451}, {"DistinctOnTargets", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_334}, + &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_333}, {"InnerTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, &PEGTransformerFactory::FinalizeTableRefTrampoline, nullptr}, {"TableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_453}, + &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_452}, {"BaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_454}, + &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_453}, {"TableAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_38}, {"ValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_455}, + &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_454}, {"ParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_456}, + &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_455}, {"JoinedTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"JoinedTableRefChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_457}, + &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_456}, {"JoinOrPivot", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TablePivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_458}, + &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_457}, {"TablePivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_459}, + &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_458}, {"PivotGroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_460}, + &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_459}, {"TableUnpivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_461}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_460}, {"TableUnpivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_462}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_461}, {"PivotHeader", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_463}, + &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_462}, {"PivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_464}, + &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_463}, {"PivotValueTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotEnumTarget", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_12}, {"PivotListTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_465}, + &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_464}, {"UnpivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_466}, + &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_465}, {"PivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_467}, + &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_466}, {"UnpivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_467}, + &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_466}, {"Lateral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeLateralTrampoline, &FRAME_PLAN_12}, {"BaseTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9080,37 +9065,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableFunctionLateralOpt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_468}, + &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_467}, {"TableFunctionAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_469}, + &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_468}, {"WithOrdinality", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_12}, {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CatalogReservedSchemaTableFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_470}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_469}, {"TableFunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"TableFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_471}, + &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_470}, {"FunctionArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NamedFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_472}, + &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_471}, {"PositionalFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_31}, {"NamedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_473}, + &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_472}, {"TableAlias", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableAliasAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_474}, + &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_473}, {"TableAliasWithoutAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_475}, + &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_474}, {"AtClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_476}, + &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_475}, {"AtSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_477}, + &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_476}, {"AtUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_19}, {"VersionAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9122,21 +9107,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestJoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestJoinAliased", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_478}, + &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_477}, {"NearestJoinBare", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_479}, + &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_478}, {"NearestBareTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_480}, + &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_479}, {"NearestTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_481}, + &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_480}, {"NearestTableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_482}, + &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_481}, {"NearestBaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_483}, + &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_482}, {"NearestParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_484}, + &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_483}, {"ApproxOrExact", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestApprox", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9150,19 +9135,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestSimilarity", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_12}, {"RegularJoinClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_485}, + &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_484}, {"JoinByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_486}, + &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_485}, {"Asof", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAsofTrampoline, &FRAME_PLAN_12}, {"JoinWithoutOnClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_487}, + &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_486}, {"JoinQualifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_21}, {"UsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_488}, + &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_487}, {"UsingColumnName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, &FRAME_PLAN_149}, {"JoinType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9172,7 +9157,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CrossJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_12}, {"NaturalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_489}, + &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_488}, {"PositionalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_12}, {"FullJoin", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9192,35 +9177,35 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WhereClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_21}, {"GroupByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_490}, + &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_489}, {"HavingClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_21}, {"QualifyClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_21}, {"SampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_491}, + &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_490}, {"SelectSampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_491}, + &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_490}, {"WindowClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_492}, + &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_491}, {"WindowDefinition", &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline, nullptr}, {"SampleEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleEntryCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_493}, + &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_492}, {"SampleEntryFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_494}, + &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_493}, {"SampleFunction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_83}, {"SampleProperties", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_495}, + &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_494}, {"RepeatableSample", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_496}, + &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_495}, {"SampleSeed", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_12}, {"SampleCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_497}, + &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_496}, {"SampleValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9234,7 +9219,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GroupByAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_12}, {"GroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_498}, + &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_497}, {"GroupByExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupByBaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9242,7 +9227,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"EmptyGroupingItem", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_12}, {"CubeOrRollupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_499}, + &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_498}, {"CubeOrRollup", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, &FRAME_PLAN_19}, {"CubeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9250,9 +9235,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"RollupKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_12}, {"GroupingSetsClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_500}, + &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_499}, {"SubqueryReference", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_296}, {"OrderByExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_98}, {"DescOrAsc", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9268,17 +9253,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NullsLast", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_12}, {"OrderByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_501}, + &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_500}, {"OrderByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OrderByExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_501}, {"OrderByAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_502}, {"LimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_504}, + &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_503}, {"OffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_505}, + &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_504}, {"OffsetValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_31}, {"LimitValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9294,45 +9279,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FetchClauseWithoutValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_12}, {"FetchClauseWithValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_506}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_505}, {"FetchValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_31}, {"AliasedExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ColIdExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_507}, + &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_506}, {"ExpressionAsCollabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_389}, + &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_388}, {"ExpressionOptIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_31}, {"ValuesClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_508}, + &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_507}, {"ValuesExpressions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_295}, {"SetStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetKeywordStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_509}, + &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_508}, {"VariableAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_510}, + &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_509}, {"SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_510}, {"ResetTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_511}, {"ResetVariableOrSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_512}, {"SetSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_511}, {"StandardAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_514}, + &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_513}, {"SetVariableOrSetting", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_515}, + &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_514}, {"ZoneValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ZoneLocal", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9344,13 +9329,13 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ZoneIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_12}, {"ZoneIntervalWithInterval", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_516}, + &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_515}, {"ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_12}, {"SetSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_511}, {"SetVariable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_517}, + &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_516}, {"VariableScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_12}, {"SettingScope", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9362,19 +9347,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GlobalScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_12}, {"SetAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_518}, + &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_517}, {"VariableList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_343}, {"TransactionStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BeginTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_519}, + &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_518}, {"RollbackTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_12}, {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_12}, {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_520}, + &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_519}, {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReadOnly", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9382,27 +9367,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ReadWrite", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_12}, {"UpdateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_521}, + &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_520}, {"UpdateTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BaseTableSet", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_182}, {"BaseTableAliasSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_522}, + &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_521}, {"UpdateAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_32}, {"UpdateSetClauseList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_523}, + &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_522}, {"UpdateSetClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateSetTuple", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_17}, {"UpdateSetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_524}, + &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_523}, {"UpdateSetColumnTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_525}, + &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_524}, {"UseStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_526}, + &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_525}, {"UseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SchemaNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9410,21 +9395,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CatalogNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, &FRAME_PLAN_54}, {"UseTargetCatalogSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_527}, + &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_526}, {"DotIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_12}, {"VacuumStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_528}, + &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_527}, {"VacuumOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"VacuumParensOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_529}, + &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_528}, {"VacuumLegacyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_530}, + &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_529}, {"VacuumOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, &FRAME_PLAN_19}, {"OptAnalyze", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_531}, + &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_530}, {"OptFull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptFullTrampoline, &FRAME_PLAN_12}, {"OptFreeze", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9432,7 +9417,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OptVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_12}, {"NameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_423}, }; static case_insensitive_map_t BuildGeneratedTransformFrameOps() { @@ -9851,13 +9836,25 @@ arena_ptr PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline(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(); + if (dynamic_repeat_opt.HasResult()) { + auto &dynamic_repeat_pr = dynamic_repeat_opt.GetResult().Cast(); + auto dynamic_repeat_children = dynamic_repeat_pr.GetChildren(); + dynamic_child_count = dynamic_repeat_children.size(); + } optional catalog_qualification {}; if (process.child_results[0]) { catalog_qualification = process.TakeResult(0); } - optional schema_qualification {}; - if (process.child_results[1]) { - schema_qualification = process.TakeResult(1); + optional> schema_qualification {}; + if (dynamic_child_count > 0) { + vector schema_qualification_value; + schema_qualification_value.reserve(dynamic_child_count); + for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { + schema_qualification_value.push_back(process.TakeResult(i)); + } + schema_qualification = std::move(schema_qualification_value); } auto sequence_name = list_pr.GetChild(2).Cast().identifier; auto result = @@ -13427,8 +13424,15 @@ arena_ptr PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); + auto &dynamic_repeat_pr = list_pr.GetChild(1).Cast(); + auto dynamic_repeat_children = dynamic_repeat_pr.GetChildren(); + auto dynamic_child_count = dynamic_repeat_children.size(); auto catalog_qualification = process.TakeResult(0); - auto reserved_schema_qualification = process.TakeResult(1); + vector reserved_schema_qualification; + reserved_schema_qualification.reserve(dynamic_child_count); + for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { + reserved_schema_qualification.push_back(process.TakeResult(i)); + } auto reserved_index_name = list_pr.GetChild(2).Cast().identifier; auto result = TransformCatalogReservedSchemaIndex(transformer, catalog_qualification, reserved_schema_qualification, reserved_index_name); diff --git a/src/duckdb/src/parser/peg/transformer/transform_use.cpp b/src/duckdb/src/parser/peg/transformer/transform_use.cpp index 67b487a30..2e586ae63 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_use.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_use.cpp @@ -6,14 +6,7 @@ namespace duckdb { // UseStatement <- 'USE' UseTarget unique_ptr PEGTransformerFactory::TransformUseStatement(PEGTransformer &transformer, const QualifiedName &use_target) { - string value_str; - if (IsInvalidSchema(use_target.Schema())) { - value_str = SQLIdentifier::ToString(use_target.Name()); - } else { - value_str = SQLIdentifier(use_target.Schema()) + "." + SQLIdentifier(use_target.Name()); - } - - auto value_expr = ConstantExpression::String(value_str); + auto value_expr = ConstantExpression::String(use_target.ToString()); return make_uniq("schema", std::move(value_expr), SetScope::AUTOMATIC); } @@ -35,11 +28,11 @@ QualifiedName PEGTransformerFactory::TransformUseTargetCatalogSchema(PEGTransformer &transformer, const Identifier &catalog_name, const Identifier &reserved_schema_name, const optional> &dot_identifier) { - if (dot_identifier && !dot_identifier->empty()) { - throw ParserException("Expected \"USE database\" or \"USE database.schema\""); + vector path {catalog_name, reserved_schema_name}; + if (dot_identifier) { + path.insert(path.end(), dot_identifier->begin(), dot_identifier->end()); } - QualifiedName result({catalog_name}, reserved_schema_name); - return result; + return QualifiedName::FromPath(std::move(path)); } Identifier PEGTransformerFactory::TransformDotIdentifier(PEGTransformer &transformer, const Identifier &identifier) { diff --git a/src/duckdb/src/parser/tableref/showref.cpp b/src/duckdb/src/parser/tableref/showref.cpp index f29b49574..bc0307de6 100644 --- a/src/duckdb/src/parser/tableref/showref.cpp +++ b/src/duckdb/src/parser/tableref/showref.cpp @@ -22,16 +22,7 @@ string ShowRef::ToString() const { if (show_type == ShowType::SUMMARY) { result += "SUMMARIZE "; } else if (show_type == ShowType::SHOW_FROM) { - result += "SHOW TABLES FROM "; - string name = ""; - if (!GetCatalogName().empty()) { - name += SQLIdentifier(GetCatalogName()); - if (!GetSchemaName().empty()) { - name += "."; - } - } - name += SQLIdentifier(GetSchemaName()); - result += name; + result += "SHOW TABLES FROM " + qualified_name.Parent().ToString(); } else { result += "DESCRIBE "; } diff --git a/src/duckdb/src/planner/binder.cpp b/src/duckdb/src/planner/binder.cpp index 580ac0109..1cbfd2dc9 100644 --- a/src/duckdb/src/planner/binder.cpp +++ b/src/duckdb/src/planner/binder.cpp @@ -302,6 +302,21 @@ bool Binder::IsBindingIndexKey() const { return binding_index_key; } +DecimalWidthLimit Binder::GetDecimalWidthLimit() const { + if (decimal_width_limit) { + return *decimal_width_limit; + } + return DecimalWidthLimit::FromSetting(context); +} + +optional_ptr Binder::GetFixedDecimalWidthLimit() const { + return decimal_width_limit; +} + +void Binder::SetDecimalWidthLimit(optional_ptr limit) { + decimal_width_limit = limit; +} + 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 f0b54378d..96ab57732 100644 --- a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp @@ -70,6 +70,10 @@ static Value NegatePercentileValue(const Value &v, const bool desc) { const auto &type = v.type(); switch (type.id()) { case LogicalTypeId::DECIMAL: { + if (type.InternalType() == PhysicalType::VARCHAR) { + // a wide decimal has no HUGEINT representation, the quantile handles it as DOUBLE + return Value::DOUBLE(-v.GetValue()); + } // Negate DECIMALs as DECIMAL. const auto integral = IntegralValue::Get(v); const auto width = DecimalType::GetWidth(type); diff --git a/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp index 8cb1adfa9..e3e89e046 100644 --- a/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp @@ -26,14 +26,15 @@ BindResult ExpressionBinder::BindExpression(BetweenExpression &expr, idx_t depth // cast the input types to the same type // now obtain the result type of the input types LogicalType input_type; + const auto decimal_width_limit = binder.GetDecimalWidthLimit(); if (!BoundComparisonExpression::TryBindComparison(context, input_sql_type, lower_sql_type, input_type, - expr.GetExpressionType())) { + expr.GetExpressionType(), decimal_width_limit)) { throw BinderException(expr, "Cannot mix values of type %s and %s in BETWEEN clause - an explicit cast is required", input_sql_type.ToString(), lower_sql_type.ToString()); } if (!BoundComparisonExpression::TryBindComparison(context, input_type, upper_sql_type, input_type, - expr.GetExpressionType())) { + expr.GetExpressionType(), decimal_width_limit)) { throw BinderException(expr, "Cannot mix values of type %s and %s in BETWEEN clause - an explicit cast is required", input_type.ToString(), upper_sql_type.ToString()); diff --git a/src/duckdb/src/planner/binder/expression/bind_case_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_case_expression.cpp index 451c7b8b6..4bc6bd7c0 100644 --- a/src/duckdb/src/planner/binder/expression/bind_case_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_case_expression.cpp @@ -22,9 +22,10 @@ BindResult ExpressionBinder::BindExpression(CaseExpression &expr, idx_t depth) { // the children have been successfully resolved // figure out the result type of the CASE expression auto return_type = ExpressionBinder::GetExpressionReturnType(*else_expr); + const auto decimal_width_limit = binder.GetDecimalWidthLimit(); for (auto &check : checks) { auto then_type = ExpressionBinder::GetExpressionReturnType(*check.second); - if (!LogicalType::TryGetMaxLogicalType(context, return_type, then_type, return_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, return_type, then_type, return_type, decimal_width_limit)) { throw BinderException( expr, "Cannot mix values of type %s and %s in CASE expression - an explicit cast is required", return_type.ToString(), then_type.ToString()); 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 72d3a6d5a..ef8e37c5e 100644 --- a/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp @@ -62,6 +62,14 @@ static bool SwitchVarcharComparison(const LogicalType &type) { bool BoundComparisonExpression::TryBindComparison(ClientContext &context, const LogicalType &left_type, const LogicalType &right_type, LogicalType &result_type, ExpressionType comparison_type) { + return TryBindComparison(context, left_type, right_type, result_type, comparison_type, + DecimalWidthLimit::FromSetting(context)); +} + +bool BoundComparisonExpression::TryBindComparison(ClientContext &context, const LogicalType &left_type, + const LogicalType &right_type, LogicalType &result_type, + ExpressionType comparison_type, + const DecimalWidthLimit &decimal_width_limit) { LogicalType res; bool is_equality; switch (comparison_type) { @@ -78,9 +86,9 @@ bool BoundComparisonExpression::TryBindComparison(ClientContext &context, const break; } if (is_equality) { - res = LogicalType::ForceMaxLogicalType(context, left_type, right_type); + res = LogicalType::ForceMaxLogicalType(context, left_type, right_type, decimal_width_limit); } else { - if (!LogicalType::TryGetMaxLogicalType(context, left_type, right_type, res)) { + if (!LogicalType::TryGetMaxLogicalType(context, left_type, right_type, res, decimal_width_limit)) { return false; } } @@ -88,7 +96,7 @@ 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}; - uint32_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, max_decimal_width = 0; for (idx_t i = 0; i < argument_types.size(); i++) { uint32_t width, scale; auto can_convert = argument_types[i].GetDecimalProperties(width, scale); @@ -97,15 +105,19 @@ bool BoundComparisonExpression::TryBindComparison(ClientContext &context, const return true; } max_width = MaxValue(width, max_width); + if (argument_types[i].id() == LogicalTypeId::DECIMAL) { + max_decimal_width = MaxValue(width, max_decimal_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); - if (max_width > Decimal::MAX_WIDTH_DECIMAL) { + idx_t required_width = MaxValue(idx_t(max_scale) + max_width_over_scale, max_width); + const idx_t width_limit = decimal_width_limit.ResultWidth(max_decimal_width); + if (required_width > width_limit) { // target width does not fit in decimal: truncate the scale (if possible) to try and make it fit - max_width = Decimal::MAX_WIDTH_DECIMAL; + required_width = width_limit; } - res = LogicalType::DECIMAL(max_width, max_scale); + res = LogicalType::DECIMAL(NumericCast(required_width), max_scale); break; } case LogicalTypeId::VARCHAR: @@ -161,7 +173,7 @@ unique_ptr ExpressionBinder::CreateBoundComparison(ExpressionType co unique_ptr left, unique_ptr right, ErrorData &error) { try { - return BoundComparisonExpression::Bind(context, comparison_type, std::move(left), std::move(right)); + return BoundComparisonExpression::Bind(context, comparison_type, std::move(left), std::move(right), binder); } catch (const std::exception &ex) { error = ErrorData(ex); return nullptr; diff --git a/src/duckdb/src/planner/binder/expression/bind_constant_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_constant_expression.cpp index 9be98fbb8..2bdc5e187 100644 --- a/src/duckdb/src/planner/binder/expression/bind_constant_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_constant_expression.cpp @@ -1,11 +1,25 @@ +#include "duckdb/common/types/decimal.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression_binder.hpp" +#include "duckdb/planner/binder.hpp" namespace duckdb { BindResult ExpressionBinder::BindExpression(ConstantExpression &expr, idx_t depth) { - return BindResult(make_uniq(expr.GetLiteral().ToValue())); + auto value = expr.GetLiteral().ToValue(); + if (value.type().id() == LogicalTypeId::DECIMAL) { + // a literal wider than the max_decimal_width setting is refused like a wider type: binding it to another type + // would change its value with the setting + const auto width = DecimalType::GetWidth(value.type()); + const auto limit = binder.GetDecimalWidthLimit(); + if (width > limit.width) { + return BindResult( + BinderException(expr, "Decimal literal of %u digits exceeds the maximum DECIMAL width of %u (%s)", + width, limit.width, limit.hint)); + } + } + return BindResult(make_uniq(std::move(value))); } } // namespace duckdb diff --git a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp index ba0354dea..65dca756a 100644 --- a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp @@ -126,8 +126,8 @@ static void CastDecimalLambdaToAccumulatorType(ClientContext &context, BindResul rebound_lambda_expr.LambdaExprMutable() = std::move(cast_expr); } -ListReduceRebindResult MaybeRebindListReduceLambda(ClientContext &context, idx_t depth, - const vector &function_child_types, +ListReduceRebindResult MaybeRebindListReduceLambda(ClientContext &context, const DecimalWidthLimit &decimal_width_limit, + idx_t depth, const vector &function_child_types, bind_lambda_function_t bind_lambda_function, BindResult &bind_lambda_result, const bind_lambda_expression_t &bind_lambda_expression, @@ -154,12 +154,14 @@ ListReduceRebindResult MaybeRebindListReduceLambda(ClientContext &context, idx_t LogicalType accumulator_type; if (has_initial) { const auto &initial_type = function_child_types[2]; - if (!LogicalType::TryGetMaxLogicalType(context, initial_type, lambda_return_type, accumulator_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, initial_type, lambda_return_type, accumulator_type, + decimal_width_limit)) { throw BinderException("No common super type between initial value type %s and lambda return type %s", initial_type.ToString(), lambda_return_type.ToString()); } } else { - if (!LogicalType::TryGetMaxLogicalType(context, list_child_type, lambda_return_type, accumulator_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, list_child_type, lambda_return_type, accumulator_type, + decimal_width_limit)) { throw BinderException("No common super type between list element type %s and lambda return type %s", list_child_type.ToString(), lambda_return_type.ToString()); } @@ -266,9 +268,9 @@ CatalogEntry &ExpressionBinder::BindFunction(FunctionExpression &function) { ColumnQualifier qualifier(binder, lambda_bindings); auto func = qualifier.QualifyFunction(function); if (!func) { + auto bound_name = Binder::BindTableName(binder.EntryRetriever(), function.GetQualifiedName()); // function was not found - check if we this is a table function (to throw a more helpful error message) - EntryLookupInfo table_function_lookup(CatalogType::TABLE_FUNCTION_ENTRY, function.GetQualifiedName(), - error_context); + EntryLookupInfo table_function_lookup(CatalogType::TABLE_FUNCTION_ENTRY, bound_name, error_context); auto table_func = GetCatalogEntry(table_function_lookup, OnEntryNotFound::RETURN_NULL); if (table_func) { throw BinderException(function, @@ -277,7 +279,7 @@ CatalogEntry &ExpressionBinder::BindFunction(FunctionExpression &function) { function.FunctionName()); } // not a table function - rebind to throw an error - EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, function.GetQualifiedName(), error_context); + EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, bound_name, error_context); func = GetCatalogEntry(function_lookup, OnEntryNotFound::THROW_EXCEPTION); } return *func; @@ -547,9 +549,9 @@ BindResult ExpressionBinder::BindLambdaFunction(FunctionExpression &function, Sc // list_reduce requires binding the lambda function a second time as there is a cyclical dependency between its // acc parameter type and its return type. This is resolved by initially binding it with acc = initial, and then // rebinding it with acc = return type - auto rebind_result = - MaybeRebindListReduceLambda(context, depth, function_child_types, bind_lambda_function, bind_lambda_result, - bind_lambda_expression, nullptr, lambda_expr_copy); + auto rebind_result = MaybeRebindListReduceLambda(context, binder.GetDecimalWidthLimit(), depth, + function_child_types, bind_lambda_function, bind_lambda_result, + bind_lambda_expression, nullptr, lambda_expr_copy); if (rebind_result.did_rebind) { capture_child_types = std::move(rebind_result.capture_child_types); override_bind_lambda_context = std::move(rebind_result.override_bind_lambda_context); diff --git a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp index 833e3b58f..0e92f4899 100644 --- a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp @@ -32,12 +32,13 @@ LogicalType ExpressionBinder::ResolveCoalesceType(OperatorExpression &op, vector LogicalType max_type = ExpressionBinder::GetExpressionReturnType(*children[0]); bool is_in_operator = (op.GetExpressionType() == ExpressionType::COMPARE_IN || op.GetExpressionType() == ExpressionType::COMPARE_NOT_IN); + const auto decimal_width_limit = binder.GetDecimalWidthLimit(); for (idx_t i = 1; i < children.size(); i++) { auto child_return = ExpressionBinder::GetExpressionReturnType(*children[i]); if (is_in_operator) { // If it's IN/NOT_IN operator, adjust DECIMAL and VARCHAR returned type. if (!BoundComparisonExpression::TryBindComparison(context, max_type, child_return, max_type, - op.GetExpressionType())) { + op.GetExpressionType(), decimal_width_limit)) { throw BinderException(op, "Cannot mix values of type %s and %s in %s clause - an explicit cast is required", max_type.ToString(), child_return.ToString(), @@ -45,7 +46,7 @@ LogicalType ExpressionBinder::ResolveCoalesceType(OperatorExpression &op, vector } } else { // If it's COALESCE operator, don't do extra adjustment. - if (!LogicalType::TryGetMaxLogicalType(context, max_type, child_return, max_type)) { + if (!LogicalType::TryGetMaxLogicalType(context, max_type, child_return, max_type, decimal_width_limit)) { throw BinderException( op, "Cannot mix values of type %s and %s in COALESCE operator - an explicit cast is required", max_type.ToString(), child_return.ToString()); diff --git a/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp index 22d7a9415..5dec7a246 100644 --- a/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_type_expression.cpp @@ -105,9 +105,10 @@ BindResult ExpressionBinder::BindExpression(TypeExpression &type_expr, idx_t dep bound_parameters.emplace_back(param->GetAlias().GetIdentifierName(), bound_param, location); }; - // Select the matching constructor and call it - auto result_type = - type_entry.constructors.Bind(context, type_entry.user_type, bound_parameters, type_expr.GetQueryLocation()); + // Select the matching constructor and call it, binding decimals within the limit of the binder + const auto decimal_width_limit = binder.GetDecimalWidthLimit(); + auto result_type = type_entry.constructors.Bind(context, type_entry.user_type, bound_parameters, + type_expr.GetQueryLocation(), &decimal_width_limit); // Return the resulting type! auto result_expr = diff --git a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp index 43c761e17..a346f94a9 100644 --- a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp @@ -44,6 +44,9 @@ static bool IsRangeType(const LogicalType &type) { case PhysicalType::DOUBLE: case PhysicalType::INTERVAL: return true; + case PhysicalType::VARCHAR: + // wide decimals are BIGNUM blobs whose byte order is their numeric order + return type.id() == LogicalTypeId::DECIMAL; default: return false; } diff --git a/src/duckdb/src/planner/binder/statement/bind_create.cpp b/src/duckdb/src/planner/binder/statement/bind_create.cpp index b4e40acc1..a1bfce806 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create.cpp @@ -176,14 +176,19 @@ void Binder::SearchSchema(CreateInfo &info) { // no catalog and no schema given: use the search path default for both auto &default_entry = search_path->GetDefault(); catalog = default_entry.GetCatalog(); - schema_path.push_back(default_entry.GetSchema()); + schema_path = default_entry.GetSchemaPath(); } else if (schema_path.empty()) { // a catalog was given but no schema: use the catalog's default schema - auto default_schema = search_path->GetDefaultSchema(context, catalog); - if (!default_schema) { - throw BinderException("Catalog %s has no default schema - specify a schema explicitly", catalog); + auto entries = search_path->GetEntriesForCatalog(catalog); + if (catalog != TEMP_CATALOG && !entries.empty()) { + schema_path = entries[0].GetSchemaPath(); + } else { + auto default_schema = search_path->GetDefaultSchema(context, catalog); + if (!default_schema) { + throw BinderException("Catalog %s has no default schema - specify a schema explicitly", catalog); + } + schema_path.push_back(*default_schema); } - schema_path.push_back(*default_schema); } else if (IsInvalidCatalog(catalog)) { // a schema was given but no catalog: resolve the catalog that holds it catalog = search_path->ResolveCatalog(schema_path[0]); @@ -264,12 +269,19 @@ QualifiedName Binder::BindTableName(CatalogEntryRetriever &retriever, const Qual EntryLookupInfo schema_lookup(CatalogType::SCHEMA_ENTRY, QualifiedName(schema_path[0])); auto schema = Catalog::GetSchema(retriever, schema_lookup, OnEntryNotFound::RETURN_NULL); if (schema) { - catalog = schema->ParentCatalog().GetName(); + catalog = schema->ParentCatalog().IsTemporaryCatalog() + ? retriever.GetSearchPath().ResolveCatalog(schema_path[0]) + : schema->ParentCatalog().GetName(); } else { catalog = DatabaseManager::GetDefaultDatabase(retriever.GetContext()); } } - return QualifiedName::FromCatalogSchema(std::move(catalog), std::move(schema_path), resolved.Name()); + auto result = QualifiedName::FromCatalogSchema(std::move(catalog), std::move(schema_path), resolved.Name()); + auto catalog_entry = Catalog::GetCatalogEntry(retriever, result.Catalog()); + if (catalog_entry) { + catalog_entry->CheckNestedSchemaSupport(result, CatalogType::TABLE_ENTRY); + } + return result; } QualifiedName Binder::BindTableName(const QualifiedName &name) { @@ -295,6 +307,7 @@ void Binder::BindCreateSchema(CreateSchemaInfo &info) { info.SetQualifiedName(ResolveCatalog(context, info.GetQualifiedName())); auto &resolved_catalog = Catalog::GetCatalog(context, info.SchemaCatalog()); + resolved_catalog.CheckNestedSchemaSupport(info.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); auto supports_create_schema = resolved_catalog.SupportsCreateSchema(info); if (supports_create_schema.HasError()) { supports_create_schema.Throw(); @@ -564,6 +577,26 @@ SchemaCatalogEntry &Binder::BindCreateFunctionInfo(CreateInfo &info) { } } + if (!info.temporary && attached.HasStorageManager()) { + // the parameter, default and return types are written to the catalog, and the stored expressions may cast + auto &storage_manager = attached.GetStorageManager(); + for (const auto &type : function->types) { + storage_manager.CheckDecimalWidthIsSupported(type); + } + for (const auto &default_value : default_values) { + storage_manager.CheckDecimalWidthIsSupported(default_value.second.type()); + } + storage_manager.CheckDecimalWidthIsSupported(function->return_type); + for (auto &default_parameter : function->default_parameters) { + storage_manager.CheckExpressionDecimalsAreSupported(*default_parameter.second); + } + if (info.type == CatalogType::MACRO_ENTRY) { + storage_manager.CheckExpressionDecimalsAreSupported(*function->Cast().expression); + } else { + storage_manager.CheckQueryDecimalsAreSupported(*function->Cast().query_node); + } + } + vector dummy_types; vector dummy_names; // positional parameters @@ -930,6 +963,13 @@ BoundStatement Binder::Bind(CreateStatement &stmt) { base.binding_mode = CreateViewBindingMode::SKIP_BINDING; } } + if (base.query && !base.temporary) { + // the query of the view is stored, so a cast in it may not target a decimal wider than the database stores + auto &attached = schema.ParentCatalog().GetAttached(); + if (!attached.IsTemporary() && attached.HasStorageManager()) { + attached.GetStorageManager().CheckQueryDecimalsAreSupported(*base.query->node); + } + } BindCreateViewInfo(base); result.plan = make_uniq(LogicalOperatorType::LOGICAL_CREATE_VIEW, std::move(stmt.info), &schema); break; @@ -1053,6 +1093,11 @@ BoundStatement Binder::Bind(CreateStatement &stmt) { SetCatalogLookupCallback(dependency_callback); // Bind the underlying type BindLogicalType(create_type_info.type); + // the type is written to the catalog + auto &attached = catalog.GetAttached(); + if (!create_type_info.temporary && attached.HasStorageManager()) { + attached.GetStorageManager().CheckDecimalWidthIsSupported(create_type_info.type); + } } break; } diff --git a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp index dbfeb1014..757fece59 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp @@ -590,9 +590,25 @@ static void BindCreateTableConstraints(CreateTableInfo &create_info, CatalogEntr D_ASSERT(fk.info.fk_keys.empty()); FindForeignKeyIndexes(create_info.columns, fk.fk_columns, fk.info.fk_keys); + auto reference = fk.referenced_table; + if (reference.Path().empty()) { + reference = fk.info.schema.empty() || fk.info.schema == schema.name + ? QualifiedName(fk.info.table) + : QualifiedName(Identifier(), fk.info.schema, fk.info.table); + } + auto resolved = Binder::ResolveCatalog(entry_retriever, reference, false); + auto &path = resolved.Path(); + auto catalog = path.front().empty() ? schema.ParentCatalog().GetName() : path.front(); + vector schema_path(path.begin() + 1, path.end() - 1); + if (schema_path.empty()) { + schema_path = schema.GetSchemaPath(); + } + auto fk_name = QualifiedName::FromCatalogSchema(std::move(catalog), std::move(schema_path), fk.info.table); + // Resolve the self-reference. - if (create_info.GetTableName() == fk.info.table) { + if (fk_name == schema.GetQualifiedName(create_info.GetTableName())) { fk.info.type = ForeignKeyType::FK_TYPE_SELF_REFERENCE_TABLE; + fk.referenced_table = QualifiedName(schema.GetSchemaPath(), fk.info.table); FindMatchingPrimaryKeyColumns(create_info.columns, create_info.constraints, fk); FindForeignKeyIndexes(create_info.columns, fk.pk_columns, fk.info.pk_keys); CheckForeignKeyTypes(create_info.columns, create_info.columns, fk); @@ -602,13 +618,6 @@ static void BindCreateTableConstraints(CreateTableInfo &create_info, CatalogEntr // Resolve the table reference in the same catalog/schema as the table being // created, so FK references work for external catalogs (not just the default). EntryLookupInfo table_lookup(CatalogType::TABLE_ENTRY, QualifiedName(fk.info.table)); - QualifiedName fk_name; - if (fk.info.schema.empty() || fk.info.schema == schema.name) { - // a foreign key can only reference a table in the same (possibly nested) schema - fk_name = schema.GetQualifiedName(fk.info.table); - } else { - fk_name = QualifiedName(Identifier::InvalidCatalog(), fk.info.schema, fk.info.table); - } auto table_entry = entry_retriever.GetEntry(EntryLookupInfo(table_lookup, fk_name)); if (table_entry->type == CatalogType::VIEW_ENTRY) { throw BinderException("cannot reference a VIEW with a FOREIGN KEY"); @@ -619,6 +628,7 @@ static void BindCreateTableConstraints(CreateTableInfo &create_info, CatalogEntr if (&pk_table_entry_ptr.schema != &schema) { throw BinderException("Creating foreign keys across different schemas or catalogs is not supported"); } + fk.referenced_table = QualifiedName(schema.GetSchemaPath(), fk.info.table); FindMatchingPrimaryKeyColumns(pk_table_entry_ptr.GetColumns(), pk_table_entry_ptr.GetConstraints(), fk); FindForeignKeyIndexes(pk_table_entry_ptr.GetColumns(), fk.pk_columns, fk.info.pk_keys); CheckForeignKeyTypes(pk_table_entry_ptr.GetColumns(), create_info.columns, fk); diff --git a/src/duckdb/src/planner/binder/statement/bind_drop.cpp b/src/duckdb/src/planner/binder/statement/bind_drop.cpp index 2127c2e2b..a38b00eeb 100644 --- a/src/duckdb/src/planner/binder/statement/bind_drop.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_drop.cpp @@ -48,6 +48,7 @@ BoundStatement Binder::Bind(DropStatement &stmt) { // dropping a schema is never read-only because there are no temporary schemas. The catalog is the leading // component of the resolved path ([catalog, parent schemas..., schema]) auto &catalog = Catalog::GetCatalog(context, stmt.info->GetQualifiedName().Path().front()); + catalog.CheckNestedSchemaSupport(stmt.info->GetQualifiedName(), CatalogType::SCHEMA_ENTRY); properties.RegisterDBModify(catalog, context, stmt.info->GetModifications()); break; } diff --git a/src/duckdb/src/planner/binder/tableref/bind_showref.cpp b/src/duckdb/src/planner/binder/tableref/bind_showref.cpp index b7ee04b12..60bffb812 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_showref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_showref.cpp @@ -16,6 +16,7 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/database_manager.hpp" #include "duckdb/main/extension_helper.hpp" #include "duckdb/main/extension_entries.hpp" #include "duckdb/logging/logger.hpp" @@ -194,52 +195,80 @@ BoundStatement Binder::BindDescribeTable(ShowRef &ref) { if (lname == "\"databases\"") { sql = PragmaShowDatabases(); } else if (lname == "\"schemas\"") { - sql = "SELECT " - " schema.database_name, " - " schema.schema_name, " - " ((select current_schema() = schema.schema_name) " - " and (select current_database() = schema.database_name)) \"current\" " + auto &default_entry = ClientData::Get(context).catalog_search_path->GetDefault(); + auto catalog_name = default_entry.GetCatalog(); + if (catalog_name.empty()) { + catalog_name = DatabaseManager::GetDefaultDatabase(context); + } + auto schema = + Catalog::GetSchema(context, catalog_name, default_entry.GetSchemaPath(), OnEntryNotFound::RETURN_NULL); + auto current = schema ? StringUtil::Format("(schema.oid = %llu AND schema.database_oid = %llu)", schema->oid, + schema->ParentCatalog().GetOid()) + : "false"; + SetAlwaysRequireRebind(); + sql = "SELECT schema.database_name, schema.schema_name, " + current + + " \"current\" " "FROM duckdb_schemas() schema " "JOIN duckdb_databases dbs USING (database_oid) " "WHERE dbs.internal = false " "ORDER BY all;"; } else if (lname == "\"tables\"") { - sql = PragmaShowTables(); - } else if (ref.show_type == ShowType::SHOW_FROM) { - auto catalog_name = ref.GetCatalogName(); - auto schema_name = ref.GetSchemaName(); - - // Check for unqualified name, promote schema to catalog if unambiguous, and set schema_name to empty if so - Binder::BindSchemaOrCatalog(catalog_name, schema_name); - - optional_idx schema_oid; - // If fully qualified, check if the schema exists - if (!catalog_name.empty() && !schema_name.empty()) { - auto schema_entry = Catalog::GetSchema(context, catalog_name, schema_name, OnEntryNotFound::RETURN_NULL); - if (!schema_entry) { - // "a.b" can also name a nested schema - vector nested_path {catalog_name, schema_name}; - schema_entry = Catalog::GetSchema(context, Identifier(), nested_path, OnEntryNotFound::RETURN_NULL); - if (schema_entry) { - schema_oid = schema_entry->oid; + SetAlwaysRequireRebind(); + vector schemas; + for (auto &entry : ClientData::Get(context).catalog_search_path->Get()) { + auto catalog = entry.GetCatalog(); + if (catalog.empty()) { + catalog = DatabaseManager::TryGetDefaultDatabase(context); + if (catalog.empty()) { + continue; } } - if (!schema_entry) { - throw CatalogException("SHOW TABLES FROM: No catalog + schema named \"%s.%s\" found.", - catalog_name.GetIdentifierName(), schema_name.GetIdentifierName()); + auto schema = Catalog::GetSchema(context, catalog, entry.GetSchemaPath(), OnEntryNotFound::RETURN_NULL); + if (schema) { + schemas.push_back(StringUtil::Format("(database_name = %s AND schema_oid = %llu)", + SQLString(schema->ParentCatalog().GetName().GetIdentifierName()), + schema->oid)); + } + } + sql = PragmaShowTables(schemas.empty() ? "false" : StringUtil::Join(schemas, " OR ")); + } else if (ref.show_type == ShowType::SHOW_FROM) { + SetAlwaysRequireRebind(); + auto schema_path = ref.qualified_name.Parent().Path(); + Identifier catalog_name; + if (schema_path.size() == 1) { + BindSchemaOrCatalog(catalog_name, schema_path[0]); + if (schema_path[0].empty()) { + schema_path.clear(); + } + } else if (Catalog::GetCatalogEntry(context, schema_path[0])) { + catalog_name = schema_path[0]; + schema_path.erase(schema_path.begin()); + } + optional_idx schema_oid; + if (!schema_path.empty()) { + if (catalog_name.empty()) { + catalog_name = ClientData::Get(context).catalog_search_path->ResolveCatalog(schema_path[0]); } - } else if (catalog_name.empty() && !schema_name.empty()) { - // We have a schema name, use default catalog - auto &client_data = ClientData::Get(context); - auto &default_entry = client_data.catalog_search_path->GetDefault(); - catalog_name = default_entry.GetCatalog(); - auto schema_entry = Catalog::GetSchema(context, catalog_name, schema_name, OnEntryNotFound::RETURN_NULL); + auto schema_entry = Catalog::GetSchema(context, catalog_name, schema_path, OnEntryNotFound::RETURN_NULL); if (!schema_entry) { - throw CatalogException("SHOW TABLES FROM: No catalog + schema named \"%s.%s\" found.", - catalog_name.GetIdentifierName(), schema_name.GetIdentifierName()); + auto name = ref.qualified_name.Parent(); + if (name.Path().size() == 1) { + name = QualifiedName({catalog_name}, name.Name()); + } + throw CatalogException("SHOW TABLES FROM: No catalog + schema named \"%s\" found.", name.ToString()); } + catalog_name = schema_entry->ParentCatalog().GetName(); + schema_oid = schema_entry->oid; + } + vector filters; + if (!catalog_name.empty()) { + filters.push_back( + StringUtil::Format("lower(database_name) = lower(%s)", SQLString(catalog_name.GetIdentifierName()))); + } + if (schema_oid.IsValid()) { + filters.push_back(StringUtil::Format("schema_oid = %llu", schema_oid.GetIndex())); } - sql = PragmaShowTables(catalog_name.GetIdentifierName(), schema_name.GetIdentifierName(), schema_oid); + sql = PragmaShowTables(StringUtil::Join(filters, " AND ")); } else if (lname == "\"variables\"") { sql = PragmaShowVariables(); } else if (lname == "__show_tables_expanded") { diff --git a/src/duckdb/src/planner/expression/bound_cast_expression.cpp b/src/duckdb/src/planner/expression/bound_cast_expression.cpp index 4aa164f74..d4675b0e5 100644 --- a/src/duckdb/src/planner/expression/bound_cast_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_cast_expression.cpp @@ -8,6 +8,7 @@ #include "duckdb/main/config.hpp" #include "duckdb/main/context.hpp" #include "duckdb/planner/expression_binder.hpp" +#include "duckdb/common/types/decimal.hpp" namespace duckdb { @@ -445,6 +446,10 @@ static uint8_t IntegerTypeDecimalDigits(const LogicalType &type) { return 19; case LogicalTypeId::UBIGINT: return 20; + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UHUGEINT: + // a decimal wider than 38 digits holds every HUGEINT + return 39; default: return 0; } @@ -505,6 +510,12 @@ bool BoundCastExpression::CastCanThrow(const LogicalType &source_type, const Log if (source_type.id() == LogicalTypeId::BIGNUM) { return true; } + // FLOAT and DOUBLE are the maximum of DECIMAL and FLOAT/DOUBLE, but a decimal wider than 38 digits can exceed + // their range, e.g. a DECIMAL(309,0) of 2e308 -> DOUBLE + if ((target_type.id() == LogicalTypeId::FLOAT || target_type.id() == LogicalTypeId::DOUBLE) && + source_type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(source_type))) { + return true; + } // Floating point values that are not finite (NaN, inf) cannot be represented as a BIGNUM if (target_type.id() == LogicalTypeId::BIGNUM && (source_type.id() == LogicalTypeId::FLOAT || source_type.id() == LogicalTypeId::DOUBLE)) { @@ -518,6 +529,7 @@ bool BoundCastExpression::CastCanThrow(const LogicalType &source_type, const Log // 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) + // in databases that stay within 38 digits if (target_type.id() == LogicalTypeId::DECIMAL) { return !DecimalHoldsEveryValue(source_type, target_type); } diff --git a/src/duckdb/src/planner/expression_binder/index_binder.cpp b/src/duckdb/src/planner/expression_binder/index_binder.cpp index 1526dd6c4..26ce29df9 100644 --- a/src/duckdb/src/planner/expression_binder/index_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/index_binder.cpp @@ -5,6 +5,8 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/parser/parsed_data/create_index_info.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/column_binding.hpp" @@ -17,10 +19,288 @@ #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/bound_cast_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/function/cast/bound_cast_data.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/main/attached_database.hpp" +#include "duckdb/storage/storage_manager.hpp" namespace duckdb { +namespace { + +//! The storage version the keys of an index are written with: the version its stored data records (the ART saves the +//! version it was created under, an index written before v1.5.0 records none), or the version of the database for an +//! index that is being created. The version stays with the index when the database is upgraded to a newer storage +//! version, since the stored keys keep their types. +StorageVersion IndexKeyStorageVersion(AttachedDatabase &db, optional_ptr storage_info) { + if (storage_info && storage_info->IsValid()) { + auto entry = storage_info->options.find("storage_version"); + if (entry == storage_info->options.end()) { + return StorageVersion::INVALID; + } + return static_cast(entry->second.GetValue()); + } + return db.GetStorageManager().GetStorageVersion(); +} + +//! Whether the keys of an index of the storage version are bound within 38 digits: the engines of the storage versions +//! before wide decimals bind every decimal key that way, and the keys they store have those types +bool KeysPredateWideDecimals(StorageVersion key_version) { + return StorageManager::IsPriorToVersion(Decimal::WIDE_VERSION_ADDED, key_version); +} + +//! The width the keys of the storage version are bound within, in place of the max_decimal_width setting, so that +//! every session binds a key to the same types: 38 digits before wide decimals, as the engines of those versions bind +//! them, and the uint32_t range of the width from then on, so that the key types follow from the column types alone +uint32_t KeyDecimalWidth(StorageVersion key_version) { + if (KeysPredateWideDecimals(key_version)) { + return Decimal::MAX_WIDTH_INT128; + } + return NumericLimits::Maximum(); +} + +//! The hint of the errors a wider type raises while binding keys of the storage version, if it bounds them +string KeyDecimalWidthReason(StorageVersion key_version) { + if (!KeysPredateWideDecimals(key_version)) { + return string(); + } + return StringUtil::Format("index keys of storage version %s are bound within %d digits, as the engines of that " + "version bind them; upgrade the database to storage version %s or later for wider keys", + GetStorageVersionName(key_version, false), Decimal::MAX_WIDTH_INT128, + GetStorageVersionName(Decimal::WIDE_VERSION_ADDED, false)); +} + +//! Binds the keys within the decimal width of their storage version while it lives, in place of the setting +struct KeyDecimalWidthScope { + KeyDecimalWidthScope(Binder &binder_p, StorageVersion key_version) + : binder(binder_p), reason(KeyDecimalWidthReason(key_version)), + limit(KeyDecimalWidth(key_version), reason.c_str()), previous(binder_p.GetFixedDecimalWidthLimit()) { + binder.SetDecimalWidthLimit(&limit); + } + ~KeyDecimalWidthScope() { + binder.SetDecimalWidthLimit(previous); + } + + Binder &binder; + const string reason; + const DecimalWidthLimit limit; + optional_ptr previous; +}; + +//! The first expression of a wide decimal type within the key, if any: the engines before wide decimals bind every +//! subexpression within 38 digits, so a wide intermediate changes the computed key as much as a wide result +optional_ptr FindWideDecimalExpression(const Expression &expr) { + if (StorageManager::ContainsWideDecimal(expr.GetReturnType())) { + return &expr; + } + optional_ptr result; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + if (!result) { + result = FindWideDecimalExpression(child); + } + }); + return result; +} + +optional_ptr FindWideDecimalExpression(const vector> &keys) { + for (auto &key : keys) { + auto wide = FindWideDecimalExpression(*key); + if (wide) { + return wide; + } + } + return nullptr; +} + +//! The element type of a LIST or ARRAY +const LogicalType &NestedChildType(const LogicalType &type) { + return type.id() == LogicalTypeId::ARRAY ? ArrayType::GetChildType(type) : ListType::GetChildType(type); +} + +bool IsNestedList(const LogicalType &type) { + return type.id() == LogicalTypeId::LIST || type.id() == LogicalTypeId::ARRAY; +} + +bool IsBignumDecimalPair(const LogicalType &a, const LogicalType &b) { + return a.id() == LogicalTypeId::BIGNUM && b.id() == LogicalTypeId::DECIMAL; +} + +//! Whether the cast converts a BIGNUM to a DECIMAL or a DECIMAL to a BIGNUM, the types themselves +bool IsBignumDecimalCast(const LogicalType &source, const LogicalType &target) { + return IsBignumDecimalPair(source, target) || IsBignumDecimalPair(target, source); +} + +//! A STRUCT or a TUPLE (an unnamed struct): the cast between them pairs the fields +bool IsStructOrTuple(const LogicalType &type) { + return type.id() == LogicalTypeId::STRUCT || type.id() == LogicalTypeId::TUPLE; +} + +bool CastsBetweenBignumAndDecimal(ClientContext &context, const LogicalType &source, const LogicalType &target); + +//! The member of a UNION a cast promotes its source to: the member the source casts to implicitly at the lowest cost, +//! none when no member or several members do (the cast does not bind then) +optional_ptr PromotedUnionMember(ClientContext &context, const LogicalType &source, + const LogicalType &target) { + optional_ptr result; + auto best_cost = NumericLimits::Maximum(); + bool ambiguous = false; + for (idx_t i = 0; i < UnionType::GetMemberCount(target); i++) { + auto &member = UnionType::GetMemberType(target, i); + const auto cost = CastFunctionSet::ImplicitCastCost(context, source, member); + if (cost < 0 || cost > best_cost) { + continue; + } + ambiguous = cost == best_cost; + best_cost = cost; + result = &member; + } + return ambiguous ? nullptr : result; +} + +//! Whether every member of a source UNION has a member of its name in the target UNION +bool UnionMembersMatchByName(const LogicalType &source, const LogicalType &target) { + for (idx_t i = 0; i < UnionType::GetMemberCount(source); i++) { + auto &name = UnionType::GetMemberName(source, i); + bool found = false; + for (idx_t j = 0; j < UnionType::GetMemberCount(target); j++) { + if (UnionType::GetMemberName(target, j) == name) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; +} + +//! Whether a cast to a UNION converts between BIGNUM and DECIMAL in the members it selects: a source UNION whose +//! members all have a name in the target pairs the members by name, any other source is promoted into the member it +//! casts to implicitly (union_casts.cpp) +bool UnionCastsBetweenBignumAndDecimal(ClientContext &context, const LogicalType &source, const LogicalType &target) { + if (source.id() == LogicalTypeId::UNION && UnionMembersMatchByName(source, target)) { + for (idx_t i = 0; i < UnionType::GetMemberCount(source); i++) { + auto &name = UnionType::GetMemberName(source, i); + for (idx_t j = 0; j < UnionType::GetMemberCount(target); j++) { + if (UnionType::GetMemberName(target, j) == name && + CastsBetweenBignumAndDecimal(context, UnionType::GetMemberType(source, i), + UnionType::GetMemberType(target, j))) { + return true; + } + } + } + return false; + } + auto member = PromotedUnionMember(context, source, target); + return member && CastsBetweenBignumAndDecimal(context, source, *member); +} + +//! Whether a cast converts between BIGNUM and DECIMAL, the types themselves or the children the cast pairs: the +//! elements of lists and arrays, the keys and values of maps, the struct fields the cast matches, every field of a +//! STRUCT cast to a MAP with the value type, and the union members the cast selects; the engines before wide decimals +//! have no such cast +bool CastsBetweenBignumAndDecimal(ClientContext &context, const LogicalType &source, const LogicalType &target) { + if (IsBignumDecimalCast(source, target)) { + return true; + } + if (IsNestedList(source) && IsNestedList(target)) { + return CastsBetweenBignumAndDecimal(context, NestedChildType(source), NestedChildType(target)); + } + if (source.id() == LogicalTypeId::MAP && target.id() == LogicalTypeId::MAP) { + return CastsBetweenBignumAndDecimal(context, MapType::KeyType(source), MapType::KeyType(target)) || + CastsBetweenBignumAndDecimal(context, MapType::ValueType(source), MapType::ValueType(target)); + } + if (source.id() == LogicalTypeId::STRUCT && target.id() == LogicalTypeId::MAP) { + auto &value_type = MapType::ValueType(target); + for (auto &field : StructType::GetChildTypes(source)) { + if (CastsBetweenBignumAndDecimal(context, field.second, value_type)) { + return true; + } + } + return false; + } + if (target.id() == LogicalTypeId::UNION) { + return UnionCastsBetweenBignumAndDecimal(context, source, target); + } + if (!IsStructOrTuple(source) || !IsStructOrTuple(target)) { + return false; + } + // the fields the cast pairs: by name between named structs, else by position; a cast that does not bind pairs none + auto mapping = StructBoundCastData::GetFieldMapping(source, target); + if (mapping.kind != StructCastFieldMapping::MatchKind::VALID) { + return false; + } + auto &source_children = StructType::GetChildTypes(source); + auto &target_children = StructType::GetChildTypes(target); + for (idx_t i = 0; i < mapping.source_indexes.size(); i++) { + auto &source_child = source_children[mapping.source_indexes[i]].second; + auto &target_child = target_children[mapping.target_indexes[i]].second; + if (CastsBetweenBignumAndDecimal(context, source_child, target_child)) { + return true; + } + } + return false; +} + +//! Why the engines before wide decimals compute other keys for the expressions than this engine, empty when they +//! agree: those engines bind every decimal within 38 digits and have no cast between BIGNUM and DECIMAL +string DescribeLegacyKeyDifference(const vector> &keys, const IndexKeyBinding &binding) { + auto wide = FindWideDecimalExpression(keys); + if (wide) { + return StringUtil::Format("%s binds to %s, those engines bind decimal keys within %d digits", wide->ToString(), + wide->GetReturnType().ToString(), Decimal::MAX_WIDTH_INT128); + } + return binding.legacy_cast; +} + +//! A stored index whose keys the engines of its storage version computed otherwise would leave the stored keys +//! unmatched (a UNIQUE index would accept duplicates), so it is not bound until it is created again +void ThrowMismatchedStoredKey(const UnboundIndex &unbound_index, StorageVersion key_version, const string &difference) { + auto &name = unbound_index.GetIndexName(); + throw BinderException("Cannot bind index %s on table %s: the index was stored at storage version %s, whose engines " + "compute other keys for its expression (%s), so the stored keys differ from the keys this " + "engine computes. DROP INDEX %s and CREATE it again; until then writes to the table fail, as " + "does a CHECKPOINT after writes replayed from the write-ahead log", + name, unbound_index.GetTableName(), GetStorageVersionName(key_version, false), difference, + name); +} + +//! The keys of a new index are stored at the storage version of its database: a key the engines of that version +//! compute otherwise is refused, like a column type they cannot read, so that they compute the stored keys +void CheckNewKeys(AttachedDatabase &db, const vector> &keys, const IndexKeyBinding &binding) { + if (!KeysPredateWideDecimals(binding.version)) { + return; + } + auto &storage = db.GetStorageManager(); + auto wide = FindWideDecimalExpression(keys); + if (wide) { + throw InvalidInputException( + storage.GetUnsupportedDecimalWidthReason(wide->GetReturnType(), "index key expressions")); + } + if (!binding.legacy_cast.empty()) { + throw InvalidInputException(storage.GetUnsupportedPriorToVersionReason( + "Index key expressions with a cast between BIGNUM and DECIMAL", Decimal::WIDE_VERSION_ADDED)); + } +} + +//! Registers the keys being bound with the binder for the duration of the scope +struct IndexKeyBindingScope { + IndexKeyBindingScope(optional_ptr &slot_p, IndexKeyBinding &binding) : slot(slot_p) { + D_ASSERT(!slot); + slot = &binding; + } + ~IndexKeyBindingScope() { + slot = nullptr; + } + optional_ptr &slot; +}; + +} // namespace + IndexBinder::IndexBinder(Binder &binder, ClientContext &context, optional_ptr table, optional_ptr info) : ExpressionBinder(binder, context), table(table), info(info) { @@ -64,7 +344,7 @@ static bool IsValidIndexExpression(Binder &binder, const Expression &expr, Error return true; } -unique_ptr IndexBinder::BindIndex(const UnboundIndex &unbound_index) { +unique_ptr IndexBinder::BindIndex(const UnboundIndex &unbound_index, bool skip_mismatched_keys) { auto &index_type_name = unbound_index.GetIndexType(); // Do we know the type of this index now? auto index_type = context.db->config.GetIndexTypes().FindByName(index_type_name); @@ -78,22 +358,37 @@ unique_ptr IndexBinder::BindIndex(const UnboundIndex &unbound_index) auto &storage_info = unbound_index.GetStorageInfo(); auto &parsed_expressions = unbound_index.GetParsedExpressions(); - // bind the parsed expressions to create unbound expressions + // bind the parsed expressions to create unbound expressions, within the decimal width of their storage version + // and as the engines of that version bound them + IndexKeyBinding binding {IndexKeyStorageVersion(unbound_index.db, storage_info), true, string()}; auto &properties = binder.GetStatementProperties(); const auto statement_requires_rebind = properties.always_require_rebind; vector> unbound_expressions; unbound_expressions.reserve(parsed_expressions.size()); - for (auto &expr : parsed_expressions) { - auto copy = expr->Copy(); - properties.always_require_rebind = false; - unbound_expressions.push_back(Bind(copy)); - // Stored keys must satisfy the same requirements as newly created keys. - ErrorData error; - if (!IsValidIndexExpression(binder, *unbound_expressions.back(), error)) { - throw DataCorruptionException("Invalid index %s: %s", create_info.GetIndexName(), error.RawMessage()); + { + IndexKeyBindingScope scope(keys, binding); + KeyDecimalWidthScope key_width(binder, binding.version); + for (auto &expr : parsed_expressions) { + auto copy = expr->Copy(); + properties.always_require_rebind = false; + unbound_expressions.push_back(Bind(copy)); + // Stored keys must satisfy the same requirements as newly created keys. + ErrorData error; + if (!IsValidIndexExpression(binder, *unbound_expressions.back(), error)) { + throw DataCorruptionException("Invalid index %s: %s", create_info.GetIndexName(), error.RawMessage()); + } } } properties.always_require_rebind = statement_requires_rebind; + if (KeysPredateWideDecimals(binding.version)) { + auto difference = DescribeLegacyKeyDifference(unbound_expressions, binding); + if (!difference.empty()) { + if (skip_mismatched_keys) { + return nullptr; + } + ThrowMismatchedStoredKey(unbound_index, binding.version, difference); + } + } CreateIndexInput input(context, unbound_index.table_io_manager, unbound_index.db, create_info.constraint_type, create_info.GetIndexName(), create_info.column_ids, unbound_expressions, storage_info, @@ -149,19 +444,28 @@ unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, // Bind the index expressions. // The expressions are bound again when the index is loaded, so they cannot depend on the session or the query - // they are bound in (e.g. now(), getvariable()) - such functions are folded to constants while binding. + // they are bound in (e.g. now(), getvariable()) - such functions are folded to constants while binding, and + // decimals are bound within the width of the storage version instead of the max_decimal_width setting. + auto &db = table_entry.ParentCatalog().GetAttached(); + const auto key_version = db.HasStorageManager() ? IndexKeyStorageVersion(db, nullptr) : StorageVersion::LATEST; + IndexKeyBinding binding {key_version, false, string()}; auto &properties = binder.GetStatementProperties(); const auto statement_requires_rebind = properties.always_require_rebind; vector> expressions; - for (auto &expr : create_index_info->expressions) { - properties.always_require_rebind = false; - expressions.push_back(Bind(expr)); - ErrorData error; - if (!IsValidIndexExpression(binder, *expressions.back(), error)) { - error.Throw(); + { + IndexKeyBindingScope scope(keys, binding); + KeyDecimalWidthScope key_width(binder, key_version); + for (auto &expr : create_index_info->expressions) { + properties.always_require_rebind = false; + expressions.push_back(Bind(expr)); + ErrorData error; + if (!IsValidIndexExpression(binder, *expressions.back(), error)) { + error.Throw(); + } } } properties.always_require_rebind = statement_requires_rebind; + CheckNewKeys(db, expressions, binding); auto &get = plan->Cast(); InitCreateIndexInfo(get, *create_index_info); @@ -176,25 +480,75 @@ unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, BindResult IndexBinder::BindExpression(unique_ptr &expr_ptr, idx_t depth, bool root_expression) { auto &expr = *expr_ptr; + const bool legacy_keys = keys && KeysPredateWideDecimals(keys->version); switch (expr.GetExpressionClass()) { case ExpressionClass::WINDOW: 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: { - // 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); + case ExpressionClass::CONSTANT: + if (legacy_keys && keys->stored) { + return BindLegacyConstant(expr.Cast()); + } + break; + default: + break; + } + // 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); + auto result = ExpressionBinder::BindExpression(expr_ptr, depth); + if (legacy_keys && !result.HasError()) { + // the casts this node adds are bound now: an enclosing function folds a constant node to its value + BindLegacyCasts(result.expression); + } + return result; +} + +BindResult IndexBinder::BindLegacyConstant(ConstantExpression &expr) { + // those engines bind a literal wider than 38 digits to a DOUBLE, the stored keys hold that value + return BindResult(make_uniq(expr.GetLiteral().ToValue(Decimal::MAX_WIDTH_INT128))); +} + +void IndexBinder::BindLegacyCasts(unique_ptr &expr) { + // the node is an explicit cast, the casts of its children are the implicit casts the node added: the children + // themselves were bound before + BindLegacyCast(expr); + ExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { BindLegacyCast(child); }); +} + +void IndexBinder::BindLegacyCast(unique_ptr &expr) { + if (!BoundCastExpression::IsCast(*expr)) { + return; + } + auto &cast = expr->Cast(); + const auto source = BoundCastExpression::SourceType(cast); + auto &target = BoundCastExpression::TargetType(cast); + if (!CastsBetweenBignumAndDecimal(context, source, target)) { + return; + } + if (keys->stored && IsBignumDecimalCast(source, target)) { + // those engines bind the cast to the null cast: a TRY_CAST gives NULL, a CAST raises an error + if (BoundCastExpression::GetBoundCast(cast).IsNullCast()) { + return; + } + auto child = std::move(BoundCastExpression::ChildMutable(cast)); + expr = BoundCastExpression::Create(std::move(child), target, BoundCastInfo(DefaultCasts::TryVectorNullCast), + BoundCastExpression::IsTryCast(cast)); + return; } + if (keys->legacy_cast.empty()) { + keys->legacy_cast = + StringUtil::Format("%s casts %s to %s, a cast those engines do not have (a TRY_CAST gives NULL there)", + cast.ToString(), source.ToString(), target.ToString()); } } diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 58557981b..07d98a406 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -218,6 +218,9 @@ static FilterPropagateResult CheckZonemapAgainstConstants(const BaseStatistics & if (stats.GetStatsType() == StatisticsType::STRING_STATS) { return StringStats::CheckZonemap(stats, comparison_type, values); } + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + return BignumStats::CheckZonemap(stats, comparison_type, values); + } return FilterPropagateResult::NO_PRUNING_POSSIBLE; default: return FilterPropagateResult::NO_PRUNING_POSSIBLE; diff --git a/src/duckdb/src/planner/filter/table_filter_dynamic_function.cpp b/src/duckdb/src/planner/filter/table_filter_dynamic_function.cpp index 4b0a0cbf8..1dc11c972 100644 --- a/src/duckdb/src/planner/filter/table_filter_dynamic_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_dynamic_function.cpp @@ -70,6 +70,9 @@ FilterPropagateResult DynamicFilterData::CheckStatistics(const BaseStatistics &s if (stats.GetStatsType() == StatisticsType::STRING_STATS) { return StringStats::CheckZonemap(stats, comparison_type, array_ptr(constant)); } + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + return BignumStats::CheckZonemap(stats, comparison_type, array_ptr(constant)); + } return FilterPropagateResult::NO_PRUNING_POSSIBLE; default: return FilterPropagateResult::NO_PRUNING_POSSIBLE; diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index 6cd9d6276..74a34f64a 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -52,8 +52,8 @@ DataTableInfo::DataTableInfo(AttachedDatabase &db, shared_ptr ta D_ASSERT(!this->schema_path.empty()); } -void DataTableInfo::BindIndexes(ClientContext &context, const optional &index_type) { - indexes.Bind(context, *this, index_type); +void DataTableInfo::BindIndexes(ClientContext &context, const optional &index_type, bool skip_mismatched_keys) { + indexes.Bind(context, *this, index_type, skip_mismatched_keys); } bool DataTableInfo::IsTemporary() const { diff --git a/src/duckdb/src/storage/index_entry.cpp b/src/duckdb/src/storage/index_entry.cpp index 2d0b14f1c..487f27f96 100644 --- a/src/duckdb/src/storage/index_entry.cpp +++ b/src/duckdb/src/storage/index_entry.cpp @@ -356,9 +356,10 @@ void IndexEntry::Retire() { bind_state = IndexBindState::RETIRED; } -unique_ptr IndexEntry::Bind(IndexBinder &binder, const vector &table_types) { +unique_ptr IndexEntry::Bind(IndexBinder &binder, const vector &table_types, + bool skip_mismatched_keys) { auto entry_lock = lock.GetExclusiveLock(); - return owned_index->Cast().Bind(binder, table_types); + return owned_index->Cast().Bind(binder, table_types, skip_mismatched_keys); } void IndexEntry::CommitBind(unique_ptr bound_index) { diff --git a/src/duckdb/src/storage/serialization/serialize_constraint.cpp b/src/duckdb/src/storage/serialization/serialize_constraint.cpp index 6132d72f0..dc20c10c4 100644 --- a/src/duckdb/src/storage/serialization/serialize_constraint.cpp +++ b/src/duckdb/src/storage/serialization/serialize_constraint.cpp @@ -55,6 +55,9 @@ void ForeignKeyConstraint::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault(204, "table", info.table); serializer.WritePropertyWithDefault>(205, "pk_keys", info.pk_keys); serializer.WritePropertyWithDefault>(206, "fk_keys", info.fk_keys); + if (serializer.ShouldSerialize(StorageVersion::V2_0_0) || (referenced_table.Path().size() > 2)) { + serializer.WriteProperty(207, "referenced_table", referenced_table); + } } unique_ptr ForeignKeyConstraint::Deserialize(Deserializer &deserializer) { @@ -66,6 +69,7 @@ unique_ptr ForeignKeyConstraint::Deserialize(Deserializer &deseriali deserializer.ReadPropertyWithDefault(204, "table", result->info.table); deserializer.ReadPropertyWithDefault>(205, "pk_keys", result->info.pk_keys); deserializer.ReadPropertyWithDefault>(206, "fk_keys", result->info.fk_keys); + deserializer.ReadPropertyWithExplicitDefault(207, "referenced_table", result->referenced_table, QualifiedName()); return std::move(result); } diff --git a/src/duckdb/src/storage/statistics/base_statistics.cpp b/src/duckdb/src/storage/statistics/base_statistics.cpp index dd80cc014..f1e25e0c1 100644 --- a/src/duckdb/src/storage/statistics/base_statistics.cpp +++ b/src/duckdb/src/storage/statistics/base_statistics.cpp @@ -80,6 +80,10 @@ StatisticsType BaseStatistics::GetStatsType(const LogicalType &type) { if (type.id() == LogicalTypeId::VARIANT) { return StatisticsType::VARIANT_STATS; } + if (type.id() == LogicalTypeId::DECIMAL && type.InternalType() == PhysicalType::VARCHAR) { + // decimals wider than 38 digits are BIGNUM blobs with min/max bounds of a bounded size + return StatisticsType::BIGNUM_STATS; + } switch (type.InternalType()) { case PhysicalType::BOOL: case PhysicalType::INT8: @@ -177,6 +181,9 @@ void BaseStatistics::Merge(const BaseStatistics &other, StatsMergeType merge_typ case StatisticsType::VARIANT_STATS: VariantStats::Merge(*this, other); break; + case StatisticsType::BIGNUM_STATS: + BignumStats::Merge(*this, other); + break; default: break; } @@ -230,6 +237,8 @@ BaseStatistics BaseStatistics::CreateUnknownType(LogicalType type) { return GeometryStats::CreateUnknown(std::move(type)); case StatisticsType::VARIANT_STATS: return VariantStats::CreateUnknown(std::move(type)); + case StatisticsType::BIGNUM_STATS: + return BignumStats::CreateUnknown(std::move(type)); default: return BaseStatistics(std::move(type)); } @@ -251,6 +260,8 @@ BaseStatistics BaseStatistics::CreateEmptyType(LogicalType type) { return GeometryStats::CreateEmpty(std::move(type)); case StatisticsType::VARIANT_STATS: return VariantStats::CreateEmpty(std::move(type)); + case StatisticsType::BIGNUM_STATS: + return BignumStats::CreateEmpty(std::move(type)); default: return BaseStatistics(std::move(type)); } @@ -298,6 +309,9 @@ void BaseStatistics::Copy(const BaseStatistics &other) { case StatisticsType::STRING_STATS: StringStats::Copy(*this, other); break; + case StatisticsType::BIGNUM_STATS: + BignumStats::Copy(*this, other); + break; default: break; } @@ -423,6 +437,9 @@ void BaseStatistics::Serialize(Serializer &serializer) const { case StatisticsType::VARIANT_STATS: VariantStats::Serialize(*this, serializer); break; + case StatisticsType::BIGNUM_STATS: + BignumStats::Serialize(*this, serializer); + break; default: break; } @@ -467,6 +484,9 @@ BaseStatistics BaseStatistics::Deserialize(Deserializer &deserializer) { case StatisticsType::VARIANT_STATS: VariantStats::Deserialize(obj, stats); break; + case StatisticsType::BIGNUM_STATS: + BignumStats::Deserialize(obj, stats); + break; default: break; } @@ -499,6 +519,9 @@ Value BaseStatistics::ToStruct(bool exact) const { case StatisticsType::VARIANT_STATS: children = VariantStats::ToStruct(*this, exact); break; + case StatisticsType::BIGNUM_STATS: + children = BignumStats::ToStruct(*this); + break; default: break; } @@ -579,6 +602,9 @@ void BaseStatistics::Verify(const Vector &vector, const SelectionVector &sel, id case StatisticsType::VARIANT_STATS: VariantStats::Verify(*this, vector, sel, count); break; + case StatisticsType::BIGNUM_STATS: + BignumStats::Verify(*this, vector, sel, count); + break; default: break; } @@ -670,6 +696,12 @@ BaseStatistics BaseStatistics::FromConstantType(const Value &input) { } return result; } + case StatisticsType::BIGNUM_STATS: { + auto result = BignumStats::CreateEmpty(input.type()); + BignumStats::SetMin(result, input); + BignumStats::SetMax(result, input); + return result; + } case StatisticsType::VARIANT_STATS: { auto result = VariantStats::CreateEmpty(input.type()); auto unshredded_type = VariantShredding::GetUnshreddedType(); diff --git a/src/duckdb/src/storage/statistics/bignum_stats.cpp b/src/duckdb/src/storage/statistics/bignum_stats.cpp new file mode 100644 index 000000000..1d5c66dd3 --- /dev/null +++ b/src/duckdb/src/storage/statistics/bignum_stats.cpp @@ -0,0 +1,410 @@ +#include "duckdb/storage/statistics/bignum_stats.hpp" + +#include "duckdb/common/serializer/deserializer.hpp" +#include "duckdb/common/serializer/serializer.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" +#include "duckdb/common/types/vector.hpp" +#include "duckdb/storage/statistics/base_statistics.hpp" + +namespace duckdb { + +//! The owned bytes of the min and max bounds +struct BignumStatsExtraData : public ExtraStatsData { + string blobs[2]; +}; + +//! The bytes a bound keeps: the header and the first magnitude bytes of the blob +static constexpr idx_t MAX_BOUND_SIZE = Bignum::BIGNUM_HEADER_SIZE + BignumStatsData::MAX_BOUND_DATA_BYTES; + +//! The byte a cut bound omits: a min bound continues with 0x00 and a max bound with 0xFF +static data_t PadByte(bool is_min) { + return is_min ? 0x00 : 0xFF; +} + +//! The number of magnitude bytes the header of a blob records (see Bignum::SetHeader) +static idx_t HeaderDataSize(const string_t &blob) { + auto data = const_data_ptr_cast(blob.GetData()); + uint32_t header = (uint32_t(data[0]) << 16) | (uint32_t(data[1]) << 8) | uint32_t(data[2]); + if ((data[0] & 0x80) == 0) { + // the header of a negative value is complemented + header = ~header; + } + return header & 0x7FFFFF; +} + +//! Compares a blob or bound with a bound, the bytes a cut bound omits read as its pad; the byte order of the BIGNUM +//! encoding is the numeric order +static int CompareBound(const string_t &lhs, const string_t &rhs, bool is_min) { + const idx_t lhs_size = lhs.GetSize(); + const idx_t rhs_size = rhs.GetSize(); + const idx_t common = MinValue(lhs_size, rhs_size); + const int cmp = memcmp(lhs.GetData(), rhs.GetData(), common); + if (cmp != 0) { + return cmp < 0 ? -1 : 1; + } + // the longer side continues against the pad of the shorter one + const bool lhs_longer = lhs_size > rhs_size; + auto &longer = lhs_longer ? lhs : rhs; + const auto pad = PadByte(is_min); + for (idx_t i = common; i < longer.GetSize(); i++) { + const auto byte = static_cast(longer.GetData()[i]); + if (byte != pad) { + return (byte > pad) == lhs_longer ? 1 : -1; + } + } + return 0; +} + +//! The complete blob of a bound: a cut bound is padded to the size its header records +static string PadBound(const string_t &bound, bool is_min) { + string result(bound.GetData(), bound.GetSize()); + const idx_t full_size = Bignum::BIGNUM_HEADER_SIZE + HeaderDataSize(bound); + if (result.size() < full_size) { + result.append(full_size - result.size(), static_cast(PadByte(is_min))); + } + return result; +} + +BaseStatistics BignumStats::CreateUnknown(LogicalType type) { + BaseStatistics result(std::move(type)); + result.InitializeUnknown(); + auto &data = GetDataUnsafe(result); + data.has_min = false; + data.has_max = false; + data.min_exact = true; + data.max_exact = true; + return result; +} + +BaseStatistics BignumStats::CreateEmpty(LogicalType type) { + BaseStatistics result(std::move(type)); + result.InitializeEmpty(); + auto &data = GetDataUnsafe(result); + data.has_min = true; + data.has_max = true; + data.min_exact = true; + data.max_exact = true; + return result; +} + +BignumStatsData &BignumStats::GetDataUnsafe(BaseStatistics &stats) { + D_ASSERT(stats.GetStatsType() == StatisticsType::BIGNUM_STATS); + return stats.stats_union.bignum_data; +} + +const BignumStatsData &BignumStats::GetDataUnsafe(const BaseStatistics &stats) { + D_ASSERT(stats.GetStatsType() == StatisticsType::BIGNUM_STATS); + return stats.stats_union.bignum_data; +} + +string_t BignumStats::AssignBound(BaseStatistics &stats, string_t blob, bool is_min, bool &exact) { + if (!stats.extra_data) { + stats.extra_data = make_uniq(); + } + auto &owned = stats.extra_data->Cast().blobs[is_min ? 0 : 1]; + idx_t size = blob.GetSize(); + if (size > MAX_BOUND_SIZE) { + // the cut bound reads as the blob with its tail replaced by the pad, which lies beyond the blob + size = MAX_BOUND_SIZE; + exact = false; + } + owned.assign(blob.GetData(), size); + return string_t(owned); +} + +bool BignumStats::HasMinMax(const BaseStatistics &stats) { + if (stats.GetType().id() == LogicalTypeId::SQLNULL) { + return false; + } + auto &data = GetDataUnsafe(stats); + return data.has_min && data.has_max && data.min.GetSize() > 0 && data.max.GetSize() > 0; +} + +bool BignumStats::MinIsExact(const BaseStatistics &stats) { + return HasMinMax(stats) && GetDataUnsafe(stats).min_exact; +} + +bool BignumStats::MaxIsExact(const BaseStatistics &stats) { + return HasMinMax(stats) && GetDataUnsafe(stats).max_exact; +} + +string BignumStats::MinBlob(const BaseStatistics &stats) { + D_ASSERT(HasMinMax(stats)); + return PadBound(GetDataUnsafe(stats).min, true); +} + +string BignumStats::MaxBlob(const BaseStatistics &stats) { + D_ASSERT(HasMinMax(stats)); + return PadBound(GetDataUnsafe(stats).max, false); +} + +//! The largest magnitude of a DECIMAL of the width, 10^width - 1, as a BIGNUM blob with the given sign +static string WidthLimitBlob(uint32_t width, bool negative) { + const auto power = DecimalHelper::PowerOfTen(width); + // the magnitude bytes follow the header of the (positive) power, one is borrowed from the least significant byte up + vector magnitude(power.begin() + Bignum::BIGNUM_HEADER_SIZE, power.end()); + for (idx_t i = magnitude.size(); i > 0; i--) { + if (magnitude[i - 1]-- != 0) { + break; + } + } + idx_t start = 0; + while (start + 1 < magnitude.size() && magnitude[start] == 0) { + start++; + } + return Bignum::FromByteArray(magnitude.data() + start, magnitude.size() - start, negative); +} + +//! The value of a bound: the pad of a cut bound can carry it beyond the range of the type (a max bound above the +//! largest value of the width, a negative min bound below the smallest), such a bound is the limit of the range itself +static Value BoundValue(const LogicalType &type, const string &blob, bool is_min) { + const auto width = DecimalType::GetWidth(type); + const auto scale = DecimalType::GetScale(type); + const bignum_t value {string_t(blob)}; + if (DecimalHelper::FitsWidth(value, width)) { + return Value::DECIMAL(value, width, scale); + } + const auto limit = WidthLimitBlob(width, is_min); + return Value::DECIMAL(bignum_t(string_t(limit)), width, scale); +} + +Value BignumStats::Min(const BaseStatistics &stats) { + if (!HasMinMax(stats)) { + throw InternalException("BignumStats::Min called but no min value was found"); + } + return BoundValue(stats.GetType(), MinBlob(stats), true); +} + +Value BignumStats::Max(const BaseStatistics &stats) { + if (!HasMinMax(stats)) { + throw InternalException("BignumStats::Max called but no max value was found"); + } + return BoundValue(stats.GetType(), MaxBlob(stats), false); +} + +void BignumStats::SetMin(BaseStatistics &stats, string_t blob) { + auto &data = GetDataUnsafe(stats); + data.has_min = true; + data.min_exact = true; + data.min = AssignBound(stats, blob, true, data.min_exact); +} + +void BignumStats::SetMax(BaseStatistics &stats, string_t blob) { + auto &data = GetDataUnsafe(stats); + data.has_max = true; + data.max_exact = true; + data.max = AssignBound(stats, blob, false, data.max_exact); +} + +void BignumStats::SetMin(BaseStatistics &stats, const Value &val) { + if (val.IsNull()) { + GetDataUnsafe(stats).has_min = false; + return; + } + D_ASSERT(val.type() == stats.GetType()); + SetMin(stats, string_t(StringValue::Get(val))); +} + +void BignumStats::SetMax(BaseStatistics &stats, const Value &val) { + if (val.IsNull()) { + GetDataUnsafe(stats).has_max = false; + return; + } + D_ASSERT(val.type() == stats.GetType()); + SetMax(stats, string_t(StringValue::Get(val))); +} + +void BignumStats::MergeBound(BaseStatistics &stats, string_t blob, bool exact, bool is_min) { + auto &data = GetDataUnsafe(stats); + auto &bound = is_min ? data.min : data.max; + auto &bound_exact = is_min ? data.min_exact : data.max_exact; + if (bound.GetSize() > 0) { + const int cmp = CompareBound(blob, bound, is_min); + if (is_min ? cmp > 0 : cmp < 0) { + return; + } + if (cmp == 0) { + // the same bound: it is attained when either side attains it + bound_exact = bound_exact || exact; + return; + } + } + bound = AssignBound(stats, blob, is_min, exact); + bound_exact = exact; +} + +void BignumStats::Update(BaseStatistics &stats, string_t blob) { + Merge(stats, blob, blob); +} + +void BignumStats::Merge(BaseStatistics &stats, string_t min, string_t max) { + auto &data = GetDataUnsafe(stats); + if (data.has_min && min.GetSize() > 0) { + MergeBound(stats, min, true, true); + } + if (data.has_max && max.GetSize() > 0) { + MergeBound(stats, max, true, false); + } +} + +void BignumStats::Merge(BaseStatistics &stats, const BaseStatistics &other) { + if (other.GetType().id() == LogicalTypeId::VALIDITY || other.GetType().id() == LogicalTypeId::SQLNULL) { + return; + } + auto &data = GetDataUnsafe(stats); + auto &other_data = GetDataUnsafe(other); + data.has_min = data.has_min && other_data.has_min; + data.has_max = data.has_max && other_data.has_max; + if (data.has_min && other_data.min.GetSize() > 0) { + MergeBound(stats, other_data.min, other_data.min_exact, true); + } + if (data.has_max && other_data.max.GetSize() > 0) { + MergeBound(stats, other_data.max, other_data.max_exact, false); + } +} + +void BignumStats::Copy(BaseStatistics &stats, const BaseStatistics &other) { + auto &data = GetDataUnsafe(stats); + auto &other_data = GetDataUnsafe(other); + // the bounds of the other statistics are within the bound size, so they are copied as they are + bool exact = true; + if (other_data.min.GetSize() > 0) { + data.min = AssignBound(stats, other_data.min, true, exact); + } + if (other_data.max.GetSize() > 0) { + data.max = AssignBound(stats, other_data.max, false, exact); + } + data.min_exact = other_data.min_exact; + data.max_exact = other_data.max_exact; +} + +//! The bounds enclose every value, so a comparison the bounds decide is decided for every value; a bound that is not +//! attained only loses pruning power, never correctness +static FilterPropagateResult CheckZonemapBound(const string_t &min, const string_t &max, ExpressionType comparison_type, + const string_t &constant) { + const int min_cmp = CompareBound(constant, min, true); + const int max_cmp = CompareBound(constant, max, false); + const bool in_range = min_cmp >= 0 && max_cmp <= 0; + const bool exact_range = min_cmp == 0 && max_cmp == 0; + switch (comparison_type) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOT_DISTINCT_FROM: + if (exact_range) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + return in_range ? FilterPropagateResult::NO_PRUNING_POSSIBLE : FilterPropagateResult::FILTER_ALWAYS_FALSE; + case ExpressionType::COMPARE_NOTEQUAL: + case ExpressionType::COMPARE_DISTINCT_FROM: + if (!in_range) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + return exact_range ? FilterPropagateResult::FILTER_ALWAYS_FALSE : FilterPropagateResult::NO_PRUNING_POSSIBLE; + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + if (min_cmp <= 0) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + return max_cmp <= 0 ? FilterPropagateResult::NO_PRUNING_POSSIBLE : FilterPropagateResult::FILTER_ALWAYS_FALSE; + case ExpressionType::COMPARE_GREATERTHAN: + if (min_cmp < 0) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + return max_cmp < 0 ? FilterPropagateResult::NO_PRUNING_POSSIBLE : FilterPropagateResult::FILTER_ALWAYS_FALSE; + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + if (max_cmp >= 0) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + return min_cmp >= 0 ? FilterPropagateResult::NO_PRUNING_POSSIBLE : FilterPropagateResult::FILTER_ALWAYS_FALSE; + case ExpressionType::COMPARE_LESSTHAN: + if (max_cmp > 0) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + return min_cmp > 0 ? FilterPropagateResult::NO_PRUNING_POSSIBLE : FilterPropagateResult::FILTER_ALWAYS_FALSE; + default: + throw InternalException("Expression type in zonemap check not implemented"); + } +} + +FilterPropagateResult BignumStats::CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type, + array_ptr constants) { + if (!HasMinMax(stats)) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + D_ASSERT(stats.CanHaveNoNull()); + auto &data = GetDataUnsafe(stats); + for (auto &constant_value : constants) { + D_ASSERT(constant_value.type() == stats.GetType()); + D_ASSERT(!constant_value.IsNull()); + auto &constant = StringValue::Get(constant_value); + auto prune_result = CheckZonemapBound(data.min, data.max, comparison_type, string_t(constant)); + if (prune_result == FilterPropagateResult::NO_PRUNING_POSSIBLE) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } else if (prune_result == FilterPropagateResult::FILTER_ALWAYS_TRUE) { + return FilterPropagateResult::FILTER_ALWAYS_TRUE; + } + } + return FilterPropagateResult::FILTER_ALWAYS_FALSE; +} + +void BignumStats::Serialize(const BaseStatistics &stats, Serializer &serializer) { + auto &data = GetDataUnsafe(stats); + serializer.WriteProperty(200, "has_min", data.has_min); + serializer.WriteProperty(201, "has_max", data.has_max); + serializer.WriteProperty(202, "min", data.min.GetString()); + serializer.WriteProperty(203, "max", data.max.GetString()); + serializer.WritePropertyWithDefault(204, "min_exact", data.min_exact, true); + serializer.WritePropertyWithDefault(205, "max_exact", data.max_exact, true); +} + +void BignumStats::Deserialize(Deserializer &deserializer, BaseStatistics &stats) { + auto &data = GetDataUnsafe(stats); + data.has_min = deserializer.ReadProperty(200, "has_min"); + data.has_max = deserializer.ReadProperty(201, "has_max"); + auto min = deserializer.ReadProperty(202, "min"); + auto max = deserializer.ReadProperty(203, "max"); + data.min_exact = deserializer.ReadPropertyWithExplicitDefault(204, "min_exact", true); + data.max_exact = deserializer.ReadPropertyWithExplicitDefault(205, "max_exact", true); + if (!min.empty()) { + data.min = AssignBound(stats, string_t(min), true, data.min_exact); + } + if (!max.empty()) { + data.max = AssignBound(stats, string_t(max), false, data.max_exact); + } +} + +child_list_t BignumStats::ToStruct(const BaseStatistics &stats) { + child_list_t result; + auto &data = GetDataUnsafe(stats); + if (data.has_min && data.has_max) { + result.emplace_back("min", data.min.GetSize() > 0 ? Min(stats) : Value(stats.GetType())); + result.emplace_back("max", data.max.GetSize() > 0 ? Max(stats) : Value(stats.GetType())); + result.emplace_back("min_exact", Value::BOOLEAN(data.min_exact)); + result.emplace_back("max_exact", Value::BOOLEAN(data.max_exact)); + } + return result; +} + +void BignumStats::Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count) { + auto &data = GetDataUnsafe(stats); + auto entries = vector.Values(); + for (idx_t i = 0; i < count; i++) { + auto idx = sel.get_index(i); + auto entry = entries[idx]; + if (!entry.IsValid()) { + continue; + } + auto value = entry.GetValue(); + // LCOV_EXCL_START + if (data.has_min && (data.min.GetSize() == 0 || CompareBound(value, data.min, true) < 0)) { + throw InternalException("Statistics mismatch: value is smaller than min.\nStatistics: %s\nVector: %s", + stats.ToString(), vector.ToString()); + } + if (data.has_max && (data.max.GetSize() == 0 || CompareBound(value, data.max, false) > 0)) { + throw InternalException("Statistics mismatch: value is bigger than max.\nStatistics: %s\nVector: %s", + stats.ToString(), vector.ToString()); + } + // LCOV_EXCL_STOP + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index d90dc2db8..2b8ee85d3 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -4,6 +4,16 @@ #include "duckdb/common/enums/checkpoint_abort.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/common/extension_type_info.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/parser/expression/cast_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/query_node.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/common/types/geometry.hpp" +#include "duckdb/common/types/variant.hpp" #include "duckdb/common/thread.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/main/attached_database.hpp" @@ -249,6 +259,191 @@ bool StorageManager::TargetAtLeastVersion(StorageVersion target_version, Storage return true; } +//! The argument types recorded in the signature of an AGGREGATE_STATE type (see EncodeStateParameters) +static vector AggregateStateArgumentTypes(const LogicalType &state_type) { + vector result; + auto ext_info = state_type.GetExtensionInfo(); + if (!ext_info) { + return result; + } + auto entry = ext_info->properties.find("parameters"); + if (entry == ext_info->properties.end() || entry->second.IsNull() || + entry->second.type().id() != LogicalTypeId::LIST) { + return result; + } + for (auto ¶meter : ListValue::GetChildren(entry->second)) { + if (parameter.IsNull()) { + continue; + } + if (parameter.type().id() == LogicalTypeId::TYPE) { + result.push_back(TypeValue::GetType(parameter)); + } else if (parameter.type().id() == LogicalTypeId::STRUCT) { + // a (type, value) pair of a parameter bound to a constant + auto &children = StructValue::GetChildren(parameter); + if (!children.empty() && !children[0].IsNull() && children[0].type().id() == LogicalTypeId::TYPE) { + result.push_back(TypeValue::GetType(children[0])); + } + } + } + return result; +} + +static string UnsupportedAtStorageVersion(AttachedDatabase &db, StorageVersion storage_version, const string &what, + StorageVersion required) { + return StringUtil::Format("%s are not supported in storage versions prior to %s (database %s is using storage " + "version %s)", + what, GetStorageVersionName(required, false), db.GetName(), + GetStorageVersionName(storage_version, false)); +} + +static string WideDecimalUnsupportedReason(AttachedDatabase &db, StorageVersion storage_version, + const string &subject) { + auto what = StringUtil::Format("DECIMAL %s wider than %d digits", subject, Decimal::MAX_WIDTH_INT128); + return UnsupportedAtStorageVersion(db, storage_version, what, Decimal::WIDE_VERSION_ADDED); +} + +bool StorageManager::ContainsWideDecimal(const LogicalType &logical_type) { + return TypeVisitor::Contains(logical_type, [&](const LogicalType &type) { + if (type.IsAggregateState()) { + for (auto &argument_type : AggregateStateArgumentTypes(type)) { + if (ContainsWideDecimal(argument_type)) { + return true; + } + } + return false; + } + return type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type)); + }); +} + +string StorageManager::GetUnsupportedPriorToVersionReason(const string &what, StorageVersion required) const { + D_ASSERT(IsPriorToVersion(required, GetStorageVersion())); + return UnsupportedAtStorageVersion(db, GetStorageVersion(), what, required); +} + +string StorageManager::GetUnsupportedTypeReason(const LogicalType &logical_type) const { + const auto storage_version = GetStorageVersion(); + auto unsupported = [&](const string &what, StorageVersion required) { + return UnsupportedAtStorageVersion(db, storage_version, what, required); + }; + string reason; + TypeVisitor::Contains(logical_type, [&](const LogicalType &type) { + if (type.IsAggregateState()) { + if (storage_version < StorageVersion::V2_0_0) { + reason = unsupported("Aggregate state columns", StorageVersion::V2_0_0); + return true; + } + // the argument types of the aggregate are stored with the state + for (auto &argument_type : AggregateStateArgumentTypes(type)) { + reason = GetUnsupportedTypeReason(argument_type); + if (!reason.empty()) { + return true; + } + } + return false; + } + switch (type.id()) { + case LogicalTypeId::STRUCT: + if (storage_version < StorageVersion::V2_0_0 && StructType::GetChildCount(type) == 0) { + reason = unsupported("Empty STRUCT columns", StorageVersion::V2_0_0); + } + break; + case LogicalTypeId::TUPLE: + // TUPLEs are stored as unnamed STRUCTs, which older engines reject; the unnamed STRUCTs of an older file + // are deserialized as TUPLE while loading and must stay attachable + if (storage_version < StorageVersion::V2_0_0 && IsLoaded()) { + reason = unsupported("TUPLE columns", StorageVersion::V2_0_0); + } + break; + case LogicalTypeId::DECIMAL: + // decimals wider than 38 digits are stored as BIGNUM blobs, which older engines cannot read + if (storage_version < Decimal::WIDE_VERSION_ADDED && Decimal::IsWide(DecimalType::GetWidth(type))) { + reason = WideDecimalUnsupportedReason(db, storage_version, "columns"); + } + break; + case LogicalTypeId::VARIANT: + if (storage_version < Variant::VERSION_ADDED) { + reason = unsupported("VARIANT columns", Variant::VERSION_ADDED); + } + break; + case LogicalTypeId::GEOMETRY: + if (GeoType::HasCRS(type) && storage_version < Geometry::VERSION_ADDED) { + auto required = GetStorageVersionName(Geometry::VERSION_ADDED, false); + auto current = GetStorageVersionName(storage_version, false); + + // TODO: Turn this into a hard error + auto &logger = Logger::Get(db.GetDatabase()); + logger.WriteLog(DefaultLogType::NAME, LogLevel::LOG_WARNING, + "GEOMETRY columns with coordinate reference system identifiers are not supported in " + "storage versions prior " + "to %s (database %s is using storage version %s). CRS will not be persisted.", + required, db.GetName(), current); + } + break; + default: + break; + } + return !reason.empty(); + }); + return reason; +} + +void StorageManager::CheckTypeIsSupported(const LogicalType &type) const { + auto reason = GetUnsupportedTypeReason(type); + if (!reason.empty()) { + throw InvalidInputException(reason); + } +} + +string StorageManager::GetUnsupportedDecimalWidthReason(const LogicalType &type, const string &subject) const { + const auto storage_version = GetStorageVersion(); + if (storage_version >= Decimal::WIDE_VERSION_ADDED || !ContainsWideDecimal(type)) { + return string(); + } + return WideDecimalUnsupportedReason(db, storage_version, subject); +} + +void StorageManager::CheckDecimalWidthIsSupported(const LogicalType &type) const { + auto reason = GetUnsupportedDecimalWidthReason(type); + if (!reason.empty()) { + throw InvalidInputException(reason); + } +} + +void StorageManager::CheckExpressionDecimalsAreSupported(const ParsedExpression &expression) const { + if (GetStorageVersion() >= StorageVersion::V2_0_0) { + // from v2.0.0 on a CAST stores its target as a type expression, which the reading engine binds itself + return; + } + // a work list instead of recursion, the expression tree is user data + vector> work; + work.emplace_back(expression); + while (!work.empty()) { + auto &expr = work.back().get(); + work.pop_back(); + switch (expr.GetExpressionClass()) { + case ExpressionClass::CAST: + CheckDecimalWidthIsSupported(UnboundType::TryDefaultBind(expr.Cast().TargetType())); + break; + case ExpressionClass::SUBQUERY: + CheckQueryDecimalsAreSupported(*expr.Cast().Subquery()->node); + break; + default: + break; + } + ParsedExpressionIterator::EnumerateChildren(expr, + [&](const ParsedExpression &child) { work.emplace_back(child); }); + } +} + +void StorageManager::CheckQueryDecimalsAreSupported(QueryNode &node) const { + if (GetStorageVersion() >= StorageVersion::V2_0_0) { + return; + } + ParsedExpressionIterator::EnumerateQueryNodeChildren( + node, [&](unique_ptr &child) { CheckExpressionDecimalsAreSupported(*child); }); +} + bool StorageManager::HasWAL() const { if (InMemory() || read_only || !load_complete) { return false; diff --git a/src/duckdb/src/storage/table/row_group_reorderer.cpp b/src/duckdb/src/storage/table/row_group_reorderer.cpp index 315230a31..47bb46058 100644 --- a/src/duckdb/src/storage/table/row_group_reorderer.cpp +++ b/src/duckdb/src/storage/table/row_group_reorderer.cpp @@ -230,6 +230,13 @@ optional_ptr> RowGroupReorderer::GetNextRowGroup(SegmentNo Value RowGroupReorderer::RetrieveStat(const BaseStatistics &stats, OrderByStatistics order_by, OrderByColumnType column_type) { if (column_type == OrderByColumnType::NUMERIC) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + // the bignum_t tier of decimals + if (!BignumStats::HasMinMax(stats)) { + return Value(); + } + return order_by == OrderByStatistics::MIN ? BignumStats::Min(stats) : BignumStats::Max(stats); + } if (!NumericStats::HasMinMax(stats)) { return Value(); } diff --git a/src/duckdb/src/storage/table/variant_column_data.cpp b/src/duckdb/src/storage/table/variant_column_data.cpp index 4edd72240..e59695a34 100644 --- a/src/duckdb/src/storage/table/variant_column_data.cpp +++ b/src/duckdb/src/storage/table/variant_column_data.cpp @@ -4,7 +4,11 @@ #include "duckdb/storage/table/variant_column_data.hpp" #include "duckdb/common/serializer/deserializer.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/variant_iterator.hpp" #include "duckdb/function/variant/variant_shredding.hpp" +#include "duckdb/main/attached_database.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" #include "duckdb/storage/statistics/variant_stats.hpp" @@ -13,6 +17,7 @@ #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/table/scan_state.hpp" #include "duckdb/storage/table/struct_column_data.hpp" +#include "duckdb/storage/storage_manager.hpp" #include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/main/config.hpp" @@ -377,6 +382,57 @@ struct VariantShreddedAppendInput { } // namespace +//! Whether a VARIANT value holds a decimal wider than 38 digits, which engines before wide decimals cannot read +static bool ContainsWideDecimal(const VariantNode &root) { + // an explicit work list, deeply nested values must not consume stack + vector pending; + pending.push_back(root); + while (!pending.empty()) { + auto node = pending.back(); + pending.pop_back(); + switch (node.GetTypeId()) { + case VariantLogicalType::DECIMAL: + if (Decimal::IsWide(node.GetDecimalProperties().width)) { + return true; + } + break; + case VariantLogicalType::OBJECT: + for (auto &entry : node.GetObjectChildren()) { + pending.push_back(entry.value); + } + break; + case VariantLogicalType::ARRAY: + for (auto child : node.GetArrayChildren()) { + pending.push_back(child); + } + break; + default: + break; + } + } + return false; +} + +//! The unshredded payload of a wide decimal is stored as it is, so a storage version before wide decimals refuses it +static void CheckWideDecimals(StorageManager &storage_manager, const Vector &vector, idx_t count) { + const auto storage_version = storage_manager.GetStorageVersion(); + if (storage_version >= Decimal::WIDE_VERSION_ADDED) { + return; + } + VariantIterator iterator(vector); + for (idx_t row = 0; row < count; row++) { + if (!iterator.RowIsValid(row) || !ContainsWideDecimal(iterator.Root(row))) { + continue; + } + auto required = GetStorageVersionName(Decimal::WIDE_VERSION_ADDED, false); + auto current = GetStorageVersionName(storage_version, false); + throw InvalidInputException("DECIMAL values wider than %d digits cannot be stored in a VARIANT column in " + "storage versions prior to %s (database %s is using storage version %s)", + Decimal::MAX_WIDTH_INT128, required, storage_manager.GetAttached().GetName(), + current); + } +} + void VariantColumnData::Append(ColumnAppendState &state, const Vector &vector, idx_t count) { if (vector.GetVectorType() != VectorType::FLAT_VECTOR) { Vector append_vector(Vector::Ref(vector)); @@ -384,6 +440,7 @@ void VariantColumnData::Append(ColumnAppendState &state, const Vector &vector, i Append(state, append_vector, count); return; } + CheckWideDecimals(GetStorageManager(), vector, count); // append the null values validity->Append(state.child_appends[0], vector, count); @@ -754,6 +811,13 @@ unique_ptr VariantColumnData::Checkpoint(const RowGroup & if (shredded_type.id() == LogicalTypeId::INVALID) { shredded_type = GetShreddedType(); } + if (GetStorageManager().GetStorageVersion() < Decimal::WIDE_VERSION_ADDED && + TypeVisitor::Contains(shredded_type, [](const LogicalType &type) { + return type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type)); + })) { + // a shredded column of a decimal wider than 38 digits cannot be stored in this storage version + should_shred = false; + } D_ASSERT(shredded_type.id() == LogicalTypeId::STRUCT); auto &type_entries = StructType::GetChildTypes(shredded_type); if (type_entries.size() != 2) { diff --git a/src/duckdb/src/storage/table_index_list.cpp b/src/duckdb/src/storage/table_index_list.cpp index e4011dfd0..b68a62b56 100644 --- a/src/duckdb/src/storage/table_index_list.cpp +++ b/src/duckdb/src/storage/table_index_list.cpp @@ -357,7 +357,8 @@ shared_ptr TableIndexList::FindEntry(idx_t index_oid) const { return nullptr; } -void TableIndexList::Bind(ClientContext &context, DataTableInfo &table_info, const optional &index_type) { +void TableIndexList::Bind(ClientContext &context, DataTableInfo &table_info, const optional &index_type, + bool skip_mismatched_keys) { { // Early-out, if we have no unbound indexes. annotated_lock_guard lock(index_entries_lock); @@ -381,12 +382,15 @@ void TableIndexList::Bind(ClientContext &context, DataTableInfo &table_info, con } annotated_unique_lock lock(index_entries_lock); + // Indexes left unbound because their stored keys do not match. + vector> skipped; // Busy-spin trying to bind all indexes. while (true) { shared_ptr index_entry; for (auto &entry : index_entries) { if (entry->GetBindState() != IndexBindState::BOUND && - (!index_type || entry->GetIndexType() == *index_type)) { + (!index_type || entry->GetIndexType() == *index_type) && + std::find(skipped.begin(), skipped.end(), entry) == skipped.end()) { index_entry = entry; break; } @@ -429,7 +433,7 @@ void TableIndexList::Bind(ClientContext &context, DataTableInfo &table_info, con for (auto &col : table.GetColumns().Physical()) { physical_column_types.push_back(col.Type()); } - bound_idx = index_entry->Bind(idx_binder, physical_column_types); + bound_idx = index_entry->Bind(idx_binder, physical_column_types, skip_mismatched_keys); } catch (...) { // Leave the index unbound, so that a later attempt binds it instead of waiting for this one forever. lock.lock(); @@ -437,8 +441,15 @@ void TableIndexList::Bind(ClientContext &context, DataTableInfo &table_info, con throw; } - // Commit the bound index to the index entry. lock.lock(); + if (!bound_idx) { + // The index stays unbound, a write that has to maintain it refuses it. + index_entry->SetBindState(IndexBindState::UNBOUND); + skipped.push_back(index_entry); + continue; + } + + // Commit the bound index to the index entry. auto current_entry = std::find(index_entries.begin(), index_entries.end(), index_entry); if (current_entry == index_entries.end()) { continue; diff --git a/src/duckdb/ub_src_common_types.cpp b/src/duckdb/ub_src_common_types.cpp index 317b7e6a8..dfde44c30 100644 --- a/src/duckdb/ub_src_common_types.cpp +++ b/src/duckdb/ub_src_common_types.cpp @@ -2,6 +2,8 @@ #include "src/common/types/bignum.cpp" +#include "src/common/types/bignum_decimal.cpp" + #include "src/common/types/bit.cpp" #include "src/common/types/blob.cpp" diff --git a/src/duckdb/ub_src_storage_statistics.cpp b/src/duckdb/ub_src_storage_statistics.cpp index 4af74db3d..91a7adb9c 100644 --- a/src/duckdb/ub_src_storage_statistics.cpp +++ b/src/duckdb/ub_src_storage_statistics.cpp @@ -2,6 +2,8 @@ #include "src/storage/statistics/base_statistics.cpp" +#include "src/storage/statistics/bignum_stats.cpp" + #include "src/storage/statistics/column_statistics.cpp" #include "src/storage/statistics/distinct_statistics.cpp"