diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index 36ef2f3d2..06c87c9f1 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -2,6 +2,9 @@ #include "core_functions/aggregate/sum_helpers.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/bignum.hpp" +#include "duckdb/common/bignum_limbs.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -509,13 +512,80 @@ unique_ptr BindDecimalSum(BindAggregateFunctionInput &input) { struct BignumState { bool is_set; - BignumIntermediate value; + //! Whether the sum has outgrown the hugeint_t accumulator and lives in the arena-allocated wide value + bool is_wide; + //! The sum while it fits a hugeint_t + hugeint_t small; + //! The sum once it does not + BignumIntermediate wide; }; struct BignumOperation { + //! The magnitude of an input of at most 16 bytes as a hugeint_t; false when it does not fit + static bool TryGetSmall(const BignumIntermediate &input, hugeint_t &result) { + if (input.size > 2 * BignumLimb::BYTES) { + return false; + } + const int64_t end = input.size; + uint64_t lo = BignumLimb::LoadAbsolute(input.data, input.is_negative, end); + uint64_t hi = + BignumLimb::LoadAbsolute(input.data, input.is_negative, end - static_cast(BignumLimb::BYTES)); + if (hi >> 63) { + // a magnitude of 2^127 or more + return false; + } + if (input.is_negative) { + // two's complement of the magnitude + hi = ~hi + (lo == 0); + lo = ~lo + 1; + } + result = hugeint_t(static_cast(hi), lo); + return true; + } + + //! Writes a hugeint_t as a BIGNUM blob and returns its size; blob needs room for 16 + header bytes + static idx_t EncodeSmall(hugeint_t value, char *blob) { + const bool is_negative = value.upper < 0; + uint64_t hi = static_cast(value.upper); + uint64_t lo = value.lower; + if (is_negative) { + hi = ~hi + (lo == 0); + lo = ~lo + 1; + } + const idx_t byte_count = BignumLimb::ByteCount(hi, lo); + Bignum::SetHeader(blob, byte_count, is_negative); + BignumLimb::StoreMagnitude(reinterpret_cast(blob + Bignum::BIGNUM_HEADER_SIZE), byte_count, hi, lo, + is_negative); + return byte_count + Bignum::BIGNUM_HEADER_SIZE; + } + + //! Adds a hugeint_t to the wide value + static void AddSmallToWide(BignumState &state, hugeint_t value, ArenaAllocator &allocator) { + char blob[2 * BignumLimb::BYTES + Bignum::BIGNUM_HEADER_SIZE]; + const auto size = EncodeSmall(value, blob); + BignumIntermediate rhs(reinterpret_cast(blob), size); + state.wide.AddInPlace(allocator, rhs); + } + + //! Moves the sum from the hugeint_t accumulator to the wide value + static void Widen(BignumState &state, ArenaAllocator &allocator) { + D_ASSERT(!state.is_wide); + state.wide.Initialize(allocator); + AddSmallToWide(state, state.small, allocator); + state.is_wide = true; + } + template static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input, idx_t count) { + hugeint_t value; + hugeint_t total; + if (!state.is_wide && TryGetSmall(BignumIntermediate(input), value) && + Hugeint::TryMultiply(value, hugeint_t(static_cast(count)), total) && + Hugeint::TryAddInPlace(state.small, total)) { + state.is_set = true; + return; + } for (idx_t i = 0; i < count; i++) { Operation(state, input, unary_input); } @@ -523,12 +593,16 @@ struct BignumOperation { template static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { - if (!state.is_set) { - state.is_set = true; - state.value.Initialize(unary_input.input.allocator); + const BignumIntermediate rhs(input); + state.is_set = true; + if (!state.is_wide) { + hugeint_t value; + if (TryGetSmall(rhs, value) && Hugeint::TryAddInPlace(state.small, value)) { + return; + } + Widen(state, unary_input.input.allocator); } - BignumIntermediate rhs(input); - state.value.AddInPlace(unary_input.input.allocator, rhs); + state.wide.AddInPlace(unary_input.input.allocator, rhs); } template @@ -537,18 +611,34 @@ struct BignumOperation { return; } if (!target.is_set) { - target.value.Initialize(input.allocator); + // the target is still zero: a plain add, the small sum is copied, the wide one needs its own allocation target.is_set = true; } - target.value.AddInPlace(input.allocator, source.value); + if (!target.is_wide) { + if (!source.is_wide && Hugeint::TryAddInPlace(target.small, source.small)) { + return; + } + Widen(target, input.allocator); + } + if (source.is_wide) { + target.wide.AddInPlace(input.allocator, source.wide); + } else { + AddSmallToWide(target, source.small, input.allocator); + } } template static void Finalize(STATE &state, TARGET_TYPE &target, AggregateFinalizeData &finalize_data) { + // the state is only read: it is exported while other threads may still read it if (!state.is_set) { finalize_data.ReturnNull(); + } else if (state.is_wide) { + target = state.wide.ToBignum(finalize_data.input.allocator); } else { - target = state.value.ToBignum(finalize_data.input.allocator); + auto blob = reinterpret_cast( + finalize_data.input.allocator.Allocate(2 * BignumLimb::BYTES + Bignum::BIGNUM_HEADER_SIZE)); + const auto size = EncodeSmall(state.small, blob); + target = bignum_t(string_t(blob, UnsafeNumericCast(size))); } } 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 08e1a0abf..02db38ae3 100644 --- a/src/duckdb/extension/core_functions/scalar/array/array_value.cpp +++ b/src/duckdb/extension/core_functions/scalar/array/array_value.cpp @@ -37,7 +37,7 @@ void ArrayValueFunction(DataChunk &args, ExpressionState &state, Vector &result) for (idx_t i = 0; i < num_rows; i++) { for (idx_t j = 0; j < num_columns; j++) { - auto val = args.GetValue(j, i).DefaultCastAs(child_type); + auto val = args.GetValue(j, i).CastAs(state.GetContext(), child_type); child.SetValue((i * num_columns) + j, val); } } diff --git a/src/duckdb/extension/core_functions/scalar/generic/binning.cpp b/src/duckdb/extension/core_functions/scalar/generic/binning.cpp index f393f61ef..d35ee31b5 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/binning.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/binning.cpp @@ -475,7 +475,7 @@ void EquiWidthBinFunction(DataChunk &args, ExpressionState &state, Vector &resul } return result_bins; }); - VectorOperations::DefaultCast(intermediate_result, result, args.size()); + VectorOperations::Cast(state.GetContext(), intermediate_result, result, args.size()); } void UnsupportedEquiWidth(DataChunk &args, ExpressionState &state, Vector &) { diff --git a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp index e8de8c22d..0b060ea0d 100644 --- a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp +++ b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp @@ -165,7 +165,7 @@ static unique_ptr PropagateAbsStats(ClientContext &context, Func } double min_val, max_val; - if (current_min == 0 || current_max == 0) { + if (current_min == 0) { // Unlike integers, floating point abs cannot be removed for zero: abs(-0.0) clears the sign bit. min_val = AbsOperator::Operation(current_min); max_val = AbsOperator::Operation(current_max); @@ -751,7 +751,7 @@ unique_ptr ResolveDecimalRoundPrecision(BoundScalarFunction &bound template void DecimalRoundPrecisionResolveTypes(ResolveScalarFunctionTypesInput &input) { - auto val = input.GetNonNullConstant(1).DefaultCastAs(LogicalType::INTEGER); + auto val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::INTEGER); ResolveDecimalRoundPrecision(input.GetBoundFunction(), input.GetArgumentType(0), IntegerValue::Get(val)); } @@ -760,7 +760,7 @@ void DecimalRoundPrecisionResolveTypes(ResolveScalarFunctionTypesInput &input) { template unique_ptr BindDecimalRoundPrecision(BindScalarFunctionInput &input) { auto &bound_function = input.GetBoundFunction(); - auto val = input.GetNonNullConstant(1).DefaultCastAs(LogicalType::INTEGER); + auto val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::INTEGER); return ResolveDecimalRoundPrecision( bound_function, bound_function.GetLogicalArguments()[0], IntegerValue::Get(val)); } diff --git a/src/duckdb/extension/json/include/json_executors.hpp b/src/duckdb/extension/json/include/json_executors.hpp index 210e211c6..7f8144cd5 100644 --- a/src/duckdb/extension/json/include/json_executors.hpp +++ b/src/duckdb/extension/json/include/json_executors.hpp @@ -103,7 +103,7 @@ struct JSONExecutors { casted_paths = make_uniq(Vector::Ref(args.data[1])); } else { casted_paths = make_uniq(LogicalTypeId::VARCHAR); - VectorOperations::DefaultCast(args.data[1], *casted_paths, args.size(), true); + VectorOperations::Cast(state.GetContext(), args.data[1], *casted_paths, args.size(), true); } BinaryExecutor::Execute( inputs, *casted_paths, result, args.size(), [&](string_t input, string_t path) -> optional { diff --git a/src/duckdb/extension/json/include/json_functions.hpp b/src/duckdb/extension/json/include/json_functions.hpp index a77283c6b..3816a8639 100644 --- a/src/duckdb/extension/json/include/json_functions.hpp +++ b/src/duckdb/extension/json/include/json_functions.hpp @@ -31,7 +31,7 @@ struct JSONReadFunctionData : public FunctionData { JSONReadFunctionData(bool constant, string path_p, idx_t len, JSONCommon::JSONPathType path_type); unique_ptr Copy() const override; bool Equals(const FunctionData &other_p) const override; - static JSONCommon::JSONPathType CheckPath(const Value &path_val, string &path, idx_t &len); + static JSONCommon::JSONPathType CheckPath(Context &context, const Value &path_val, string &path, idx_t &len); static void ResolveTypes(ResolveScalarFunctionTypesInput &input); static unique_ptr Bind(BindScalarFunctionInput &input); diff --git a/src/duckdb/extension/json/json_functions.cpp b/src/duckdb/extension/json/json_functions.cpp index f82779f4f..9fe7fd5cb 100644 --- a/src/duckdb/extension/json/json_functions.cpp +++ b/src/duckdb/extension/json/json_functions.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/client_context.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/common/vector/string_vector.hpp" @@ -17,11 +18,11 @@ namespace duckdb { using JSONPathType = JSONCommon::JSONPathType; -JSONPathType JSONReadFunctionData::CheckPath(const Value &path_val, string &path, idx_t &len) { +JSONPathType JSONReadFunctionData::CheckPath(Context &context, const Value &path_val, string &path, idx_t &len) { if (path_val.IsNull()) { throw BinderException("JSON path cannot be NULL"); } - const auto path_str_val = path_val.DefaultCastAs(LogicalType::VARCHAR); + const auto path_str_val = path_val.CastAs(context, LogicalType::VARCHAR); auto path_str = path_str_val.GetValueUnsafe(); len = path_str.GetSize(); const auto ptr = path_str.GetData(); @@ -84,7 +85,7 @@ unique_ptr JSONReadFunctionData::Bind(BindScalarFunctionInput &inp auto path_val = input.TryGetConstant(1); if (path_val && !path_val->IsNull()) { constant = true; - path_type = CheckPath(*path_val, path, len); + path_type = CheckPath(input.GetClientContext().GetContext(), *path_val, path, len); } if (path_type == JSONCommon::JSONPathType::WILDCARD) { bound_function.SetReturnType(LogicalType::LIST(bound_function.GetReturnType())); @@ -128,7 +129,8 @@ unique_ptr JSONReadManyFunctionData::Bind(BindScalarFunctionInput for (auto &path_val : ListValue::GetChildren(paths_val)) { paths.emplace_back(""); lens.push_back(0); - if (JSONReadFunctionData::CheckPath(path_val, paths.back(), lens.back()) == JSONPathType::WILDCARD) { + if (JSONReadFunctionData::CheckPath(input.GetClientContext().GetContext(), path_val, paths.back(), + lens.back()) == JSONPathType::WILDCARD) { throw BinderException("Cannot have wildcards in JSON path when supplying multiple paths"); } } diff --git a/src/duckdb/extension/json/json_functions/copy_json.cpp b/src/duckdb/extension/json/json_functions/copy_json.cpp index 52033a932..a92a724a4 100644 --- a/src/duckdb/extension/json/json_functions/copy_json.cpp +++ b/src/duckdb/extension/json/json_functions/copy_json.cpp @@ -236,8 +236,8 @@ static BoundStatement CopyToJSONPlanInternal(Binder &binder, CopyStatement &stmt if (!option_values.empty() && option_values.back().IsNull()) { ThrowJSONCopyNullException(format, option_name); } - array_output = - option_values.empty() || BooleanValue::Get(option_values.back().DefaultCastAs(LogicalTypeId::BOOLEAN)); + array_output = option_values.empty() || + BooleanValue::Get(option_values.back().CastAs(binder.context, LogicalTypeId::BOOLEAN)); } else if (is_geojson && (option_name == "geometry_column" || option_name == "id_column")) { // NULL explicitly unsets these, so unlike the other options a NULL value is meaningful here if (option_values.size() != 1) { diff --git a/src/duckdb/extension/json/json_functions/json_modify.cpp b/src/duckdb/extension/json/json_functions/json_modify.cpp index 934f06569..fd0b89a95 100644 --- a/src/duckdb/extension/json/json_functions/json_modify.cpp +++ b/src/duckdb/extension/json/json_functions/json_modify.cpp @@ -64,7 +64,7 @@ struct JSONModifyFunctionData : public FunctionData { const auto path_val = ExpressionExecutor::EvaluateScalar(context, *arguments[1]); if (!path_val.IsNull()) { constant = true; - path = path_val.DefaultCastAs(LogicalType::VARCHAR).GetValue(); + path = path_val.CastAs(context, LogicalType::VARCHAR).GetValue(); } } return make_uniq(constant, std::move(path)); diff --git a/src/duckdb/extension/json/json_functions/json_table_in_out.cpp b/src/duckdb/extension/json/json_functions/json_table_in_out.cpp index 633147f80..3df2ad95d 100644 --- a/src/duckdb/extension/json/json_functions/json_table_in_out.cpp +++ b/src/duckdb/extension/json/json_functions/json_table_in_out.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/client_context.hpp" #include "json_common.hpp" #include "json_functions.hpp" #include "duckdb/common/atomic.hpp" @@ -309,7 +310,8 @@ struct JSONTableInOutResult { }; template -static void InitializeLocalState(JSONTableInOutLocalState &lstate, DataChunk &input, JSONTableInOutResult &result) { +static void InitializeLocalState(Context &context, JSONTableInOutLocalState &lstate, DataChunk &input, + JSONTableInOutResult &result) { lstate.total_count = 0; // Parse path, default to root if not given @@ -322,7 +324,8 @@ static void InitializeLocalState(JSONTableInOutLocalState &lstate, DataChunk &in path_value = path_values[lstate.input_row].GetValue(); } - if (JSONReadFunctionData::CheckPath(path_value, lstate.path, lstate.len) == JSONCommon::JSONPathType::WILDCARD) { + if (JSONReadFunctionData::CheckPath(context, path_value, lstate.path, lstate.len) == + JSONCommon::JSONPathType::WILDCARD) { throw BinderException("Wildcard JSON path not supported in json_each/json_tree"); } @@ -383,8 +386,8 @@ static bool JSONTableInOutHandleValue(JSONTableInOutLocalState &lstate, JSONTabl } template -static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFunctionInput &data_p, DataChunk &input, - DataChunk &output) { +static OperatorResultType JSONTableInOutFunction(ExecutionContext &context, TableFunctionInput &data_p, + DataChunk &input, DataChunk &output) { auto &gstate = data_p.global_state->Cast(); auto &lstate = data_p.local_state->Cast(); @@ -393,7 +396,7 @@ static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFuncti if (lstate.input_row >= input.size()) { return OperatorResultType::NEED_MORE_INPUT; } - InitializeLocalState(lstate, input, result); + InitializeLocalState(context.client.GetContext(), lstate, input, result); lstate.initialized = true; } diff --git a/src/duckdb/extension/json/json_functions/json_transform.cpp b/src/duckdb/extension/json/json_functions/json_transform.cpp index dca676a8a..39720c58f 100644 --- a/src/duckdb/extension/json/json_functions/json_transform.cpp +++ b/src/duckdb/extension/json/json_functions/json_transform.cpp @@ -93,7 +93,7 @@ static unique_ptr JSONTransformBind(BindScalarFunctionInput &input if (structure_val.IsNull() || arguments[1]->GetReturnType() == LogicalTypeId::SQLNULL) { bound_function.SetReturnType(LogicalTypeId::SQLNULL); } else { - auto json_structure_val = structure_val.DefaultTryCastAs(LogicalType::JSON()); + auto json_structure_val = structure_val.TryCastAs(input.GetClientContext(), LogicalType::JSON()); if (!json_structure_val) { throw BinderException("Cannot cast JSON structure to string"); } diff --git a/src/duckdb/extension/parquet/parquet_crypto.cpp b/src/duckdb/extension/parquet/parquet_crypto.cpp index 2f8a08513..922e671ad 100644 --- a/src/duckdb/extension/parquet/parquet_crypto.cpp +++ b/src/duckdb/extension/parquet/parquet_crypto.cpp @@ -154,7 +154,7 @@ ParquetEncryptionConfig::ParquetEncryptionConfig(ClientContext &context, const V throw BinderException("Parquet encryption_config %s cannot be NULL", struct_key); } if (struct_key == "footer_key") { - const auto footer_key_name = StringValue::Get(children[i].DefaultCastAs(LogicalType::VARCHAR)); + const auto footer_key_name = StringValue::Get(children[i].CastAs(context, LogicalType::VARCHAR)); if (!keys.HasKey(footer_key_name)) { throw BinderException( "No key with name \"%s\" exists. Add it with PRAGMA add_parquet_key('','');", @@ -164,7 +164,7 @@ ParquetEncryptionConfig::ParquetEncryptionConfig(ClientContext &context, const V const auto &keys = ParquetKeys::Get(context); footer_key = keys.GetKey(footer_key_name); } else if (struct_key == "footer_key_value") { - footer_key = StringValue::Get(children[i].DefaultCastAs(LogicalType::BLOB)); + footer_key = StringValue::Get(children[i].CastAs(context, LogicalType::BLOB)); } else if (struct_key == "column_keys") { throw NotImplementedException("Parquet encryption_config column_keys not yet implemented"); } else { @@ -284,13 +284,16 @@ class DecryptionTransport : public TTransport { uint32_t read_virt(uint8_t *buf, uint32_t len) override { const uint32_t result = len; - if (len > transport_remaining - ParquetCrypto::TAG_BYTES + read_buffer_size - read_buffer_offset) { - throw InvalidInputException("Too many bytes requested from crypto buffer"); + // The page header and encrypted module must agree on the decrypted size before decryption. + const auto remaining = transport_remaining - ParquetCrypto::TAG_BYTES + read_buffer_size - read_buffer_offset; + if (len != remaining) { + throw DataCorruptionException("Encrypted Parquet module size mismatch (expected %u bytes, actual %u bytes)", + len, remaining); } while (len != 0) { if (read_buffer_offset == read_buffer_size) { - ReadBlock(buf); + ReadBlock(buf, len); } const auto next = MinValue(read_buffer_size - read_buffer_offset, len); read_buffer_offset += next; @@ -350,20 +353,17 @@ class DecryptionTransport : public TTransport { } } - void ReadBlock(uint8_t *buf) { + void ReadBlock(uint8_t *buf, uint32_t buffer_size) { // Read from transport into read_buffer at one AES block size offset (up to the tag) read_buffer_size = MinValue(ParquetCrypto::CRYPTO_BLOCK_SIZE, transport_remaining - ParquetCrypto::TAG_BYTES); + if (read_buffer_size > buffer_size) { + throw DataCorruptionException("Encrypted Parquet block exceeds the destination buffer size"); + } transport_remaining -= trans.read(read_buffer + ParquetCrypto::BLOCK_SIZE, read_buffer_size); - // Decrypt from read_buffer + block size into read_buffer start (decryption can trail behind in same buffer) -#ifdef DEBUG - auto size = aes->Process(read_buffer + ParquetCrypto::BLOCK_SIZE, read_buffer_size, buf, - ParquetCrypto::CRYPTO_BLOCK_SIZE + ParquetCrypto::BLOCK_SIZE); + // Decrypt directly into the destination only after checking that the whole block fits. + auto size = aes->Process(read_buffer + ParquetCrypto::BLOCK_SIZE, read_buffer_size, buf, buffer_size); D_ASSERT(size == read_buffer_size); -#else - aes->Process(read_buffer + ParquetCrypto::BLOCK_SIZE, read_buffer_size, buf, - ParquetCrypto::CRYPTO_BLOCK_SIZE + ParquetCrypto::BLOCK_SIZE); -#endif read_buffer_offset = 0; } @@ -395,12 +395,12 @@ class SimpleReadTransport : public TTransport { uint32_t read_virt(uint8_t *buf, uint32_t len) override { const auto remaining = read_buffer_size - read_buffer_offset; - if (len > remaining) { - return remaining; + const auto read_size = MinValue(len, remaining); + if (read_size > 0) { + memcpy(buf, read_buffer + read_buffer_offset, read_size); + read_buffer_offset += read_size; } - memcpy(buf, read_buffer + read_buffer_offset, len); - read_buffer_offset += len; - return len; + return read_size; } private: diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index fa267a6cc..b56dfd409 100644 --- a/src/duckdb/extension/parquet/parquet_extension.cpp +++ b/src/duckdb/extension/parquet/parquet_extension.cpp @@ -326,11 +326,12 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun } bind_data->data_page_size_limit = val; } else if (option_name == "write_bloom_filter") { - bind_data->enable_bloom_filters = BooleanValue::Get(option_values[0].DefaultCastAs(LogicalType::BOOLEAN)); + bind_data->enable_bloom_filters = BooleanValue::Get(option_values[0].CastAs(context, LogicalType::BOOLEAN)); } else if (option_name == "bloom_filter_fallback_max_bytes") { - bind_data->bloom_filter_fallback_max_bytes = ParseBytesArg(option_name, option_values[0]); + bind_data->bloom_filter_fallback_max_bytes = + ParseBytesArg(context.GetContext(), option_name, option_values[0]); } else if (option_name == "write_page_index") { - bind_data->write_page_index = BooleanValue::Get(option_values[0].DefaultCastAs(LogicalType::BOOLEAN)); + bind_data->write_page_index = BooleanValue::Get(option_values[0].CastAs(context, LogicalType::BOOLEAN)); } else if (option_name == "bloom_filter_false_positive_ratio") { auto val = option_values[0].GetValue(); if (!(val > 0 && val <= 1)) { @@ -370,7 +371,7 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun } } else if (option_name == "write_timestamp_as_int96") { bind_data->write_timestamp_as_int96 = - BooleanValue::Get(option_values[0].DefaultCastAs(LogicalType::BOOLEAN)); + BooleanValue::Get(option_values[0].CastAs(context, LogicalType::BOOLEAN)); } else if (option_name == "timestamp_is_adjusted_to_utc") { bind_data->timestamp_is_adjusted_to_utc = EnumUtil::FromString(StringUtil::Upper(option_values[0].ToString())); diff --git a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp index 6c48ea6c6..0c7e75dee 100644 --- a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp +++ b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp @@ -100,12 +100,12 @@ void ParquetMultiFileInfo::BindReader(ClientContext &context, vector &option_values) { +static bool GetBooleanArgument(Context &context, const Identifier &key, const vector &option_values) { if (option_values.empty()) { return true; } string error_message; - auto boolean_value = option_values[0].DefaultTryCastAs(LogicalType::BOOLEAN, &error_message); + auto boolean_value = option_values[0].TryCastAs(context, LogicalType::BOOLEAN, &error_message); if (!boolean_value) { throw InvalidInputException("Unable to cast \"%s\" to BOOLEAN for Parquet option %s", option_values[0].ToString(), key); @@ -314,7 +314,7 @@ bool ParquetMultiFileInfo::ParseCopyOption(ClientContext &context, const Identif return true; } if (key == "binary_as_string") { - options.binary_as_string = GetBooleanArgument(key, values); + options.binary_as_string = GetBooleanArgument(context.GetContext(), key, values); return true; } if (key == "debug_use_openssl") { @@ -331,7 +331,7 @@ bool ParquetMultiFileInfo::ParseCopyOption(ClientContext &context, const Identif if (values.size() != 1) { throw BinderException("Parquet can_have_nan cannot be empty!"); } - options.can_have_nan = GetBooleanArgument(key, values); + options.can_have_nan = GetBooleanArgument(context.GetContext(), key, values); return true; } if (key == "prefetch_strategy") { diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 3448e2656..b363415c0 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-alpha54042"; + descriptor->api_version = "v2.1.0-alpha54418"; 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-alpha54042"; + descriptor->api_version = "v2.1.0-alpha54418"; 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-alpha54042"; + descriptor->api_version = "v2.1.0-alpha54418"; 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-alpha54042"; + descriptor->api_version = "v2.1.0-alpha54418"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/bignum.cpp b/src/duckdb/src/common/bignum.cpp index c54a1756e..3471024a5 100644 --- a/src/duckdb/src/common/bignum.cpp +++ b/src/duckdb/src/common/bignum.cpp @@ -1,6 +1,8 @@ #include "duckdb/common/bignum.hpp" +#include "duckdb/common/bignum_limbs.hpp" #include "duckdb/common/types/bignum.hpp" #include "duckdb/common/bit_utils.hpp" +#include "duckdb/common/bswap.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/common/printer.hpp" #include "duckdb/common/to_string.hpp" @@ -70,12 +72,45 @@ uint8_t BignumIntermediate::GetAbsoluteByte(int64_t index) const { return is_negative ? static_cast(~data[index]) : static_cast(data[index]); } -AbsoluteNumberComparison BignumIntermediate::IsAbsoluteBigger(const BignumIntermediate &rhs) const { - idx_t actual_start_pos = GetStartDataPos(); - idx_t actual_size = size - actual_start_pos; +//! The absolute-value limb ending just before end_idx of a value, see BignumLimb::LoadAbsolute +static inline uint64_t LoadAbsoluteLimb(const BignumIntermediate &value, int64_t end_idx) { + return BignumLimb::LoadAbsolute(value.data, value.is_negative, end_idx); +} + +//! Stores the low min(end_idx, 8) bytes of a limb as big-endian bytes ending just before end_idx +static inline void StoreLimb(data_ptr_t result, int64_t end_idx, uint64_t limb) { + if (end_idx >= 8) { + BignumLimb::StoreBE(result + end_idx - 8, limb); + return; + } + BignumLimb::StoreBEPartial(result, static_cast(end_idx), limb); +} + +//! The number of leading bytes of data[0, count) equal to the fill byte (0x00 or 0xFF), eight bytes at a time +static idx_t CountLeadingFillBytes(const_data_ptr_t data, idx_t count, bool fill_is_ones) { + const uint8_t fill_byte = fill_is_ones ? 0xFF : 0x00; + if (count == 0 || data[0] != fill_byte) { + // the common case: a trimmed value has no leading fill bytes at all + return 0; + } + const uint64_t fill = fill_is_ones ? ~uint64_t(0) : 0; + idx_t pos = 0; + for (; pos + 8 <= count; pos += 8) { + const uint64_t limb = BignumLimb::LoadBE(data + pos); + if (limb != fill) { + // the first byte that differs is the most significant differing byte of the limb + return pos + BignumLimb::LeadingZeros(limb ^ fill) / 8; + } + } + while (pos < count && data[pos] == fill_byte) { + pos++; + } + return pos; +} - idx_t rhs_actual_start_pos = rhs.GetStartDataPos(); - idx_t rhs_actual_size = rhs.size - rhs_actual_start_pos; +AbsoluteNumberComparison BignumIntermediate::IsAbsoluteBigger(const BignumIntermediate &rhs) const { + const int64_t actual_size = size - GetStartDataPos(); + const int64_t rhs_actual_size = rhs.size - rhs.GetStartDataPos(); // we have opposing signs, gotta do a bunch of checks to figure out who is the biggest // check sizes @@ -84,20 +119,18 @@ AbsoluteNumberComparison BignumIntermediate::IsAbsoluteBigger(const BignumInterm } if (actual_size < rhs_actual_size) { return SMALLER; - } else { - // they have the same size then - idx_t target_idx = actual_start_pos; - idx_t source_idx = rhs_actual_start_pos; - while (target_idx < size) { - auto data_byte = GetAbsoluteByte(static_cast(target_idx)); - auto rhs_byte = rhs.GetAbsoluteByte(static_cast(source_idx)); - if (data_byte > rhs_byte) { - return GREATER; - } else if (data_byte < rhs_byte) { - return SMALLER; - } - target_idx++; - source_idx++; + } + // same magnitude length: compare limbs from the most significant end; both values are right-aligned, so the limb + // ending `end` bytes after the start of the magnitude covers the same digits in both (bytes before the magnitude + // read as zero in LoadAbsoluteLimb, so the first, partial limb needs no special casing) + const int64_t lhs_pad = size - actual_size; + const int64_t rhs_pad = rhs.size - rhs_actual_size; + const int64_t top_limb_bytes = actual_size % 8 == 0 ? 8 : actual_size % 8; + for (int64_t end = top_limb_bytes; end <= actual_size; end += 8) { + const uint64_t lhs_limb = LoadAbsoluteLimb(*this, lhs_pad + end); + const uint64_t rhs_limb = LoadAbsoluteLimb(rhs, rhs_pad + end); + if (lhs_limb != rhs_limb) { + return lhs_limb > rhs_limb ? GREATER : SMALLER; } } // If we got here, the values are equal. @@ -120,16 +153,7 @@ void BignumIntermediate::Initialize(ArenaAllocator &allocator) { } uint32_t BignumIntermediate::GetStartDataPos(data_ptr_t data, idx_t size, bool is_negative) { - uint8_t non_initialized = is_negative ? 0xFF : 0x00; - uint32_t actual_start = 0; - for (idx_t i = 0; i < size; ++i) { - if (data[i] == non_initialized) { - actual_start++; - } else { - break; - } - } - return actual_start; + return static_cast(CountLeadingFillBytes(data, size, is_negative)); } uint32_t BignumIntermediate::GetStartDataPos() const { @@ -179,16 +203,9 @@ bool BignumIntermediate::OverOrUnderflow(data_ptr_t data, idx_t size, bool is_ne if (size <= Bignum::MAX_DATA_SIZE) { return false; } - // variable that stores a fully unset byte can safely be ignored - uint8_t byte_to_compare = is_negative ? 0xFF : 0x00; - // we will basically check if any byte has any set bit up to Bignum::MAX_DATA_SIZE, if so, that's an under/overflow - idx_t data_pos = 0; - for (idx_t i = size; i > Bignum::MAX_DATA_SIZE; i--) { - if (data[data_pos++] != byte_to_compare) { - return true; - } - } - return false; + // the bytes above the maximum size must all be fill bytes, otherwise a bit is set that cannot be represented + const idx_t excess = size - Bignum::MAX_DATA_SIZE; + return CountLeadingFillBytes(data, excess, is_negative) < excess; } bool BignumIntermediate::OverOrUnderflow() const { @@ -216,69 +233,69 @@ bignum_t BignumIntermediate::ToBignum(ArenaAllocator &allocator) const { return result; } -void BignumAddition(data_ptr_t result, int64_t result_end, bool is_target_absolute_bigger, - const BignumIntermediate &lhs, const BignumIntermediate &rhs) { - bool is_result_negative = is_target_absolute_bigger ? lhs.is_negative : rhs.is_negative; - - int64_t i_target = lhs.size - 1; // last byte index in target - int64_t i_source = rhs.size - 1; // last byte index in source - int64_t i_result = result_end - 1; // last byte index in result - - // Carry for addition - uint16_t carry = 0; - uint16_t borrow = 0; - // Add bytes from right to left - while (i_result >= 0) { - // If the numbers are negative, we bit flip them - uint8_t target_byte = lhs.GetAbsoluteByte(i_target); - uint8_t source_byte = rhs.GetAbsoluteByte(i_source); - // Add bytes and carry - uint16_t sum; - if (lhs.is_negative == rhs.is_negative) { - sum = static_cast(target_byte) + static_cast(source_byte) + carry; - carry = (sum >> 8) & 0xFF; +//! result = |lhs| +- |rhs| as a magnitude of result_end bytes, written in the encoding of the result sign. +//! rhs_negative is the sign rhs takes part with (it differs from rhs.is_negative when rhs is subtracted); the +//! magnitude bytes of rhs are still decoded with the sign they are stored with +static void BignumAddition(data_ptr_t result, int64_t result_end, bool is_target_absolute_bigger, + const BignumIntermediate &lhs, const BignumIntermediate &rhs, bool rhs_negative) { + const bool is_result_negative = is_target_absolute_bigger ? lhs.is_negative : rhs_negative; + const bool same_sign = lhs.is_negative == rhs_negative; + // the operands are right-aligned with the result: the byte ending at result index e ends at e - offset in them + const int64_t lhs_offset = result_end - static_cast(lhs.size); + const int64_t rhs_offset = result_end - static_cast(rhs.size); + const uint64_t flip = is_result_negative ? ~uint64_t(0) : 0; + + uint64_t carry = 0; + // walk the magnitudes from the least significant end, 8 bytes at a time + for (int64_t end = result_end; end > 0; end -= 8) { + const uint64_t a = LoadAbsoluteLimb(lhs, end - lhs_offset); + const uint64_t b = LoadAbsoluteLimb(rhs, end - rhs_offset); + uint64_t sum; + if (same_sign) { + sum = a + b; + const uint64_t c1 = sum < a; + sum += carry; + carry = c1 | (sum < carry); } else { - if (is_target_absolute_bigger) { - sum = static_cast(target_byte) - static_cast(source_byte) - borrow; - borrow = sum > static_cast(target_byte) ? 1 : 0; - } else { - sum = static_cast(source_byte) - static_cast(target_byte) - borrow; - borrow = sum > static_cast(source_byte) ? 1 : 0; - } - } - uint8_t result_byte = static_cast(sum & 0xFF); - // If the result is not positive, we must flip the bits again - result[i_result] = is_result_negative ? static_cast(~result_byte) : result_byte; - i_target--; - i_source--; - i_result--; - } - - if (is_result_negative != lhs.is_negative) { - // If we are flipping the sign we must be sure that we are flipping all extra bits from our target - for (int64_t i = 0; i < result_end - rhs.size; ++i) { - result[i] = is_result_negative ? 0xFF : 0x00; + const uint64_t big = is_target_absolute_bigger ? a : b; + const uint64_t small = is_target_absolute_bigger ? b : a; + sum = big - small; + const uint64_t b1 = big < small; + const uint64_t b2 = sum < carry; + sum -= carry; + carry = b1 | b2; } + StoreLimb(result, end, sum ^ flip); + } +} + +//! Writes the bitwise complement of count bytes, eight at a time +static void ComplementBytes(data_ptr_t target, const_data_ptr_t source, idx_t count) { + idx_t pos = 0; + for (; pos + 8 <= count; pos += 8) { + uint64_t limb; + memcpy(&limb, source + pos, sizeof(limb)); + limb = ~limb; + memcpy(target + pos, &limb, sizeof(limb)); + } + for (; pos < count; pos++) { + target[pos] = static_cast(~source[pos]); } } string_t BignumIntermediate::Negate(StringHeap &heap) const { auto target = heap.EmptyString(size + Bignum::BIGNUM_HEADER_SIZE); auto ptr = target.GetDataWriteable(); + auto target_data = reinterpret_cast(ptr + Bignum::BIGNUM_HEADER_SIZE); if (!is_negative && size == 1 && data[0] == 0x00) { // If we have a zero, we just do a copy Bignum::SetHeader(ptr, size, is_negative); - for (idx_t i = 0; i < size; ++i) { - ptr[i + Bignum::BIGNUM_HEADER_SIZE] = static_cast(data[i]); - } + memcpy(target_data, data, size); } else { - // Otherwise, we set the header with a flip on the signal + // Otherwise, we set the header with a flip on the signal and flip all the data bits Bignum::SetHeader(ptr, size, !is_negative); - for (idx_t i = 0; i < size; ++i) { - // And flip all the data bits - ptr[i + Bignum::BIGNUM_HEADER_SIZE] = static_cast(~data[i]); - } + ComplementBytes(target_data, data, size); } target.Finalize(); return target; @@ -290,9 +307,7 @@ void BignumIntermediate::NegateInPlace() { return; } is_negative = !is_negative; - for (size_t i = 0; i < size; i++) { - data[i] = static_cast(~data[i]); // flip each byte of the pointer - } + ComplementBytes(data, data, size); } string ProduceOverUnderFlowError(bool is_result_negative, idx_t actual_start, idx_t data_size) { @@ -309,8 +324,79 @@ string ProduceOverUnderFlowError(bool is_result_negative, idx_t actual_start, id return error.str(); } -string_t BignumIntermediate::Add(StringHeap &heap, const BignumIntermediate &lhs, const BignumIntermediate &rhs) { - const bool same_sign = lhs.is_negative == rhs.is_negative; +//! Operands of at most this many magnitude bytes are added in registers +static constexpr uint32_t SMALL_ADD_MAX_BYTES = 2 * BignumLimb::BYTES; + +//! Writes a positive zero as a BIGNUM blob into the heap +static string_t WriteZero(StringHeap &heap) { + auto target = heap.EmptyString(1 + Bignum::BIGNUM_HEADER_SIZE); + auto ptr = target.GetDataWriteable(); + Bignum::SetHeader(ptr, 1, false); + ptr[Bignum::BIGNUM_HEADER_SIZE] = 0; + target.Finalize(); + return target; +} + +//! Adds two values of at most SMALL_ADD_MAX_BYTES magnitude bytes each: both magnitudes fit two limbs, so the sum is +//! computed in registers and encoded once, trimmed, without the general path's scratch result and trim pass +static string_t AddSmall(StringHeap &heap, const BignumIntermediate &lhs, const BignumIntermediate &rhs, + bool rhs_negative) { + D_ASSERT(lhs.size <= SMALL_ADD_MAX_BYTES && rhs.size <= SMALL_ADD_MAX_BYTES); + const uint64_t a_lo = LoadAbsoluteLimb(lhs, lhs.size); + const uint64_t a_hi = LoadAbsoluteLimb(lhs, static_cast(lhs.size) - 8); + const uint64_t b_lo = LoadAbsoluteLimb(rhs, rhs.size); + const uint64_t b_hi = LoadAbsoluteLimb(rhs, static_cast(rhs.size) - 8); + + bool is_negative = lhs.is_negative; + uint64_t lo; + uint64_t hi; + // the sum of two 128-bit magnitudes needs a 129th bit + uint64_t top = 0; + if (lhs.is_negative == rhs_negative) { + lo = a_lo + b_lo; + const uint64_t carry = lo < a_lo; + hi = a_hi + b_hi; + top = hi < a_hi; + hi += carry; + top |= hi < carry; + } else { + if (a_hi == b_hi && a_lo == b_lo) { + return WriteZero(heap); + } + const bool lhs_bigger = a_hi > b_hi || (a_hi == b_hi && a_lo > b_lo); + const uint64_t big_lo = lhs_bigger ? a_lo : b_lo; + const uint64_t big_hi = lhs_bigger ? a_hi : b_hi; + const uint64_t small_lo = lhs_bigger ? b_lo : a_lo; + const uint64_t small_hi = lhs_bigger ? b_hi : a_hi; + lo = big_lo - small_lo; + hi = big_hi - small_hi - (big_lo < small_lo); + is_negative = lhs_bigger ? lhs.is_negative : rhs_negative; + } + + // encode the magnitude in as many bytes as it needs, complemented for a negative result + const idx_t byte_count = top ? 2 * BignumLimb::BYTES + 1 : BignumLimb::ByteCount(hi, lo); + auto target = heap.EmptyString(byte_count + Bignum::BIGNUM_HEADER_SIZE); + auto ptr = target.GetDataWriteable(); + Bignum::SetHeader(ptr, byte_count, is_negative); + auto out = reinterpret_cast(ptr + Bignum::BIGNUM_HEADER_SIZE); + if (top) { + // the 129th bit is the most significant byte, the two limbs follow in full + *out++ = static_cast(is_negative ? ~top : top); + BignumLimb::StoreMagnitude(out, 2 * BignumLimb::BYTES, hi, lo, is_negative); + } else { + BignumLimb::StoreMagnitude(out, byte_count, hi, lo, is_negative); + } + target.Finalize(); + return target; +} + +string_t BignumIntermediate::Add(StringHeap &heap, const BignumIntermediate &lhs, const BignumIntermediate &rhs, + bool negate_rhs) { + const bool rhs_negative = rhs.is_negative != negate_rhs; + if (lhs.size <= SMALL_ADD_MAX_BYTES && rhs.size <= SMALL_ADD_MAX_BYTES) { + return AddSmall(heap, lhs, rhs, rhs_negative); + } + const bool same_sign = lhs.is_negative == rhs_negative; const uint32_t actual_size = lhs.size - lhs.GetStartDataPos(); const uint32_t actual_rhs_size = rhs.size - rhs.GetStartDataPos(); uint32_t result_size = actual_size; @@ -322,7 +408,7 @@ string_t BignumIntermediate::Add(StringHeap &heap, const BignumIntermediate &lhs result_size++; } result_size += Bignum::BIGNUM_HEADER_SIZE; - if (lhs.is_negative != rhs.is_negative) { + if (!same_sign) { auto is_absolute_bigger = lhs.IsAbsoluteBigger(rhs); if (is_absolute_bigger == EQUAL) { // We set this value to 0 @@ -343,8 +429,8 @@ string_t BignumIntermediate::Add(StringHeap &heap, const BignumIntermediate &lhs auto target_data = target.GetDataWriteable(); BignumAddition(reinterpret_cast(target_data + Bignum::BIGNUM_HEADER_SIZE), result_size_data, - is_target_absolute_bigger, lhs, rhs); - bool is_result_negative = is_target_absolute_bigger ? lhs.is_negative : rhs.is_negative; + is_target_absolute_bigger, lhs, rhs, rhs_negative); + bool is_result_negative = is_target_absolute_bigger ? lhs.is_negative : rhs_negative; if (OverOrUnderflow(reinterpret_cast(target_data + Bignum::BIGNUM_HEADER_SIZE), result_size_data, is_result_negative)) { auto actual_start = GetStartDataPos(reinterpret_cast(target_data + Bignum::BIGNUM_HEADER_SIZE), @@ -356,8 +442,10 @@ string_t BignumIntermediate::Add(StringHeap &heap, const BignumIntermediate &lhs target.SetSizeAndFinalize(result_size_data + Bignum::BIGNUM_HEADER_SIZE, result_size); return target; } -void BignumIntermediate::AddInPlace(ArenaAllocator &allocator, const BignumIntermediate &rhs) { - const bool same_sign = is_negative == rhs.is_negative; + +void BignumIntermediate::AddInPlace(ArenaAllocator &allocator, const BignumIntermediate &rhs, bool negate_rhs) { + const bool rhs_negative = rhs.is_negative != negate_rhs; + const bool same_sign = is_negative == rhs_negative; idx_t actual_size = size - GetStartDataPos(); idx_t actual_rhs_size = rhs.size - rhs.GetStartDataPos(); if (actual_size < actual_rhs_size || (same_sign && (IsMSBSet() || (rhs.IsMSBSet() && size == rhs.size)))) { @@ -366,7 +454,7 @@ void BignumIntermediate::AddInPlace(ArenaAllocator &allocator, const BignumInter Reallocate(allocator, min_size); } bool is_target_absolute_bigger = true; - if (rhs.is_negative != is_negative) { + if (!same_sign) { auto is_absolute_bigger = IsAbsoluteBigger(rhs); if (is_absolute_bigger == EQUAL) { // We set this value to 0 @@ -378,8 +466,8 @@ void BignumIntermediate::AddInPlace(ArenaAllocator &allocator, const BignumInter } } - bool is_result_negative = is_target_absolute_bigger ? is_negative : rhs.is_negative; - BignumAddition(data, size, is_target_absolute_bigger, *this, rhs); + bool is_result_negative = is_target_absolute_bigger ? is_negative : rhs_negative; + BignumAddition(data, size, is_target_absolute_bigger, *this, rhs, rhs_negative); if (is_result_negative != is_negative) { is_negative = is_result_negative; } @@ -395,8 +483,13 @@ void BignumIntermediate::AddInPlace(ArenaAllocator &allocator, const BignumInter //===--------------------------------------------------------------------===// namespace { -//! Little-endian base 2^32 digits of an absolute value without leading zero digits; zero is the empty vector -using bignum_magnitude_t = unsafe_vector; +//! Little-endian base 2^DIGIT_BITS digits of an absolute value without leading zero digits; zero is the empty vector +using bignum_magnitude_t = unsafe_vector; + +constexpr idx_t DIGIT_BYTES = BignumLimb::DIGIT_BYTES; +constexpr idx_t DIGIT_BITS = BignumLimb::DIGIT_BITS; +constexpr bignum_twodigit_t BASE = static_cast(1) << DIGIT_BITS; +constexpr bignum_twodigit_t DIGIT_MASK = BASE - 1; //! Digit operations between two interrupt checks, roughly a millisecond of work constexpr idx_t INTERRUPT_CHECK_INTERVAL = idx_t(1) << 20; @@ -420,22 +513,14 @@ void TrimMagnitude(bignum_magnitude_t &digits) { void GetMagnitude(const BignumIntermediate &value, bignum_magnitude_t &digits) { digits.clear(); - const idx_t start = value.GetStartDataPos(); - digits.reserve((value.size - start + Bignum::DIGIT_BYTES - 1) / Bignum::DIGIT_BYTES); - digit_t current = 0; - uint8_t shift = 0; - // walk the big-endian magnitude bytes from the least significant byte upwards - for (idx_t i = value.size; i > start; i--) { - current |= static_cast(value.GetAbsoluteByte(static_cast(i - 1))) << shift; - shift += 8; - if (shift == Bignum::DIGIT_BITS) { - digits.push_back(current); - current = 0; - shift = 0; - } - } - if (shift != 0) { - digits.push_back(current); + const int64_t start = value.GetStartDataPos(); + const int64_t byte_count = static_cast(value.size) - start; + digits.reserve((byte_count + DIGIT_BYTES - 1) / DIGIT_BYTES); + // walk the big-endian magnitude bytes from the least significant end, a digit at a time; the most significant + // digit may be partial, LoadAbsolute reads the bytes before the magnitude as zero and truncation keeps the low + // DIGIT_BYTES bytes of the loaded limb + for (int64_t end = value.size; end > start; end -= DIGIT_BYTES) { + digits.push_back(static_cast(BignumLimb::LoadAbsolute(value.data, value.is_negative, end))); } TrimMagnitude(digits); } @@ -445,7 +530,7 @@ idx_t MagnitudeBitCount(const bignum_magnitude_t &digits) { if (digits.empty()) { return 0; } - return digits.size() * Bignum::DIGIT_BITS - CountZeros::Leading(digits.back()); + return digits.size() * DIGIT_BITS - BignumLimb::LeadingZeros(digits.back()); } idx_t BitsToBytes(idx_t bits) { @@ -456,8 +541,7 @@ idx_t BitsToBytes(idx_t bits) { string_t WriteMagnitude(StringHeap &heap, const bignum_magnitude_t &digits, bool is_negative) { if (digits.empty()) { // zero is always encoded as a single positive zero byte - const auto zero = Bignum::InitializeBignumZero(); - return heap.AddBlob(zero.data(), zero.size()); + return WriteZero(heap); } const idx_t byte_count = BitsToBytes(MagnitudeBitCount(digits)); if (byte_count > Bignum::MAX_DATA_SIZE) { @@ -466,38 +550,234 @@ string_t WriteMagnitude(StringHeap &heap, const bignum_magnitude_t &digits, bool auto target = heap.EmptyString(byte_count + Bignum::BIGNUM_HEADER_SIZE); auto target_data = target.GetDataWriteable(); Bignum::SetHeader(target_data, byte_count, is_negative); - auto result = target_data + Bignum::BIGNUM_HEADER_SIZE; - for (idx_t i = 0; i < byte_count; i++) { - // byte i is the i-th most significant byte of the result - const idx_t byte_from_lsb = byte_count - 1 - i; - D_ASSERT(byte_from_lsb / Bignum::DIGIT_BYTES < digits.size()); - const auto byte = static_cast(digits[byte_from_lsb / Bignum::DIGIT_BYTES] >> - (8 * (byte_from_lsb % Bignum::DIGIT_BYTES))); - result[i] = static_cast(is_negative ? static_cast(~byte) : byte); + auto result = reinterpret_cast(target_data + Bignum::BIGNUM_HEADER_SIZE); + // the most significant digit only gets the bytes it needs, the others are written in full + idx_t digit_idx = digits.size() - 1; + const idx_t top_bytes = byte_count - digit_idx * DIGIT_BYTES; + BignumLimb::StoreMagnitudePartial(result, top_bytes, digits[digit_idx], is_negative); + result += top_bytes; + while (digit_idx > 0) { + digit_idx--; + BignumLimb::StoreMagnitudePartial(result, DIGIT_BYTES, digits[digit_idx], is_negative); + result += DIGIT_BYTES; } target.Finalize(); return target; } -//! Schoolbook multiplication: result = lhs * rhs +//! Below this many digits in the shorter operand, magnitudes are multiplied with the schoolbook algorithm +constexpr idx_t KARATSUBA_THRESHOLD = 16; + +//! out[0..a_size] = a * digit +inline void MultiplyByDigit(BignumArithmeticState &state, const bignum_digit_t *a, idx_t a_size, bignum_digit_t digit, + bignum_digit_t *out) { + AccountWork(state, a_size); + bignum_twodigit_t carry = 0; + for (idx_t j = 0; j < a_size; j++) { + const bignum_twodigit_t product = static_cast(digit) * a[j] + carry; + out[j] = static_cast(product); + carry = product >> DIGIT_BITS; + } + out[a_size] = static_cast(carry); +} + +//! Schoolbook multiplication: out[0..a_size + b_size) = a * b for two non-empty operands, with the shorter one in the +//! outer loop; the first row of partial products is written, the others are added +void SchoolbookMultiply(BignumArithmeticState &state, const bignum_digit_t *a, idx_t a_size, const bignum_digit_t *b, + idx_t b_size, bignum_digit_t *out) { + if (a_size < b_size) { + std::swap(a, b); + std::swap(a_size, b_size); + } + D_ASSERT(b_size >= 1); + MultiplyByDigit(state, a, a_size, b[0], out); + for (idx_t i = 1; i < b_size; i++) { + AccountWork(state, a_size); + bignum_twodigit_t carry = 0; + const bignum_twodigit_t b_digit = b[i]; + for (idx_t j = 0; j < a_size; j++) { + // (BASE - 1)^2 + 2 * (BASE - 1) = BASE^2 - 1, so this cannot overflow + const bignum_twodigit_t product = b_digit * a[j] + out[i + j] + carry; + out[i + j] = static_cast(product); + carry = product >> DIGIT_BITS; + } + out[i + a_size] = static_cast(carry); + } +} + +//! out[0..a_size) = a + b, where a_size >= b_size; the carry out of the top digit is returned +bignum_digit_t AddDigits(BignumArithmeticState &state, const bignum_digit_t *a, idx_t a_size, const bignum_digit_t *b, + idx_t b_size, bignum_digit_t *out) { + D_ASSERT(a_size >= b_size); + AccountWork(state, a_size); + bignum_twodigit_t carry = 0; + idx_t i = 0; + for (; i < b_size; i++) { + const bignum_twodigit_t sum = static_cast(a[i]) + b[i] + carry; + out[i] = static_cast(sum); + carry = sum >> DIGIT_BITS; + } + for (; i < a_size; i++) { + const bignum_twodigit_t sum = static_cast(a[i]) + carry; + out[i] = static_cast(sum); + carry = sum >> DIGIT_BITS; + } + return static_cast(carry); +} + +//! out += addend, where the sum fits in out_size digits +void AddInPlace(BignumArithmeticState &state, bignum_digit_t *out, idx_t out_size, const bignum_digit_t *addend, + idx_t addend_size) { + D_ASSERT(addend_size <= out_size); + AccountWork(state, addend_size); + bignum_twodigit_t carry = 0; + idx_t i = 0; + for (; i < addend_size; i++) { + const bignum_twodigit_t sum = static_cast(out[i]) + addend[i] + carry; + out[i] = static_cast(sum); + carry = sum >> DIGIT_BITS; + } + for (; carry; i++) { + D_ASSERT(i < out_size); + out[i]++; + carry = out[i] == 0 ? 1 : 0; + } +} + +//! out -= subtrahend, where out >= subtrahend +void SubtractInPlace(BignumArithmeticState &state, bignum_digit_t *out, idx_t out_size, + const bignum_digit_t *subtrahend, idx_t subtrahend_size) { + D_ASSERT(subtrahend_size <= out_size); + AccountWork(state, subtrahend_size); + bignum_digit_t borrow = 0; + idx_t i = 0; + for (; i < subtrahend_size; i++) { + const bignum_digit_t difference = out[i] - subtrahend[i]; + // at most one of the two steps underflows: the difference is non-zero when the first one did + const bignum_digit_t next_borrow = (out[i] < subtrahend[i] || difference < borrow) ? 1 : 0; + out[i] = difference - borrow; + borrow = next_borrow; + } + for (; borrow; i++) { + D_ASSERT(i < out_size); + borrow = out[i] == 0 ? 1 : 0; + out[i]--; + } +} + +//! The scratch digits MultiplyDigits needs for operands of up to digit_count digits +idx_t KaratsubaScratchSize(idx_t digit_count) { + idx_t total = 0; + while (digit_count >= KARATSUBA_THRESHOLD) { + // a balanced split sums halves of at most half digits (with their carry digit) and multiplies the sums + const idx_t half = (digit_count + 1) / 2 + 1; + total += 4 * half; + digit_count = half; + } + return total; +} + +//! out[0..a_size + b_size) = a * b: Karatsuba multiplication down to KARATSUBA_THRESHOLD digits, schoolbook below +//! scratch holds KaratsubaScratchSize(max(a_size, b_size)) digits and may alias neither operand nor out +void MultiplyDigits(BignumArithmeticState &state, const bignum_digit_t *a, idx_t a_size, const bignum_digit_t *b, + idx_t b_size, bignum_digit_t *out, bignum_digit_t *scratch) { + if (a_size < b_size) { + std::swap(a, b); + std::swap(a_size, b_size); + } + if (b_size < KARATSUBA_THRESHOLD) { + SchoolbookMultiply(state, a, a_size, b, b_size, out); + return; + } + if (2 * b_size <= a_size) { + // unbalanced: multiply b with b_size digit chunks of a and add up the partial products + std::fill(out, out + a_size + b_size, 0); + auto part = scratch; + for (idx_t offset = 0; offset < a_size; offset += b_size) { + const idx_t chunk_size = MinValue(b_size, a_size - offset); + MultiplyDigits(state, a + offset, chunk_size, b, b_size, part, scratch + 2 * b_size); + AddInPlace(state, out + offset, a_size + b_size - offset, part, chunk_size + b_size); + } + return; + } + // a = a1 * BASE^m + a0 and b = b1 * BASE^m + b0, where b1 is not empty because 2 * b_size > a_size + const idx_t m = a_size / 2; + const idx_t a1_size = a_size - m; + const idx_t b1_size = b_size - m; + // z0 = a0 * b0 and z2 = a1 * b1 fill the low and the high digits of the result + MultiplyDigits(state, a, m, b, m, out, scratch); + MultiplyDigits(state, a + m, a1_size, b + m, b1_size, out + 2 * m, scratch); + // a_sum = a0 + a1 and b_sum = b0 + b1, each followed by its carry digit when there is one + auto a_sum = scratch; + idx_t a_sum_size = a1_size; + a_sum[a_sum_size] = AddDigits(state, a + m, a1_size, a, m, a_sum); + a_sum_size += a_sum[a_sum_size] ? 1 : 0; + auto b_sum = a_sum + a1_size + 1; + idx_t b_sum_size = MaxValue(m, b1_size); + b_sum[b_sum_size] = + b1_size >= m ? AddDigits(state, b + m, b1_size, b, m, b_sum) : AddDigits(state, b, m, b + m, b1_size, b_sum); + b_sum_size += b_sum[b_sum_size] ? 1 : 0; + // z1 = (a0 + a1) * (b0 + b1) - z0 - z2 = a0 * b1 + a1 * b0 goes in at digit m + auto z1 = b_sum + MaxValue(m, b1_size) + 1; + idx_t z1_size = a_sum_size + b_sum_size; + MultiplyDigits(state, a_sum, a_sum_size, b_sum, b_sum_size, z1, z1 + z1_size); + SubtractInPlace(state, z1, z1_size, out, 2 * m); + SubtractInPlace(state, z1, z1_size, out + 2 * m, a1_size + b1_size); + while (z1_size > 0 && z1[z1_size - 1] == 0) { + z1_size--; + } + AddInPlace(state, out + m, a_size + b_size - m, z1, z1_size); +} + +//! result = lhs * rhs, for two non-empty magnitudes void MultiplyMagnitudes(BignumArithmeticState &state, const bignum_magnitude_t &lhs, const bignum_magnitude_t &rhs, bignum_magnitude_t &result) { - result.assign(lhs.size() + rhs.size(), 0); - for (idx_t i = 0; i < lhs.size(); i++) { - AccountWork(state, rhs.size()); - twodigit_t carry = 0; - const twodigit_t lhs_digit = lhs[i]; - for (idx_t j = 0; j < rhs.size(); j++) { - // (2^32 - 1)^2 + 2 * (2^32 - 1) = 2^64 - 1, so this cannot overflow - const twodigit_t product = lhs_digit * rhs[j] + result[i + j] + carry; - result[i + j] = static_cast(product); - carry = product >> Bignum::DIGIT_BITS; + result.resize(lhs.size() + rhs.size()); + if (rhs.size() == 1) { + MultiplyByDigit(state, lhs.data(), lhs.size(), rhs[0], result.data()); + } else if (lhs.size() == 1) { + MultiplyByDigit(state, rhs.data(), rhs.size(), lhs[0], result.data()); + } else if (MinValue(lhs.size(), rhs.size()) < KARATSUBA_THRESHOLD) { + SchoolbookMultiply(state, lhs.data(), lhs.size(), rhs.data(), rhs.size(), result.data()); + } else { + auto &scratch = state.karatsuba_scratch; + const idx_t scratch_size = KaratsubaScratchSize(MaxValue(lhs.size(), rhs.size())); + if (scratch.size() < scratch_size) { + scratch.resize(scratch_size); } - result[i + rhs.size()] = static_cast(carry); + MultiplyDigits(state, lhs.data(), lhs.size(), rhs.data(), rhs.size(), result.data(), scratch.data()); } TrimMagnitude(result); } +//! Division by a single digit; the remainder is returned +bignum_digit_t DivideByDigit(const bignum_magnitude_t ÷nd, bignum_digit_t divisor, bignum_magnitude_t "ient) { + const idx_t m = dividend.size(); + quotient.assign(m, 0); + bignum_digit_t rem = 0; + constexpr idx_t HALF_BITS = DIGIT_BITS / 2; + if (divisor >> HALF_BITS == 0) { + // a divisor that fits half a digit: halve the digits so that every step is a native division of digit width + // instead of a double-width one, which has no hardware instruction on most platforms + const bignum_digit_t half_mask = (static_cast(1) << HALF_BITS) - 1; + for (idx_t i = m; i > 0; i--) { + const bignum_digit_t digit = dividend[i - 1]; + const bignum_digit_t high = (rem << HALF_BITS) | (digit >> HALF_BITS); + const bignum_digit_t q_high = high / divisor; + const bignum_digit_t low = ((high - q_high * divisor) << HALF_BITS) | (digit & half_mask); + const bignum_digit_t q_low = low / divisor; + rem = low - q_low * divisor; + quotient[i - 1] = (q_high << HALF_BITS) | q_low; + } + } else { + for (idx_t i = m; i > 0; i--) { + quotient[i - 1] = BignumLimb::DivRem(rem, dividend[i - 1], divisor, rem); + } + } + TrimMagnitude(quotient); + return rem; +} + //! Long division following Knuth's Algorithm D (TAOCP 4.3.1); the remainder is only produced on request void DivModMagnitudes(BignumArithmeticState &state, const bignum_magnitude_t ÷nd, const bignum_magnitude_t &divisor, bignum_magnitude_t "ient, bignum_magnitude_t &remainder, @@ -512,41 +792,30 @@ void DivModMagnitudes(BignumArithmeticState &state, const bignum_magnitude_t &di } return; } - constexpr twodigit_t BASE = static_cast(1) << Bignum::DIGIT_BITS; - constexpr twodigit_t DIGIT_MASK = BASE - 1; if (n == 1) { - // single digit divisor: simple short division AccountWork(state, m); - const twodigit_t d = divisor[0]; - twodigit_t rem = 0; - quotient.assign(m, 0); - for (idx_t i = m; i > 0; i--) { - const twodigit_t current = (rem << Bignum::DIGIT_BITS) | dividend[i - 1]; - quotient[i - 1] = static_cast(current / d); - rem = current % d; - } - TrimMagnitude(quotient); + const auto rem = DivideByDigit(dividend, divisor[0], quotient); remainder.clear(); if (want_remainder && rem != 0) { - remainder.push_back(static_cast(rem)); + remainder.push_back(rem); } return; } // D1: normalize so that the most significant divisor digit has its top bit set - const auto shift = static_cast(CountZeros::Leading(divisor[n - 1])); + const auto shift = static_cast(BignumLimb::LeadingZeros(divisor[n - 1])); auto &vn = state.normalized_divisor; auto &un = state.normalized_dividend; vn.assign(n, 0); un.assign(m + 1, 0); if (shift > 0) { for (idx_t i = n - 1; i > 0; i--) { - vn[i] = (divisor[i] << shift) | (divisor[i - 1] >> (Bignum::DIGIT_BITS - shift)); + vn[i] = (divisor[i] << shift) | (divisor[i - 1] >> (DIGIT_BITS - shift)); } vn[0] = divisor[0] << shift; - un[m] = dividend[m - 1] >> (Bignum::DIGIT_BITS - shift); + un[m] = dividend[m - 1] >> (DIGIT_BITS - shift); for (idx_t i = m - 1; i > 0; i--) { - un[i] = (dividend[i] << shift) | (dividend[i - 1] >> (Bignum::DIGIT_BITS - shift)); + un[i] = (dividend[i] << shift) | (dividend[i - 1] >> (DIGIT_BITS - shift)); } un[0] = dividend[0] << shift; } else { @@ -558,49 +827,56 @@ void DivModMagnitudes(BignumArithmeticState &state, const bignum_magnitude_t &di for (idx_t j = m - n + 1; j > 0; j--) { AccountWork(state, n); const idx_t pos = j - 1; - // D3: estimate the quotient digit - const twodigit_t numerator = (static_cast(un[pos + n]) << Bignum::DIGIT_BITS) | un[pos + n - 1]; - twodigit_t qhat = numerator / vn[n - 1]; - twodigit_t rhat = numerator % vn[n - 1]; - while (qhat >= BASE || qhat * vn[n - 2] > ((rhat << Bignum::DIGIT_BITS) | un[pos + n - 2])) { + // D3: estimate the quotient digit; the top dividend digit never exceeds the top divisor digit, so when they + // are equal the estimate is BASE - 1 (the true digit is at most that) and the remainder follows from it + bignum_twodigit_t qhat; + bignum_twodigit_t rhat; + if (un[pos + n] >= vn[n - 1]) { + const bignum_twodigit_t numerator = + (static_cast(un[pos + n]) << DIGIT_BITS) | un[pos + n - 1]; + qhat = DIGIT_MASK; + rhat = numerator - qhat * vn[n - 1]; + } else { + bignum_digit_t rem; + qhat = BignumLimb::DivRem(un[pos + n], un[pos + n - 1], vn[n - 1], rem); + rhat = rem; + } + while (rhat < BASE && qhat * vn[n - 2] > ((rhat << DIGIT_BITS) | un[pos + n - 2])) { qhat--; rhat += vn[n - 1]; - if (rhat >= BASE) { - break; - } } // D4: multiply and subtract // the borrow is at most BASE: the high half of a product is at most BASE - 2 and we borrow at most 2 units - twodigit_t borrow = 0; + bignum_twodigit_t borrow = 0; for (idx_t i = 0; i < n; i++) { - const twodigit_t product = qhat * vn[i]; - const twodigit_t subtrahend = (product & DIGIT_MASK) + borrow; - const twodigit_t current = un[i + pos]; + const bignum_twodigit_t product = qhat * vn[i]; + const bignum_twodigit_t subtrahend = (product & DIGIT_MASK) + borrow; + const bignum_twodigit_t current = un[i + pos]; if (current >= subtrahend) { - un[i + pos] = static_cast(current - subtrahend); - borrow = product >> Bignum::DIGIT_BITS; + un[i + pos] = static_cast(current - subtrahend); + borrow = product >> DIGIT_BITS; } else { // the subtrahend is below 2 * BASE, so we need to borrow one or two units from the next digit - const twodigit_t deficit = subtrahend - current; - const twodigit_t units = (deficit + BASE - 1) / BASE; - un[i + pos] = static_cast(current + units * BASE - subtrahend); - borrow = (product >> Bignum::DIGIT_BITS) + units; + const bignum_twodigit_t deficit = subtrahend - current; + const bignum_twodigit_t units = (deficit + BASE - 1) >> DIGIT_BITS; + un[i + pos] = static_cast(current + units * BASE - subtrahend); + borrow = (product >> DIGIT_BITS) + units; } } - const twodigit_t top = un[pos + n]; + const bignum_twodigit_t top = un[pos + n]; const bool went_negative = top < borrow; - un[pos + n] = static_cast(went_negative ? top + BASE - borrow : top - borrow); - quotient[pos] = static_cast(qhat); + un[pos + n] = static_cast(went_negative ? top + BASE - borrow : top - borrow); + quotient[pos] = static_cast(qhat); if (went_negative) { // D6: the estimate was one too large, add the divisor back quotient[pos]--; - twodigit_t carry = 0; + bignum_twodigit_t carry = 0; for (idx_t i = 0; i < n; i++) { - const twodigit_t sum = static_cast(un[i + pos]) + vn[i] + carry; - un[i + pos] = static_cast(sum); - carry = sum >> Bignum::DIGIT_BITS; + const bignum_twodigit_t sum = static_cast(un[i + pos]) + vn[i] + carry; + un[i + pos] = static_cast(sum); + carry = sum >> DIGIT_BITS; } - un[pos + n] = static_cast(un[pos + n] + carry); + un[pos + n] = static_cast(un[pos + n] + carry); } } TrimMagnitude(quotient); @@ -613,7 +889,7 @@ void DivModMagnitudes(BignumArithmeticState &state, const bignum_magnitude_t &di remainder.assign(n, 0); if (shift > 0) { for (idx_t i = 0; i < n; i++) { - remainder[i] = (un[i] >> shift) | (un[i + 1] << (Bignum::DIGIT_BITS - shift)); + remainder[i] = (un[i] >> shift) | (un[i + 1] << (DIGIT_BITS - shift)); } } else { std::copy(un.begin(), un.begin() + static_cast(n), remainder.begin()); diff --git a/src/duckdb/src/common/bind_helpers.cpp b/src/duckdb/src/common/bind_helpers.cpp index 3957a0a02..755af542f 100644 --- a/src/duckdb/src/common/bind_helpers.cpp +++ b/src/duckdb/src/common/bind_helpers.cpp @@ -24,7 +24,7 @@ Value ConvertVectorToValue(vector set) { return Value::LIST(std::move(set)); } -idx_t ParseBytesArg(const Identifier &name, const Value &arg) { +idx_t ParseBytesArg(Context &context, const Identifier &name, const Value &arg) { if (arg.IsNull()) { throw BinderException("NULL is not supported as a valid option for COPY option \"%s\"", StringUtil::Upper(name.GetIdentifierName())); @@ -33,7 +33,7 @@ idx_t ParseBytesArg(const Identifier &name, const Value &arg) { if (arg.type().id() == LogicalTypeId::VARCHAR) { result = DBConfig::ParseMemoryLimit(arg.ToString()); } else { - auto cast_arg = arg.DefaultTryCastAs(LogicalType::UBIGINT); + auto cast_arg = arg.TryCastAs(context, LogicalType::UBIGINT); if (!cast_arg) { throw BinderException("Unable to parse bytes from \"%s\" for copy option \"%s\" ", arg.ToString(), StringUtil::Upper(name.GetIdentifierName())); diff --git a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp index a3bb9a33b..9c06ed759 100644 --- a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp @@ -7,6 +7,7 @@ #include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/execution/expression_executor.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression_binder/constant_binder.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" @@ -970,17 +971,18 @@ static bool MappedCastIsInvertible(const MultiFileIndexMapping &mapping, const L return true; } -static bool TryCastConstant(Value &constant, const MultiFileIndexMapping &mapping, const LogicalType &target_type) { +static bool TryCastConstant(Context &context, Value &constant, const MultiFileIndexMapping &mapping, + const LogicalType &target_type) { // this filter replaces the global one, so both casts must preserve which rows match if (!BoundCastExpression::CastIsInvertible(constant.type(), target_type) || !MappedCastIsInvertible(mapping, target_type, constant.type())) { return false; } - auto cast = constant.DefaultTryCastAs(target_type); + auto cast = constant.TryCastAs(context, target_type); if (!cast) { return false; } - auto roundtrip = cast->DefaultTryCastAs(constant.type()); + auto roundtrip = cast->TryCastAs(context, constant.type()); if (!roundtrip || *roundtrip != constant) { return false; } @@ -1031,7 +1033,8 @@ static RewrittenMappedExpression RewriteMappedValueExpression(const Expression & } } -static unique_ptr RewriteDynamicFilterExpression(const shared_ptr &filter_data, +static unique_ptr RewriteDynamicFilterExpression(Context &context, + const shared_ptr &filter_data, const MultiFileIndexMapping &mapping, const LogicalType &target_type) { if (!filter_data || !filter_data->initialized) { @@ -1039,21 +1042,23 @@ static unique_ptr RewriteDynamicFilterExpression(const shared_ptr lock(filter_data->lock); auto new_constant = filter_data->constant; - if (!TryCastConstant(new_constant, mapping, target_type)) { + if (!TryCastConstant(context, new_constant, mapping, target_type)) { return nullptr; } return BoundComparisonExpression::Create(filter_data->comparison_type, CreateReferenceExpression(target_type), make_uniq(std::move(new_constant))); } -static unique_ptr TryCastFilterExpression(const Expression &expr, const MultiFileIndexMapping &mapping, +static unique_ptr TryCastFilterExpression(Context &context, const Expression &expr, + const MultiFileIndexMapping &mapping, const LogicalType &target_type) { switch (expr.GetExpressionClass()) { case ExpressionClass::BOUND_FUNCTION: { auto &func = expr.Cast(); if (ExpressionFilter::IsRootOptionalExpression(expr)) { auto optional_child = ExpressionFilter::GetOptionalFilterChild(expr); - auto child_expr = optional_child ? TryCastFilterExpression(*optional_child, mapping, target_type) : nullptr; + auto child_expr = + optional_child ? TryCastFilterExpression(context, *optional_child, mapping, target_type) : nullptr; if (optional_child && !child_expr) { return nullptr; } @@ -1072,7 +1077,7 @@ static unique_ptr TryCastFilterExpression(const Expression &expr, co return nullptr; } auto &data = func.BindInfo()->Cast(); - return RewriteDynamicFilterExpression(data.filter_data, mapping, target_type); + return RewriteDynamicFilterExpression(context, data.filter_data, mapping, target_type); } if (!BoundComparisonExpression::IsComparison(expr)) { return nullptr; @@ -1088,7 +1093,7 @@ static unique_ptr TryCastFilterExpression(const Expression &expr, co return nullptr; } auto constant = right.Cast().GetValue(); - if (!TryCastConstant(constant, *lhs.mapping, *lhs.type)) { + if (!TryCastConstant(context, constant, *lhs.mapping, *lhs.type)) { return nullptr; } return BoundComparisonExpression::Create(comparison.GetExpressionType(), std::move(lhs.expr), @@ -1098,7 +1103,7 @@ static unique_ptr TryCastFilterExpression(const Expression &expr, co auto &conjunction = expr.Cast(); auto result = make_uniq(conjunction.GetExpressionType()); for (auto &child : conjunction.GetChildren()) { - auto rewritten_child = TryCastFilterExpression(*child, mapping, target_type); + auto rewritten_child = TryCastFilterExpression(context, *child, mapping, target_type); if (!rewritten_child) { return nullptr; } @@ -1137,7 +1142,7 @@ static unique_ptr TryCastFilterExpression(const Expression &expr, co return nullptr; } auto constant = op.GetChildren()[i]->Cast().GetValue(); - if (!TryCastConstant(constant, *lhs.mapping, *lhs.type)) { + if (!TryCastConstant(context, constant, *lhs.mapping, *lhs.type)) { return nullptr; } result->GetChildrenMutable().push_back(make_uniq(std::move(constant))); @@ -1155,10 +1160,10 @@ static unique_ptr TryCastFilterExpression(const Expression &expr, co } } -static unique_ptr TryCastTableFilter(const TableFilter &global_filter, MultiFileIndexMapping &mapping, - const LogicalType &target_type) { +static unique_ptr TryCastTableFilter(Context &context, const TableFilter &global_filter, + MultiFileIndexMapping &mapping, const LogicalType &target_type) { auto filter_expression = GetFilterExpression(global_filter); - auto rewritten_expr = TryCastFilterExpression(*filter_expression, mapping, target_type); + auto rewritten_expr = TryCastFilterExpression(context, *filter_expression, mapping, target_type); if (!rewritten_expr) { return nullptr; } @@ -1216,7 +1221,7 @@ MultiFileColumnMapper::CreateFilters(map &values, MultiFileOptions &options) { +bool MultiFileReader::ParseCopyOption(Context &context, const Identifier &key, const vector &values, + MultiFileOptions &options) { if (key != "file_row_number") { return false; } @@ -499,7 +500,7 @@ bool MultiFileReader::ParseCopyOption(const Identifier &key, const vector return true; } string error_message; - auto value = values[0].DefaultTryCastAs(LogicalType::BOOLEAN, &error_message); + auto value = values[0].TryCastAs(context, LogicalType::BOOLEAN, &error_message); if (!value) { throw InvalidInputException("Unable to cast \"%s\" to BOOLEAN for boolean option %s", values[0].ToString(), key); @@ -520,7 +521,7 @@ bool MultiFileReader::ParseOption(const Identifier &key, const Value &val, Multi options.filename_column = StringValue::Get(val); } else { string error_message; - auto boolean_value = val.DefaultTryCastAs(LogicalType::BOOLEAN, &error_message); + auto boolean_value = val.TryCastAs(context, LogicalType::BOOLEAN, &error_message); if (boolean_value) { // If the argument can be cast to boolean, we just interpret it as a boolean options.filename = BooleanValue::Get(*boolean_value); @@ -543,14 +544,14 @@ bool MultiFileReader::ParseOption(const Identifier &key, const Value &val, Multi } options.allow_empty = BooleanValue::Get(val); } else if (key == "column_statistics") { - options.SetColumnStatistics(key, val); + options.SetColumnStatistics(context.GetContext(), key, val); } else if (key == "maximum_sample_files") { - options.SetMaximumSampleFiles(key, val); + options.SetMaximumSampleFiles(context.GetContext(), key, val); } else if (key == "maximum_files_for_stats") { if (val.IsNull()) { throw InvalidInputException("Cannot use NULL as argument for %s", key); } - options.maximum_files_for_stats = val.DefaultCastAs(LogicalType::UBIGINT).GetValue(); + options.maximum_files_for_stats = val.CastAs(context, LogicalType::UBIGINT).GetValue(); } else if (key == "hive_types_autocast" || key == "hive_type_autocast") { if (val.IsNull()) { throw InvalidInputException("Cannot use NULL as argument for %s", key); @@ -1425,22 +1426,22 @@ LogicalType MultiFileOptions::GetHiveLogicalType(const string &hive_partition_co return LogicalType::VARCHAR; } -void MultiFileOptions::SetMaximumSampleFiles(const Identifier &key, const Value &val) { +void MultiFileOptions::SetMaximumSampleFiles(Context &context, const Identifier &key, const Value &val) { if (val.IsNull()) { throw BinderException("Cannot use NULL as argument to key %s", key); } - if (!TrySetMaximumSampleFiles(val)) { + if (!TrySetMaximumSampleFiles(context, val)) { throw BinderException("%s parameter must be positive, or -1 to remove the limit on the number of files " "used to determine the schema.", key); } } -bool MultiFileOptions::TrySetMaximumSampleFiles(const Value &val) { +bool MultiFileOptions::TrySetMaximumSampleFiles(Context &context, const Value &val) { if (val.IsNull()) { return false; } - auto sample_files = val.DefaultCastAs(LogicalType::BIGINT).GetValue(); + auto sample_files = val.CastAs(context, LogicalType::BIGINT).GetValue(); if (sample_files == -1) { maximum_sample_files = NumericLimits::Maximum(); return true; @@ -1452,7 +1453,7 @@ bool MultiFileOptions::TrySetMaximumSampleFiles(const Value &val) { return true; } -void MultiFileOptions::SetColumnStatistics(const Identifier &key, const Value &val) { +void MultiFileOptions::SetColumnStatistics(Context &context, const Identifier &key, const Value &val) { if (val.IsNull()) { column_statistics = Value(); return; @@ -1461,7 +1462,7 @@ void MultiFileOptions::SetColumnStatistics(const Identifier &key, const Value &v // next scan as it is. Anything that casts to it (a MAP literal of other value types, say) is taken. auto target = LogicalType::MAP(LogicalType::VARCHAR, LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); string error; - auto cast = val.DefaultTryCastAs(target, &error); + auto cast = val.TryCastAs(context, target, &error); if (!cast) { throw InvalidInputException( "%s must be a MAP of column name to a MAP of statistic name ('min', 'max', 'count', 'null_count', " @@ -1516,7 +1517,7 @@ static vector ParseColumnStatisticsKey(const string &key) { } // Apply the statistics given for one (possibly nested) column to the statistics object of that column. -static void ApplyColumnStatistics(BaseStatistics &result, const Value &given, const string &key) { +static void ApplyColumnStatistics(Context &context, BaseStatistics &result, const Value &given, const string &key) { Value min, max; optional count, null_count, distinct_count; for (auto &stat : MapValue::GetChildren(given)) { @@ -1532,7 +1533,7 @@ static void ApplyColumnStatistics(BaseStatistics &result, const Value &given, co max = stat_value; } else if (stat_name == "count" || stat_name == "null_count" || stat_name == "distinct_count") { string error; - auto parsed = stat_value.DefaultTryCastAs(LogicalType::UBIGINT, &error); + auto parsed = stat_value.TryCastAs(context, LogicalType::UBIGINT, &error); if (!parsed) { throw InvalidInputException("column_statistics: '%s' of '%s' must be a count, got '%s'", stat_name, key, stat_value.ToString()); @@ -1561,8 +1562,8 @@ static void ApplyColumnStatistics(BaseStatistics &result, const Value &given, co auto &type = result.GetType(); if (has_values && !min.IsNull() && !max.IsNull() && BaseStatistics::GetStatsType(type) == StatisticsType::NUMERIC_STATS) { - NumericStats::SetMin(result, min.DefaultCastAs(type, true)); - NumericStats::SetMax(result, max.DefaultCastAs(type, true)); + NumericStats::SetMin(result, min.CastAs(context, type, true)); + NumericStats::SetMax(result, max.CastAs(context, type, true)); } if (distinct_count.has_value() && *distinct_count > 0) { result.SetDistinctCount(*distinct_count); @@ -1609,7 +1610,8 @@ static optional_ptr DescendColumnStatistics(BaseStatistics &stat } } -void MultiFileOptions::VerifyColumnStatistics(const vector &names, const vector &types) const { +void MultiFileOptions::VerifyColumnStatistics(Context &context, const vector &names, + const vector &types) const { if (column_statistics.IsNull()) { return; } @@ -1638,11 +1640,11 @@ void MultiFileOptions::VerifyColumnStatistics(const vector &names, c throw InvalidInputException("column_statistics: '%s' names no part of column \"%s\" of type %s", key, path[0], types[column.GetIndex()].ToString()); } - ApplyColumnStatistics(*target, key_value[1], key); + ApplyColumnStatistics(context, *target, key_value[1], key); } } -unique_ptr MultiFileOptions::GetColumnStatistics(const Identifier &column_name, +unique_ptr MultiFileOptions::GetColumnStatistics(Context &context, const Identifier &column_name, const LogicalType &type) const { if (column_statistics.IsNull()) { return nullptr; @@ -1668,7 +1670,7 @@ unique_ptr MultiFileOptions::GetColumnStatistics(const Identifie throw InternalException("column_statistics: '%s' names no part of column \"%s\"", key, column_name.GetIdentifierName()); } - ApplyColumnStatistics(*target, key_value[1], key); + ApplyColumnStatistics(context, *target, key_value[1], key); } return result; } diff --git a/src/duckdb/src/common/multi_file/table_function_multi_file.cpp b/src/duckdb/src/common/multi_file/table_function_multi_file.cpp index 31ea7893c..e9c9e1bd5 100644 --- a/src/duckdb/src/common/multi_file/table_function_multi_file.cpp +++ b/src/duckdb/src/common/multi_file/table_function_multi_file.cpp @@ -485,7 +485,7 @@ bool TableFunctionMultiFileWrapper::ParseOption(ClientContext &context, const Id if (!settings.sample_files_parameter.empty() && key == settings.sample_files_parameter) { // this parameter of the wrapped function also sets how many files are sampled to determine the schema - a // value we cannot use is left to the function to report, in its own words, when it binds - file_options.TrySetMaximumSampleFiles(val); + file_options.TrySetMaximumSampleFiles(context.GetContext(), val); } return true; } @@ -516,7 +516,7 @@ bool TableFunctionMultiFileWrapper::ParseCopyOption(ClientContext &context, cons } else if (type.id() == LogicalTypeId::ANY || values[0].type() == type) { val = values[0]; } else { - val = values[0].DefaultCastAs(type); + val = values[0].CastAs(context, type); } return ParseNamedParameter(key, val, options_p.Cast()); } diff --git a/src/duckdb/src/common/types/bignum.cpp b/src/duckdb/src/common/types/bignum.cpp index 89e212d21..467ab7007 100644 --- a/src/duckdb/src/common/types/bignum.cpp +++ b/src/duckdb/src/common/types/bignum.cpp @@ -4,7 +4,9 @@ #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/typedefs.hpp" +#include "duckdb/common/types/cast_helpers.hpp" #include +#include namespace duckdb { @@ -110,31 +112,153 @@ static bool ShouldRoundDecimalDigits(const char *data, idx_t decimal_start, idx_ return decimal_start < decimal_end && data[decimal_start] >= '5'; } -static void IncrementDecimalString(string &digits) { - int carry = 1; - for (int64_t i = static_cast(digits.size()) - 1; i >= 0 && carry; i--) { - auto digit = static_cast(digits[static_cast(i)] - '0') + carry; - digits[static_cast(i)] = static_cast('0' + (digit % 10)); - carry = digit / 10; +//! 10^0 .. 10^19 +static constexpr uint64_t BIGNUM_CAST_POWERS_OF_TEN[] = {1ULL, + 10ULL, + 100ULL, + 1000ULL, + 10000ULL, + 100000ULL, + 1000000ULL, + 10000000ULL, + 100000000ULL, + 1000000000ULL, + 10000000000ULL, + 100000000000ULL, + 1000000000000ULL, + 10000000000000ULL, + 100000000000000ULL, + 1000000000000000ULL, + 10000000000000000ULL, + 100000000000000000ULL, + 1000000000000000000ULL, + 10000000000000000000ULL}; + +//! Parses eight decimal digits at once (Lemire, "Fast parsing of eight digits") +static inline uint64_t BignumCastParseEightDigits(const char *digits) { + uint64_t value; + memcpy(&value, digits, sizeof(value)); + // the ASCII offset of every digit, then two digits per 16-bit lane, then four, then eight + value -= 0x3030303030303030ULL; + value = (value * 10) + (value >> 8); + return (((value & 0x000000FF000000FFULL) * (100 + (1000000ULL << 32))) + + (((value >> 16) & 0x000000FF000000FFULL) * (1 + (10000ULL << 32)))) >> + 32; +} + +//! Parses count (1 <= count <= 19) decimal digits into an integer +static inline uint64_t BignumCastParseDigits(const char *digits, idx_t count) { + uint64_t value = 0; + idx_t i = 0; +#if !DUCKDB_IS_BIG_ENDIAN + for (; i + 8 <= count; i += 8) { + value = value * 100000000ULL + BignumCastParseEightDigits(digits + i); + } +#endif + for (; i < count; i++) { + value = value * 10 + static_cast(digits[i] - '0'); + } + 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) { + limbs.clear(); + // the first chunk takes the digits that remain after cutting Bignum::DECIMAL_SHIFT digits at a time from + // the end + idx_t chunk_size = count % Bignum::DECIMAL_SHIFT; + if (chunk_size == 0) { + chunk_size = Bignum::DECIMAL_SHIFT; + } + for (idx_t pos = 0; pos < count; pos += chunk_size, chunk_size = Bignum::DECIMAL_SHIFT) { + 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]; + uint64_t carry = chunk; + for (auto &limb : limbs) { + limb = BignumLimb::MultiplyAdd(limb, multiplier, carry, carry); + } + if (carry) { + limbs.push_back(carry); + } } - if (carry) { - digits = "1" + digits; +} + +//! Adds one to a magnitude in base 2^64 limbs +static void BignumCastIncrement(unsafe_vector &limbs) { + for (auto &limb : limbs) { + if (++limb != 0) { + return; + } + } + limbs.push_back(1); +} + +//! The number of magnitude bytes of a magnitude in base 2^64 limbs (one for zero) +static idx_t BignumCastMagnitudeBytes(const unsafe_vector &limbs) { + if (limbs.empty()) { + return 1; + } + D_ASSERT(limbs.back() != 0); + return (limbs.size() - 1) * BignumLimb::BYTES + BignumLimb::ByteCount(limbs.back()); +} + +//! Writes the header and the big-endian magnitude bytes of a BIGNUM blob from base 2^64 limbs +static void BignumCastWriteBlob(char *blob, const unsafe_vector &limbs, idx_t data_bytes, bool is_negative) { + Bignum::SetHeader(blob, data_bytes, is_negative); + auto data = data_ptr_cast(blob + Bignum::BIGNUM_HEADER_SIZE); + if (limbs.empty()) { + data[0] = is_negative ? 0xFF : 0; + return; + } + const idx_t top_bytes = data_bytes - (limbs.size() - 1) * BignumLimb::BYTES; + BignumLimb::StoreMagnitudePartial(data, top_bytes, limbs.back(), is_negative); + auto end = data + data_bytes; + for (idx_t i = 0; i + 1 < limbs.size(); i++, end -= BignumLimb::BYTES) { + BignumLimb::StoreMagnitude(end - BignumLimb::BYTES, limbs[i], is_negative); + } +} + +//! Converts the integer digits of a VARCHAR into base 2^64 limbs, 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); + if (should_round_up) { + BignumCastIncrement(limbs); } } 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) { - if (start_pos == end_pos && !should_round_up) { - is_zero = true; + if (is_zero || (start_pos == end_pos && !should_round_up)) { + return InitializeBignumZero(); } - if (should_round_up) { - string integer_digits(value.GetData() + start_pos, end_pos - start_pos); - IncrementDecimalString(integer_digits); - is_zero = false; - string_t rounded_digits(integer_digits); - return EncodeBignum(rounded_digits, 0, integer_digits.size(), is_negative, is_zero); + unsafe_vector limbs; + BignumCastVarcharToLimbs(value, start_pos, end_pos, should_round_up, limbs); + const idx_t data_bytes = BignumCastMagnitudeBytes(limbs); + string result(BIGNUM_HEADER_SIZE + data_bytes, '\0'); + BignumCastWriteBlob(&result[0], limbs, data_bytes, is_negative); + return result; +} + +bool Bignum::TryVarcharToBignum(const string_t &value, bignum_t &result_value, Vector &result, + BignumCastScratch &scratch) { + 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)) { + return false; + } + if (is_zero || (start_pos == end_pos && !should_round_up)) { + result_value = InitializeBignumZero(result); + return true; } - return EncodeBignum(value, start_pos, end_pos, is_negative, is_zero); + 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); + result_value.data.Finalize(); + return true; } bool Bignum::VarcharFormatting(const string_t &value, idx_t &start_pos, idx_t &end_pos, bool &is_negative, @@ -219,61 +343,7 @@ bool Bignum::VarcharFormatting(const string_t &value, idx_t &start_pos, idx_t &e } string Bignum::EncodeBignum(const string_t &value, idx_t start_pos, idx_t end_pos, bool is_negative, bool is_zero) { - if (is_zero) { - // Return Value 0 - return InitializeBignumZero(); - } - auto int_value_char = value.GetData(); - idx_t actual_size = end_pos - start_pos; - - // convert the decimal digits to base 2**32 digits (least significant first), DECIMAL_SHIFT digits at a time - vector digits; - digits.reserve(actual_size / DECIMAL_SHIFT + 1); - idx_t chunk_size = actual_size % DECIMAL_SHIFT; - if (chunk_size == 0) { - chunk_size = DECIMAL_SHIFT; - } - digit_t chunk_base = 1; - for (idx_t i = 0; i < chunk_size; i++) { - chunk_base *= 10; - } - for (idx_t pos = start_pos; pos < end_pos; pos += chunk_size, chunk_size = DECIMAL_SHIFT) { - digit_t carry = 0; - for (idx_t i = pos; i < pos + chunk_size; i++) { - carry = carry * 10 + static_cast(int_value_char[i] - '0'); - } - // digits = digits * 10**chunk_size + chunk - for (auto &digit : digits) { - twodigit_t tmp = static_cast(digit) * chunk_base + carry; - digit = static_cast(tmp); - carry = static_cast(tmp >> DIGIT_BITS); - } - if (carry) { - digits.push_back(carry); - } - chunk_base = DECIMAL_BASE; - } - - // we initialize result with space for our header - string result(BIGNUM_HEADER_SIZE, '0'); - result.reserve(BIGNUM_HEADER_SIZE + digits.size() * DIGIT_BYTES); - // write the bytes least significant first, these are reversed afterwards - for (idx_t digit_idx = 0; digit_idx < digits.size(); digit_idx++) { - auto digit = digits[digit_idx]; - for (idx_t byte_idx = 0; byte_idx < DIGIT_BYTES; byte_idx++) { - if (digit_idx + 1 == digits.size() && digit == 0) { - // skip leading zero bytes of the most significant digit - break; - } - auto byte = static_cast(digit & 0xFF); - result.push_back(static_cast(is_negative ? ~byte : byte)); - digit >>= 8; - } - } - std::reverse(result.begin() + BIGNUM_HEADER_SIZE, result.end()); - // Set header after we know the size of the bignum - SetHeader(&result[0], result.size() - BIGNUM_HEADER_SIZE, is_negative); - return result; + return EncodeVarcharBignum(value, start_pos, end_pos, is_negative, is_zero, false); } void Bignum::GetByteArray(vector &byte_array, bool &is_negative, const string_t &blob) { @@ -312,82 +382,113 @@ string Bignum::FromByteArray(uint8_t *data, idx_t size, bool is_negative) { return result; } -//! Below this number of limbs, numbers are multiplied with the schoolbook algorithm -static constexpr idx_t KARATSUBA_THRESHOLD = 48; +//! Below this number of decimal limbs, numbers are multiplied with the schoolbook algorithm +static constexpr idx_t KARATSUBA_THRESHOLD = 16; //! Below this number of binary limbs, numbers are converted to decimal with the schoolbook algorithm static constexpr idx_t CONVERSION_THRESHOLD = 64; -static void TrimLimbs(vector &limbs) { +//! Divides the 128-bit value (high, low), where high < 10^19, by 10^19; the quotient fits 64 bits. +//! Möller and Granlund, "Improved division by invariant integers", Algorithm 4, with the precomputed reciprocal of +//! the (normalized) divisor 10^19. +static inline uint64_t BignumCastDivRemDecimalBase(uint64_t high, uint64_t low, uint64_t &remainder) { + D_ASSERT(high < Bignum::DECIMAL_BASE); + //! floor((2^128 - 1) / 10^19) - 2^64 + constexpr uint64_t RECIPROCAL = 0xd83c94fb6d2ac34aULL; + uint64_t q1; + uint64_t q0 = BignumLimb::MultiplyAdd(RECIPROCAL, high, 0, q1); + // (q1, q0) += (high, low) + q0 += low; + q1 += high + (q0 < low ? 1 : 0); + q1 += 1; + uint64_t r = low - q1 * Bignum::DECIMAL_BASE; + if (r > q0) { + q1--; + r += Bignum::DECIMAL_BASE; + } + if (r >= Bignum::DECIMAL_BASE) { + q1++; + r -= Bignum::DECIMAL_BASE; + } + remainder = r; + 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(vector &a, const digit_t *b, idx_t b_size, idx_t shift) { +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) { b_size--; } if (a.size() < shift + b_size) { a.resize(shift + b_size, 0); } - digit_t carry = 0; + uint64_t carry = 0; idx_t i = 0; for (; i < b_size; i++) { - digit_t sum = a[shift + i] + b[i] + carry; - carry = sum >= Bignum::DECIMAL_BASE; - a[shift + i] = carry ? sum - Bignum::DECIMAL_BASE : sum; + // a + b + carry can exceed 2^64, so compare against the complement instead + const uint64_t x = a[shift + i]; + const uint64_t y = b[i] + carry; + carry = x >= Bignum::DECIMAL_BASE - y ? 1 : 0; + a[shift + i] = carry ? x - (Bignum::DECIMAL_BASE - y) : x + y; } for (idx_t idx = shift + i; carry; idx++) { if (idx == a.size()) { a.push_back(0); } - digit_t sum = a[idx] + carry; - carry = sum >= Bignum::DECIMAL_BASE; + const uint64_t sum = a[idx] + carry; + carry = sum >= Bignum::DECIMAL_BASE ? 1 : 0; a[idx] = carry ? sum - Bignum::DECIMAL_BASE : sum; } } // Subtracts the decimal limbs of b from a, where a >= b -static void SubtractDecimalLimbs(vector &a, const vector &b) { - digit_t borrow = 0; +static void SubtractDecimalLimbs(unsafe_vector &a, const unsafe_vector &b) { + uint64_t borrow = 0; idx_t i = 0; for (; i < b.size(); i++) { if (i >= a.size()) { D_ASSERT(b[i] == 0); continue; } - digit_t subtrahend = b[i] + borrow; - borrow = a[i] < subtrahend; - a[i] = borrow ? a[i] + Bignum::DECIMAL_BASE - subtrahend : a[i] - subtrahend; + const uint64_t subtrahend = b[i] + borrow; + borrow = a[i] < subtrahend ? 1 : 0; + a[i] = borrow ? a[i] + (Bignum::DECIMAL_BASE - subtrahend) : a[i] - subtrahend; } for (; borrow; i++) { D_ASSERT(i < a.size()); - borrow = a[i] == 0; + borrow = a[i] == 0 ? 1 : 0; a[i] = borrow ? Bignum::DECIMAL_BASE - 1 : a[i] - 1; } } // Multiplies two numbers in decimal limbs using Karatsuba multiplication -static vector MultiplyDecimalLimbs(const digit_t *a, idx_t a_size, const digit_t *b, idx_t b_size) { +static unsafe_vector MultiplyDecimalLimbs(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); } - vector result; + unsafe_vector result; if (b_size == 0) { return result; } result.resize(a_size + b_size, 0); if (b_size < KARATSUBA_THRESHOLD) { for (idx_t i = 0; i < b_size; i++) { - twodigit_t carry = 0; + uint64_t carry = 0; for (idx_t j = 0; j < a_size; j++) { - twodigit_t current = UnsafeNumericCast(b[i]) * a[j] + result[i + j] + carry; - carry = current / Bignum::DECIMAL_BASE; - result[i + j] = static_cast(current - carry * Bignum::DECIMAL_BASE); + // (high, low) = b[i] * a[j] + result[i + j] + carry, below 10^38 + 2 * 10^19, so high < 10^19 + uint64_t high; + uint64_t low = BignumLimb::MultiplyAdd(b[i], a[j], result[i + j], high); + low += carry; + high += low < carry ? 1 : 0; + carry = BignumCastDivRemDecimalBase(high, low, result[i + j]); } - result[i + a_size] = static_cast(carry); + result[i + a_size] = carry; } TrimLimbs(result); return result; @@ -405,9 +506,9 @@ static vector MultiplyDecimalLimbs(const digit_t *a, idx_t a_size, cons 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); - vector a_sum(a, a + m); + unsafe_vector a_sum(a, a + m); AddDecimalLimbs(a_sum, a + m, a_size - m, 0); - vector b_sum(b, b + m); + 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()); @@ -420,36 +521,42 @@ static vector MultiplyDecimalLimbs(const digit_t *a, idx_t a_size, cons return result; } -// Converts binary limbs (base 2^32) to decimal limbs (base 10^9), both little-endian -// powers[k] holds 2^(32 * 2^k) in decimal limbs -static vector BinaryToDecimalLimbs(const digit_t *binary, idx_t size, vector> &powers) { - vector digits; +// 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) { + 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--) { - digit_t hi = binary[i - 1]; + uint64_t hi = binary[i - 1]; for (idx_t j = 0; j < digits.size(); j++) { - twodigit_t tmp = UnsafeNumericCast(digits[j]) << Bignum::DIGIT_BITS | hi; - hi = static_cast(tmp / UnsafeNumericCast(Bignum::DECIMAL_BASE)); - digits[j] = static_cast(tmp - UnsafeNumericCast(Bignum::DECIMAL_BASE * hi)); + // digits[j] * 2^64 + hi, divided by 10^19 + hi = BignumCastDivRemDecimalBase(digits[j], hi, digits[j]); } while (hi) { digits.push_back(hi % Bignum::DECIMAL_BASE); hi /= Bignum::DECIMAL_BASE; } } - return digits; + return; } - // split the number into high * 2^(32 * m) + low, where m is a power of two + // split the number into high * 2^(64 * m) + low, where m is a power of two idx_t k = 0; idx_t m = 1; while (2 * m < size) { m *= 2; k++; } - auto low = BinaryToDecimalLimbs(binary, m, powers); - auto high = BinaryToDecimalLimbs(binary + m, size - m, powers); + unsafe_vector low; + unsafe_vector high; + BinaryToDecimalLimbs(binary, m, powers, low); + BinaryToDecimalLimbs(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())); @@ -458,56 +565,87 @@ static vector BinaryToDecimalLimbs(const digit_t *binary, idx_t size, v digits = MultiplyDecimalLimbs(high.data(), high.size(), power.data(), power.size()); AddDecimalLimbs(digits, low.data(), low.size(), 0); TrimLimbs(digits); - return digits; } -string Bignum::BignumToVarchar(const bignum_t &blob) { - string decimal_string; - vector byte_array; - bool is_negative; - GetByteArray(byte_array, is_negative, blob.data); - // Rounding byte_array to digit_bytes multiple size, so that we can process every digit_bytes bytes - // at a time without if check in the for loop - idx_t padding_size = (-byte_array.size()) & (DIGIT_BYTES - 1); - byte_array.insert(byte_array.begin(), padding_size, 0); - idx_t limb_count = byte_array.size() / DIGIT_BYTES; - vector binary(limb_count); - for (idx_t i = 0; i < limb_count; i++) { - digit_t limb = 0; - for (idx_t j = 0; j < DIGIT_BYTES; j++) { - limb |= UnsafeNumericCast(byte_array[i * DIGIT_BYTES + j]) << (8 * (DIGIT_BYTES - j - 1)); - } - binary[limb_count - i - 1] = limb; +//! Loads the magnitude of a BIGNUM blob into base 2^64 limbs, least significant first +static void BignumCastLoadMagnitude(const bignum_t &blob, bool &is_negative, unsafe_vector &limbs) { + const idx_t blob_size = blob.data.GetSize(); + if (blob_size < Bignum::BIGNUM_HEADER_SIZE + 1) { + throw InvalidInputException("Invalid blob size."); } - TrimLimbs(binary); - // 2^32 in decimal limbs - vector> powers {{294967296, 4}}; - auto digits = BinaryToDecimalLimbs(binary.data(), binary.size(), powers); + auto data = const_data_ptr_cast(blob.data.GetData()); + is_negative = (data[0] & 0x80) == 0; + const idx_t data_bytes = blob_size - Bignum::BIGNUM_HEADER_SIZE; + const idx_t limb_count = (data_bytes + BignumLimb::BYTES - 1) / BignumLimb::BYTES; + limbs.resize(limb_count); + auto end = data + blob_size; + for (idx_t i = 0; i + 1 < limb_count; i++, end -= BignumLimb::BYTES) { + limbs[i] = BignumLimb::LoadMagnitude(end - BignumLimb::BYTES, is_negative); + } + limbs[limb_count - 1] = BignumLimb::LoadMagnitudePartial( + data + Bignum::BIGNUM_HEADER_SIZE, data_bytes - (limb_count - 1) * BignumLimb::BYTES, is_negative); + TrimLimbs(limbs); +} +//! The number of decimal digits of a magnitude in base 10^19 limbs (one for zero) +static idx_t BignumCastDecimalLength(const unsafe_vector &digits) { if (digits.empty()) { - digits.push_back(0); + return 1; + } + idx_t top_digits = 1; + while (top_digits < Bignum::DECIMAL_SHIFT && digits.back() >= BIGNUM_CAST_POWERS_OF_TEN[top_digits]) { + top_digits++; } + return (digits.size() - 1) * Bignum::DECIMAL_SHIFT + top_digits; +} - for (idx_t i = 0; i < digits.size() - 1; i++) { - auto remain = digits[i]; - for (idx_t j = 0; j < DECIMAL_SHIFT; j++) { - decimal_string += DigitToChar(static_cast(remain % 10)); - remain /= 10; +//! Writes the decimal representation of a magnitude in base 10^19 limbs, with a sign, ending at "end" +static void BignumCastWriteDecimal(char *end, const unsafe_vector &digits, idx_t length, bool is_negative) { + char *start = end - length; + if (digits.empty()) { + *start = '0'; + } else { + for (idx_t i = 0; i + 1 < digits.size(); i++) { + // every limb below the top one takes exactly DECIMAL_SHIFT digits + end -= Bignum::DECIMAL_SHIFT; + char *ptr = NumericHelper::FormatUnsigned(digits[i], end + Bignum::DECIMAL_SHIFT); + while (ptr > end) { + *--ptr = '0'; + } } + char *ptr = NumericHelper::FormatUnsigned(digits.back(), end); + D_ASSERT(ptr == start); + (void)ptr; } - - auto remain = digits.back(); - do { - decimal_string += DigitToChar(static_cast(remain % 10)); - remain /= 10; - } while (remain != 0); - if (is_negative) { - decimal_string += '-'; + start[-1] = '-'; } - // Reverse the string to get the correct decimal representation - std::reverse(decimal_string.begin(), decimal_string.end()); - return decimal_string; +} + +//! 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); + return BignumCastDecimalLength(scratch.decimal) + (is_negative ? 1 : 0); +} + +string Bignum::BignumToVarchar(const bignum_t &blob) { + BignumCastScratch scratch; + bool is_negative; + const idx_t length = BignumCastToDecimal(blob, scratch, is_negative); + string result(length, '\0'); + BignumCastWriteDecimal(&result[0] + length, scratch.decimal, length - (is_negative ? 1 : 0), is_negative); + return result; +} + +string_t Bignum::BignumToVarchar(const bignum_t &blob, Vector &result, BignumCastScratch &scratch) { + bool is_negative; + const idx_t length = BignumCastToDecimal(blob, scratch, is_negative); + auto target = StringVector::EmptyString(result, length); + BignumCastWriteDecimal(target.GetDataWriteable() + length, scratch.decimal, length - (is_negative ? 1 : 0), + is_negative); + target.Finalize(); + return target; } string Bignum::VarcharToBignum(const string_t &value) { @@ -519,29 +657,58 @@ string Bignum::VarcharToBignum(const string_t &value) { return EncodeVarcharBignum(value, start_pos, end_pos, is_negative, is_zero, should_round_up); } +//! Returns 2^exponent as a double, for 0 <= exponent <= 1023 +static inline double BignumCastPowerOfTwo(idx_t exponent) { + D_ASSERT(exponent <= 1023); + const uint64_t bits = static_cast(exponent + 1023) << 52; + double result; + memcpy(&result, &bits, sizeof(result)); + return result; +} + bool Bignum::BignumToDouble(const bignum_t &blob, double &result, bool &strict) { result = 0; - - if (blob.data.GetSize() < 4) { + const idx_t blob_size = blob.data.GetSize(); + if (blob_size < BIGNUM_HEADER_SIZE + 1) { throw InvalidInputException("Invalid blob size."); } - auto blob_ptr = blob.data.GetData(); + auto data = const_data_ptr_cast(blob.data.GetData()); + const bool is_negative = (data[0] & 0x80) == 0; + idx_t data_byte_size = blob_size - BIGNUM_HEADER_SIZE; + auto first = data + BIGNUM_HEADER_SIZE; - // Determine if the number is negative - bool is_negative = (blob_ptr[0] & 0x80) == 0; - idx_t byte_pos = 0; - for (idx_t i = blob.data.GetSize() - 1; i > 2; i--) { - if (is_negative) { - result += static_cast(~blob_ptr[i]) * pow(256, static_cast(byte_pos)); - } else { - result += static_cast(blob_ptr[i]) * pow(256, static_cast(byte_pos)); + double magnitude; + if (data_byte_size <= BignumLimb::BYTES) { + // the conversion of a 64-bit integer rounds correctly + magnitude = static_cast(BignumLimb::LoadMagnitudePartial(first, data_byte_size, is_negative)); + } else { + // a well-formed BIGNUM has no leading zero bytes (0xFF under the complement of a negative value), tolerate them + const data_t zero = is_negative ? 0xFF : 0; + while (data_byte_size > BignumLimb::BYTES && *first == zero) { + first++; + data_byte_size--; } - byte_pos++; - } - - if (is_negative) { - result *= -1; + // 2^1024 and above do not fit a double, that is at least 129 bytes + constexpr idx_t MAX_DOUBLE_BYTES = 1024 / 8; + if (data_byte_size > MAX_DOUBLE_BYTES) { + return false; + } + // round the top 64 bits of the magnitude; the lower bytes only matter when they break a tie, which the sticky + // bit folded into the lowest of the 64 bits takes care of (the top bits hold at least 57 significant bits, so + // the sticky bit is always among the bits that the conversion to a 53-bit mantissa discards) + uint64_t top = BignumLimb::LoadMagnitude(first, is_negative); + const idx_t remaining_bytes = data_byte_size - BignumLimb::BYTES; + auto rest = first + BignumLimb::BYTES; + for (idx_t i = 0; i < remaining_bytes; i++) { + if (rest[i] != zero) { + top |= 1; + break; + } + } + // scaling by a power of two is exact, unless the value exceeds the range of a double + magnitude = static_cast(top) * BignumCastPowerOfTwo(8 * remaining_bytes); } + result = is_negative ? -magnitude : magnitude; // the value does not fit in a double return std::isfinite(result); } diff --git a/src/duckdb/src/common/types/value.cpp b/src/duckdb/src/common/types/value.cpp index a65a0eece..b8d1b5ff7 100644 --- a/src/duckdb/src/common/types/value.cpp +++ b/src/duckdb/src/common/types/value.cpp @@ -2165,6 +2165,12 @@ optional Value::TryCastAs(ClientContext &context, const LogicalType &targ return TryCastAs(CastFunctionSet::Get(context), get_input, target_type, error_message, strict); } +optional Value::TryCastAs(Context &context, const LogicalType &target_type, string *error_message, + bool strict) const { + GetCastFunctionInput get_input(context); + return TryCastAs(CastFunctionSet::Get(context), get_input, target_type, error_message, strict); +} + optional Value::DefaultTryCastAs(const LogicalType &target_type, string *error_message, bool strict) const { CastFunctionSet set; GetCastFunctionInput get_input; @@ -2189,6 +2195,11 @@ Value Value::CastAs(ClientContext &context, const LogicalType &target_type, bool return CastAs(CastFunctionSet::Get(context), get_input, target_type, strict); } +Value Value::CastAs(Context &context, const LogicalType &target_type, bool strict) const { + GetCastFunctionInput get_input(context); + return CastAs(CastFunctionSet::Get(context), get_input, target_type, strict); +} + Value Value::DefaultCastAs(const LogicalType &target_type, bool strict) const { CastFunctionSet set; GetCastFunctionInput get_input; diff --git a/src/duckdb/src/common/vector_operations/vector_cast.cpp b/src/duckdb/src/common/vector_operations/vector_cast.cpp index d834a61e0..cb1c3b898 100644 --- a/src/duckdb/src/common/vector_operations/vector_cast.cpp +++ b/src/duckdb/src/common/vector_operations/vector_cast.cpp @@ -37,6 +37,17 @@ bool VectorOperations::TryCast(ClientContext &context, Vector &source, Vector &r return VectorOperations::TryCast(set, get_input, source, result, count, error_message, strict, nullify_parent); } +bool VectorOperations::TryCast(Context &context, Vector &source, Vector &result, idx_t count, string *error_message, + bool strict, const bool nullify_parent) { + GetCastFunctionInput get_input(context); + return VectorOperations::TryCast(CastFunctionSet::Get(context), get_input, source, result, count, error_message, + strict, nullify_parent); +} + +void VectorOperations::Cast(Context &context, Vector &source, Vector &result, idx_t count, bool strict) { + VectorOperations::TryCast(context, source, result, count, nullptr, strict); +} + void VectorOperations::Cast(ClientContext &context, Vector &source, Vector &result, idx_t count, bool strict) { VectorOperations::TryCast(context, source, result, count, nullptr, strict); } diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/base_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/base_scanner.cpp index 3b2de05ab..a516216e3 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/base_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/base_scanner.cpp @@ -14,7 +14,19 @@ BaseScanner::BaseScanner(shared_ptr buffer_manager_p, shared_p shared_ptr csv_file_scan_p, const CSVIterator &iterator_p) : csv_file_scan(std::move(csv_file_scan_p)), sniffing(sniffing_p), error_handler(std::move(error_handler_p)), state_machine(std::move(state_machine_p)), states(), buffer_manager(std::move(buffer_manager_p)), - iterator(iterator_p), skipper(state_machine->transition_array.stop_patterns) { + iterator(iterator_p), skipper(state_machine->transition_array.stop_patterns), + block_scan(state_machine->transition_array.block_scan), + block_delimiter(state_machine->state_machine_options.delimiter.GetValue().empty() + ? 0 + : static_cast(state_machine->state_machine_options.delimiter.GetValue()[0])), + block_delimiter_bytes(state_machine->state_machine_options.delimiter.GetValue()), + block_multi_byte_delimiter(block_delimiter_bytes.size() > 1), + block_quote(static_cast(state_machine->state_machine_options.quote.GetValue())), + block_crlf(state_machine->state_machine_options.new_line.GetValue() == NewLineIdentifier::CARRY_ON), + block_cr(state_machine->state_machine_options.new_line.GetValue() == NewLineIdentifier::SINGLE_R), + block_escape_is_quote(block_quote != '\0' && state_machine->state_machine_options.escape.GetValue() == + state_machine->state_machine_options.quote.GetValue()), + block_comment(static_cast(state_machine->state_machine_options.comment.GetValue())) { D_ASSERT(buffer_manager); D_ASSERT(state_machine); // Initialize current buffer handle diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp index ae70e46f5..03dc39b38 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp @@ -83,9 +83,10 @@ void SkipScanner::FinalizeChunkProcess() { Process(result); } } - // Skip Carriage Return + // Skip the LF of a CRLF pair if (state_machine->options.dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON && - states.states[1] == CSVState::CARRIAGE_RETURN) { + states.IsCarriageReturn() && cur_buffer_handle && iterator.pos.buffer_pos < cur_buffer_handle->actual_size && + buffer_handle_ptr[iterator.pos.buffer_pos] == '\n') { iterator.pos.buffer_pos++; } iterator.done = FinishedFile(); diff --git a/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_refinement.cpp b/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_refinement.cpp index 3137815a6..022a819b4 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_refinement.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/sniffer/type_refinement.cpp @@ -62,7 +62,8 @@ bool CSVSniffer::TryCastVector(Vector &parse_chunk_col, idx_t size, const Logica } // target type is not varchar: perform a cast string error_message; - return VectorOperations::DefaultTryCast(parse_chunk_col, dummy_result, size, &error_message, true); + return VectorOperations::TryCast(buffer_manager->context, parse_chunk_col, dummy_result, size, &error_message, + true); } void CSVSniffer::RefineTypes() { diff --git a/src/duckdb/src/execution/operator/csv_scanner/state_machine/csv_state_machine_cache.cpp b/src/duckdb/src/execution/operator/csv_scanner/state_machine/csv_state_machine_cache.cpp index aba6ecb78..368947ec7 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/state_machine/csv_state_machine_cache.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/state_machine/csv_state_machine_cache.cpp @@ -10,6 +10,140 @@ void InitializeTransitionArray(StateMachine &transition_array, const CSVState cu } } +//! The block scanner assumes these transitions, a state machine whose table differs anywhere stays on the byte loop +static bool BlockScanEligible(const StateMachine &transition_array, const CSVStateMachineOptions &options) { + const auto &delimiter = options.delimiter.GetValue(); + const auto new_line = options.new_line.GetValue(); + const auto quote = static_cast(options.quote.GetValue()); + const auto escape = static_cast(options.escape.GetValue()); + const auto comment = static_cast(options.comment.GetValue()); + if (delimiter.empty() || delimiter.size() > 4 || (escape != '\0' && escape != quote)) { + return false; + } + if (comment != '\0' && + (comment == static_cast(delimiter[0]) || comment == quote || comment == '\n' || comment == '\r')) { + return false; + } + if (new_line != NewLineIdentifier::SINGLE_N && new_line != NewLineIdentifier::CARRY_ON && + new_line != NewLineIdentifier::SINGLE_R) { + return false; + } + const auto delimiter_byte = static_cast(delimiter[0]); + // a multi byte delimiter walks through the delimiter byte states, the block scan checks the whole delimiter at once + const CSVState delimiter_byte_states[] = {CSVState::DELIMITER_FIRST_BYTE, CSVState::DELIMITER_SECOND_BYTE, + CSVState::DELIMITER_THIRD_BYTE, CSVState::DELIMITER}; + const auto first_byte_state = delimiter.size() == 1 ? CSVState::DELIMITER : CSVState::DELIMITER_FIRST_BYTE; + for (idx_t i = 1; i < delimiter.size(); i++) { + const auto from = static_cast(delimiter_byte_states[i - 1]); + const auto to = i + 1 == delimiter.size() ? CSVState::DELIMITER : delimiter_byte_states[i]; + if (transition_array[static_cast(delimiter[i])][from] != to) { + return false; + } + } + if (transition_array[delimiter_byte][static_cast(CSVState::UNQUOTED)] != first_byte_state) { + return false; + } + const CSVState from_states[] = {CSVState::STANDARD, CSVState::DELIMITER, CSVState::RECORD_SEPARATOR, + CSVState::EMPTY_SPACE, CSVState::NOT_SET}; + for (const auto from : from_states) { + const auto from_idx = static_cast(from); + if (transition_array[delimiter_byte][from_idx] != first_byte_state) { + return false; + } + if (new_line == NewLineIdentifier::SINGLE_N && transition_array['\n'][from_idx] != CSVState::RECORD_SEPARATOR) { + return false; + } + if (new_line == NewLineIdentifier::CARRY_ON && transition_array['\r'][from_idx] != CSVState::CARRIAGE_RETURN) { + return false; + } + if (new_line == NewLineIdentifier::SINGLE_R && transition_array['\r'][from_idx] != CSVState::RECORD_SEPARATOR) { + return false; + } + if (comment != '\0' && transition_array[comment][from_idx] != CSVState::COMMENT) { + return false; + } + const bool after_separator = from != CSVState::STANDARD && from != CSVState::EMPTY_SPACE; + for (uint32_t byte = 0; byte < StateMachine::NUM_TRANSITIONS; byte++) { + if (byte == delimiter_byte || byte == '\n' || byte == '\r' || (quote != '\0' && byte == quote) || + (comment != '\0' && byte == comment)) { + continue; + } + const auto expected = byte == ' ' && after_separator ? CSVState::EMPTY_SPACE : CSVState::STANDARD; + if (transition_array[byte][from_idx] != expected) { + return false; + } + } + } + if (new_line == NewLineIdentifier::CARRY_ON && + transition_array['\n'][static_cast(CSVState::CARRIAGE_RETURN)] != CSVState::RECORD_SEPARATOR) { + return false; + } + if (comment != '\0') { + const auto in_comment = static_cast(CSVState::COMMENT); + if (transition_array['\n'][in_comment] != CSVState::RECORD_SEPARATOR) { + return false; + } + if (transition_array['\r'][in_comment] != + (new_line == NewLineIdentifier::CARRY_ON ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR)) { + return false; + } + for (uint32_t byte = 0; byte < StateMachine::NUM_TRANSITIONS; byte++) { + if (byte != '\n' && byte != '\r' && transition_array[byte][in_comment] != CSVState::COMMENT) { + return false; + } + } + } + if (quote == '\0') { + return true; + } + // the quoted value transitions the block scanner assumes + const auto standard = static_cast(CSVState::STANDARD); + const auto quoted = static_cast(CSVState::QUOTED); + const auto quoted_new_line = static_cast(CSVState::QUOTED_NEW_LINE); + const auto unquoted = static_cast(CSVState::UNQUOTED); + if (transition_array[quote][standard] != CSVState::STANDARD) { + return false; + } + const CSVState opening_states[] = {CSVState::DELIMITER, CSVState::RECORD_SEPARATOR, CSVState::EMPTY_SPACE, + CSVState::NOT_SET}; + for (const auto from : opening_states) { + if (transition_array[quote][static_cast(from)] != CSVState::QUOTED) { + return false; + } + } + if (transition_array[quote][quoted] != CSVState::UNQUOTED || + transition_array[quote][quoted_new_line] != CSVState::UNQUOTED) { + return false; + } + if (transition_array['\n'][quoted] != CSVState::QUOTED_NEW_LINE || + transition_array['\r'][quoted] != CSVState::QUOTED_NEW_LINE) { + return false; + } + if (transition_array['\n'][quoted_new_line] != CSVState::QUOTED || + transition_array['\r'][quoted_new_line] != CSVState::QUOTED) { + return false; + } + for (uint32_t byte = 0; byte < StateMachine::NUM_TRANSITIONS; byte++) { + if (byte == quote || byte == '\n' || byte == '\r') { + continue; + } + if (transition_array[byte][quoted] != CSVState::QUOTED || + transition_array[byte][quoted_new_line] != CSVState::QUOTED) { + return false; + } + } + if (new_line == NewLineIdentifier::SINGLE_N && transition_array['\n'][unquoted] != CSVState::RECORD_SEPARATOR) { + return false; + } + if (new_line == NewLineIdentifier::CARRY_ON && transition_array['\r'][unquoted] != CSVState::CARRIAGE_RETURN) { + return false; + } + if (new_line == NewLineIdentifier::SINGLE_R && transition_array['\r'][unquoted] != CSVState::RECORD_SEPARATOR) { + return false; + } + return escape != quote || transition_array[quote][unquoted] == CSVState::QUOTED; +} + void CSVStateMachineCache::Insert(const CSVStateMachineOptions &state_machine_options) { D_ASSERT(state_machine_cache.find(state_machine_options) == state_machine_cache.end()); // Initialize transition array with default values to the Standard option @@ -454,6 +588,7 @@ void CSVStateMachineCache::Insert(const CSVStateMachineOptions &state_machine_op if (escape != '\0' && escape != quote) { stop_patterns.push_back(SwarBlock::BytePattern::Byte(escape)); } + transition_array.block_scan = BlockScanEligible(transition_array, state_machine_options); } CSVStateMachineCache::CSVStateMachineCache() { diff --git a/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp b/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp index bcc682201..837f73edd 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp @@ -43,9 +43,9 @@ CSVReaderOptions::CSVReaderOptions(const CSVOption single_byte_delimiter, dialect_options.state_machine_options.delimiter = multi_byte_delimiter; } } -static bool ParseBoolean(const Value &value, const Identifier &loption); +static bool ParseBoolean(Context &context, const Value &value, const Identifier &loption); -static bool ParseBoolean(const vector &set, const Identifier &loption) { +static bool ParseBoolean(Context &context, const vector &set, const Identifier &loption) { if (set.empty()) { // no option specified: default to true return true; @@ -53,22 +53,22 @@ static bool ParseBoolean(const vector &set, const Identifier &loption) { if (set.size() > 1) { throw BinderException("%s expects a single argument as a boolean value (e.g. TRUE or 1)", loption); } - return ParseBoolean(set[0], loption); + return ParseBoolean(context, set[0], loption); } -static bool ParseBoolean(const Value &value, const Identifier &loption) { +static bool ParseBoolean(Context &context, const Value &value, const Identifier &loption) { if (value.IsNull()) { throw BinderException("%s expects a non-null boolean value (e.g. TRUE or 1)", loption); } if (value.type().id() == LogicalTypeId::LIST) { auto &children = ListValue::GetChildren(value); - return ParseBoolean(children, loption); + return ParseBoolean(context, children, loption); } if (value.type() == LogicalType::FLOAT || value.type() == LogicalType::DOUBLE || value.type().id() == LogicalTypeId::DECIMAL) { throw BinderException("%s expects a boolean value (e.g. TRUE or 1)", loption); } - return BooleanValue::Get(value.DefaultCastAs(LogicalType::BOOLEAN)); + return BooleanValue::Get(value.CastAs(context, LogicalType::BOOLEAN)); } static string ParseString(const Value &value, const Identifier &loption) { @@ -252,13 +252,13 @@ void CSVReaderOptions::SetDateFormat(LogicalTypeId type, const string &format, b } } -void CSVReaderOptions::SetReadOption(const Identifier &loption, const Value &value, +void CSVReaderOptions::SetReadOption(Context &context, const Identifier &loption, const Value &value, const vector &expected_names) { - if (SetBaseOption(loption, value)) { + if (SetBaseOption(context, loption, value)) { return; } if (loption == "auto_detect") { - auto_detect = ParseBoolean(value, loption); + auto_detect = ParseBoolean(context, value, loption); } else if (loption == "sample_size") { const auto sample_size_option = ParseInteger(value, loption); if (sample_size_option < 1 && sample_size_option != -1) { @@ -293,7 +293,7 @@ void CSVReaderOptions::SetReadOption(const Identifier &loption, const Value &val string format = ParseString(value, loption); SetDateFormat(LogicalTypeId::TIMESTAMP, format, true); } else if (loption == "ignore_errors") { - ignore_errors.Set(ParseBoolean(value, loption)); + ignore_errors.Set(ParseBoolean(context, value, loption)); } else if (loption == "buffer_size") { auto buffer_size = ParseInteger(value, loption); if (buffer_size < 0) { @@ -315,13 +315,13 @@ void CSVReaderOptions::SetReadOption(const Identifier &loption, const Value &val throw BinderException("Unsupported parameter for DECIMAL_SEPARATOR: should be '.' or ','"); } } else if (loption == "null_padding") { - null_padding = ParseBoolean(value, loption); + null_padding = ParseBoolean(context, value, loption); } else if (loption == "parallel") { - parallel = ParseBoolean(value, loption); + parallel = ParseBoolean(context, value, loption); } else if (loption == "allow_quoted_nulls") { - allow_quoted_nulls = ParseBoolean(value, loption); + allow_quoted_nulls = ParseBoolean(context, value, loption); } else if (loption == "store_rejects") { - store_rejects.Set(ParseBoolean(value, loption)); + store_rejects.Set(ParseBoolean(context, value, loption)); } else if (loption == "force_not_null") { if (!expected_names.empty()) { force_not_null = ParseColumnList(value, expected_names, loption); @@ -386,14 +386,14 @@ void CSVReaderOptions::SetReadOption(const Identifier &loption, const Value &val } } -void CSVReaderOptions::SetWriteOption(const Identifier &loption, const Value &value) { +void CSVReaderOptions::SetWriteOption(Context &context, const Identifier &loption, const Value &value) { if (loption == "new_line") { // Steal this from SetBaseOption so we can write different newlines (e.g., format JSON ARRAY) write_newline = ParseString(value, loption); return; } - if (SetBaseOption(loption, value, true)) { + if (SetBaseOption(context, loption, value, true)) { return; } @@ -418,7 +418,8 @@ void CSVReaderOptions::SetWriteOption(const Identifier &loption, const Value &va } } -bool CSVReaderOptions::SetBaseOption(const Identifier &loption, const Value &value, bool write_option) { +bool CSVReaderOptions::SetBaseOption(Context &context, const Identifier &loption, const Value &value, + bool write_option) { if (loption.StartsWith("delim") || loption.StartsWith("sep")) { SetDelimiter(ParseString(value, loption)); } else if (loption == "quote") { @@ -430,7 +431,7 @@ bool CSVReaderOptions::SetBaseOption(const Identifier &loption, const Value &val } else if (loption == "escape") { SetEscape(ParseString(value, loption)); } else if (loption == "header") { - SetHeader(ParseBoolean(value, loption)); + SetHeader(ParseBoolean(context, value, loption)); } else if (loption == "nullstr" || loption == "null") { auto &child_type = value.type(); null_str.clear(); @@ -483,7 +484,7 @@ bool CSVReaderOptions::SetBaseOption(const Identifier &loption, const Value &val } else if (loption == "compression") { SetCompression(ParseString(value, loption)); } else if (loption == "strict_mode") { - SetRFC4180(ParseBoolean(value, loption)); + SetRFC4180(ParseBoolean(context, value, loption)); } else { // unrecognized option in base CSV return false; @@ -849,7 +850,7 @@ void CSVReaderOptions::ParseOption(ClientContext &context, const Identifier &key } else if (key == "normalize_names") { normalize_names = GetBooleanValue(key, val); } else { - SetReadOption(key, val, name_list); + SetReadOption(context.GetContext(), key, val, name_list); } } //! This function is used to remember options set by the sniffer, for use in ReadCSVRelation diff --git a/src/duckdb/src/execution/operator/helper/physical_connect.cpp b/src/duckdb/src/execution/operator/helper/physical_connect.cpp index 3744495d3..a5e1e4d73 100644 --- a/src/duckdb/src/execution/operator/helper/physical_connect.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_connect.cpp @@ -77,7 +77,7 @@ SourceResultType PhysicalConnect::GetDataInternal(ExecutionContext &context, Dat ApplyLaunchedResource(launched, attach_info); auto &config = DBConfig::GetConfig(client); - AttachOptions options(attach_info.options, config.options.access_mode); + AttachOptions options(client.GetContext(), attach_info.options, config.options.access_mode); options.visibility = AttachVisibility::HIDDEN; options.ephemeral = true; if (owns_resource) { @@ -123,7 +123,7 @@ SourceResultType PhysicalConnect::GetDataInternal(ExecutionContext &context, Dat attach_info.options = info->options; auto &config = DBConfig::GetConfig(client); - AttachOptions options(attach_info.options, config.options.access_mode); + AttachOptions options(client.GetContext(), attach_info.options, config.options.access_mode); options.visibility = AttachVisibility::HIDDEN; options.ephemeral = true; options.original_path = attach_info.path; diff --git a/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp index a1fda7044..d8971bddf 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp @@ -728,7 +728,7 @@ SourceResultType PhysicalBatchCopyToFile::GetDataInternal(ExecutionContext &cont case CopyFunctionReturnType::WRITTEN_FILE_STATISTICS: { if (g.written_file_info) { g.written_file_info->file_path = std::move(fp); - PhysicalCopyToFile::ReturnStatistics(chunk, *g.written_file_info); + PhysicalCopyToFile::ReturnStatistics(context.client.GetContext(), chunk, *g.written_file_info); } else if (return_column_types) { // WRITE_EMPTY_FILE false writes no file without rows PhysicalCopyToFile::ReturnNoFileStatistics(chunk); diff --git a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp index 5ce771f82..3cda66bdb 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp @@ -149,7 +149,8 @@ class CopyOutputFileRegistry { public: //! The registry is guarded by CopyToFileGlobalState::lock. - PendingFileState ReserveFile(string output_path, optional_ptr> partition_values); + PendingFileState ReserveFile(Context &context, string output_path, + optional_ptr> partition_values); void PublishCreatedPath(PendingFileState &pending_file_state, string output_path); idx_t WrittenFileCount() const { @@ -1927,7 +1928,7 @@ bool CopyDirectoryManager::EnsureDirectory(FileSystem &fs, const string &dir_pat return created; } -PendingFileState CopyOutputFileRegistry::ReserveFile(string output_path, +PendingFileState CopyOutputFileRegistry::ReserveFile(Context &context, string output_path, optional_ptr> partition_values) { PendingFileState result; result.output_path = std::move(output_path); @@ -1944,7 +1945,7 @@ PendingFileState CopyOutputFileRegistry::ReserveFile(string output_path, const auto &partition_col_name = op.names[op.partition_columns[i]]; const auto &partition_value = (*partition_values)[i]; partition_keys.emplace_back(partition_col_name); - partition_values_as_varchar.push_back(partition_value.DefaultCastAs(LogicalType::VARCHAR)); + partition_values_as_varchar.push_back(partition_value.CastAs(context, LogicalType::VARCHAR)); } result.written_file_info->partition_keys = Value::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR, std::move(partition_keys), @@ -4569,7 +4570,7 @@ PendingFileState CopyToFileGlobalState::PrepareFileStateLocked(string output_pat if (output_path.empty()) { output_path = op.filename_pattern.CreateFilename(fs, op.file_path, op.file_extension, last_file_offset++); } - auto result = output_files.ReserveFile(std::move(output_path), partition_values); + auto result = output_files.ReserveFile(context.GetContext(), std::move(output_path), partition_values); output_files.PublishCreatedPath(result, result.output_path); return result; } @@ -4619,7 +4620,8 @@ CopyToFileGlobalState::CreatePartitionFileStateOpenLocked(FileStateHandle &file_ return PendingFileStateOpen(); } PendingFileStateOpen result; - result.pending_file_state = output_files.ReserveFile(std::move(output_path), partition_values); + result.pending_file_state = + output_files.ReserveFile(context.GetContext(), std::move(output_path), partition_values); result.open_job = make_shared_ptr(); file_state.open_job = result.open_job; return result; @@ -4884,7 +4886,7 @@ void PhysicalCopyToFile::ReturnColumnTypes(DataChunk &chunk, const vector extra_values; for (auto &entry : file_stats.extra_info) { extra_keys.emplace_back(entry.first); - extra_values.push_back(entry.second.DefaultCastAs(LogicalType::VARIANT())); + extra_values.push_back(entry.second.CastAs(context, LogicalType::VARIANT())); } chunk.data[6].Append( Value::MAP(LogicalType::VARCHAR, LogicalType::VARIANT(), std::move(extra_keys), std::move(extra_values))); @@ -5306,7 +5308,7 @@ SourceResultType PhysicalCopyToFile::GetDataInternal(ExecutionContext &context, if (use_tmp_file) { file_entry.file_path = GetNonTmpFile(context.client, file_entry.file_path); } - ReturnStatistics(chunk, file_entry); + ReturnStatistics(context.client.GetContext(), chunk, file_entry); } if (return_column_types) { if (gstate.output_files.WrittenFileCount() == 0) { diff --git a/src/duckdb/src/execution/operator/schema/physical_attach.cpp b/src/duckdb/src/execution/operator/schema/physical_attach.cpp index f50fa6974..7ddc9ed93 100644 --- a/src/duckdb/src/execution/operator/schema/physical_attach.cpp +++ b/src/duckdb/src/execution/operator/schema/physical_attach.cpp @@ -104,7 +104,7 @@ SourceResultType PhysicalAttach::GetDataInternal(ExecutionContext &context, Data } // construct the options - AttachOptions options(attach_info->options, config.options.access_mode); + AttachOptions options(context.client.GetContext(), attach_info->options, config.options.access_mode); if (owns_resource) { options.deleter_function = launched.deleter_function; options.deleter_payload = launched.deleter_payload; diff --git a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp index cf932a23e..47cb8e9c5 100644 --- a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp @@ -333,16 +333,8 @@ static idx_t ValidateAsOfConditions(LogicalComparisonJoin &op, vector &eq } PhysicalOperator &PhysicalPlanGenerator::PlanAsOfJoin(LogicalComparisonJoin &op) { -#ifdef D_ASSERT_IS_ENABLED - // The sorted ASOF operator emits the full left payload in child order (see column_lifetime_analyzer.cpp), - // so the only supported left projection maps are empty or full-width identity. - if (op.join_type != JoinType::MARK && !op.left_projection_map.empty()) { - D_ASSERT(op.left_projection_map.size() == op.children[0]->GetColumnBindings().size()); - for (idx_t i = 0; i < op.left_projection_map.size(); i++) { - D_ASSERT(op.left_projection_map[i].GetIndex() == i); - } - } -#endif + // The sorted ASOF operator emits the full left payload in child order. Pruning left projection maps are + // honored by ExtractPrunedJoinProjection, which wraps the operator in an explicit projection. // If we have a predicate and its a "simple" join, then we can just plan a regular join switch (op.join_type) { case JoinType::SEMI: @@ -406,7 +398,11 @@ PhysicalOperator &PhysicalPlanGenerator::PlanAsOfJoin(LogicalComparisonJoin &op) rhs_partition_cols.clear(); } - return Make(op, left, right, lhs_partition_cols, rhs_partition_cols); + // The sorted operator always emits the full left input width. A pruning left + // projection map is applied through a projection above the join instead. + auto pruned = ExtractPrunedJoinProjection(op, left, right, true, false); + auto &asof_join = Make(op, left, right, lhs_partition_cols, rhs_partition_cols); + return RestorePrunedJoinProjection(op, asof_join, std::move(pruned)); } return *PlanAsOfInequalityJoin(op, left, right, lhs_cardinality, rhs_cardinality); diff --git a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp index 3a3267568..da38e9748 100644 --- a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp @@ -6,6 +6,7 @@ #include "duckdb/execution/operator/join/physical_join.hpp" #include "duckdb/execution/operator/join/physical_nested_loop_join.hpp" #include "duckdb/execution/operator/join/physical_piecewise_merge_join.hpp" +#include "duckdb/execution/operator/projection/physical_projection.hpp" #include "duckdb/execution/operator/join/physical_recursive_cte_key_join.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/execution/physical_plan_generator.hpp" @@ -247,7 +248,8 @@ PhysicalOperator &PhysicalPlanGenerator::PlanComparisonJoin(LogicalComparisonJoi return join; } - // range joins apply both projection maps, the nested loop join only applies the left one of a MARK join + // the IE join applies both projection maps, the nested loop join only applies the left one of a MARK join, + // and the piecewise merge and blockwise joins emit full child layouts idx_t nested_loop_join_threshold = Settings::Get(context); if (left.estimated_cardinality < nested_loop_join_threshold || right.estimated_cardinality < nested_loop_join_threshold) { @@ -267,15 +269,19 @@ PhysicalOperator &PhysicalPlanGenerator::PlanComparisonJoin(LogicalComparisonJoi std::move(op.filter_pushdown)); } if (can_merge) { - // range join: use piecewise merge join - return Make(op, left, right, std::move(op.conditions), op.join_type, - op.estimated_cardinality, std::move(op.filter_pushdown)); + // range join: use piecewise merge join, which emits full child layouts + auto pruned = ExtractPrunedJoinProjection(op, left, right, true, true); + auto &join = Make(op, left, right, std::move(op.conditions), op.join_type, + op.estimated_cardinality, std::move(op.filter_pushdown)); + return RestorePrunedJoinProjection(op, join, std::move(pruned)); } if (PhysicalNestedLoopJoin::IsSupported(op.conditions, op.join_type)) { - // inequality join: use nested loop + // inequality join: use nested loop, which only applies the left map of a MARK join + auto pruned = ExtractPrunedJoinProjection(op, left, right, op.join_type != JoinType::MARK, true); D_ASSERT(op.left_projection_map.empty() || op.join_type == JoinType::MARK); - return Make(op, left, right, std::move(op.conditions), op.join_type, - op.estimated_cardinality, std::move(op.filter_pushdown)); + auto &join = Make(op, left, right, std::move(op.conditions), op.join_type, + op.estimated_cardinality, std::move(op.filter_pushdown)); + return RestorePrunedJoinProjection(op, join, std::move(pruned)); } for (auto &cond : op.conditions) { @@ -283,9 +289,145 @@ PhysicalOperator &PhysicalPlanGenerator::PlanComparisonJoin(LogicalComparisonJoi RewriteJoinCondition(cond.RightReference(), left.types.size()); } } + auto pruned = ExtractPrunedJoinProjection(op, left, right, true, true); D_ASSERT(op.left_projection_map.empty()); auto condition = JoinCondition::CreateExpression(std::move(op.conditions)); - return Make(op, left, right, std::move(condition), op.join_type, op.estimated_cardinality); + auto &join = + Make(op, left, right, std::move(condition), op.join_type, op.estimated_cardinality); + return RestorePrunedJoinProjection(op, join, std::move(pruned)); +} + +static bool IsPruningMap(const vector &projection_map, idx_t input_width) { + if (projection_map.empty()) { + return false; + } + if (projection_map.size() != input_width) { + return true; + } + for (idx_t i = 0; i < projection_map.size(); i++) { + if (projection_map[i].GetIndex() != i) { + return true; + } + } + return false; +} + +PhysicalPlanGenerator::PrunedJoinProjection +PhysicalPlanGenerator::ExtractPrunedJoinProjection(LogicalComparisonJoin &op, const PhysicalOperator &left, + const PhysicalOperator &right, bool expand_left, bool expand_right) { + PrunedJoinProjection info; + const auto left_width = left.GetTypes().size(); + const auto right_width = right.GetTypes().size(); + const bool emits_left = op.join_type != JoinType::RIGHT_SEMI && op.join_type != JoinType::RIGHT_ANTI; + const bool emits_right = + op.join_type != JoinType::SEMI && op.join_type != JoinType::ANTI && op.join_type != JoinType::MARK; + info.expanded_left = expand_left && emits_left && IsPruningMap(op.left_projection_map, left_width); + info.expanded_right = expand_right && emits_right && IsPruningMap(op.right_projection_map, right_width); + // a full identity map selects everything: drop it for operators that require an empty map + if (expand_left && !info.expanded_left && !op.left_projection_map.empty()) { + op.left_projection_map.clear(); + } + if (expand_right && !info.expanded_right && !op.right_projection_map.empty()) { + op.right_projection_map.clear(); + } + if (!info.expanded_left && !info.expanded_right) { + return info; + } + info.active = true; + info.original_types = op.types; + if (info.expanded_left) { + info.left_map = std::move(op.left_projection_map); + op.left_projection_map.clear(); + } + if (info.expanded_right) { + info.right_map = std::move(op.right_projection_map); + op.right_projection_map.clear(); + } + // emitted layout: per side either the full input or the original mapped columns, + // with the MARK column in between where the join type produces one + vector emitted; + idx_t original_pos = 0; + if (emits_left) { + if (info.expanded_left) { + auto &left_types = left.GetTypes(); + emitted.insert(emitted.end(), left_types.begin(), left_types.end()); + original_pos += info.left_map.size(); + } else { + idx_t count = op.left_projection_map.empty() ? left_width : op.left_projection_map.size(); + emitted.insert(emitted.end(), info.original_types.begin(), + info.original_types.begin() + NumericCast(count)); + original_pos += count; + } + } + if (op.join_type == JoinType::MARK) { + emitted.push_back(info.original_types[original_pos]); + original_pos++; + } + if (emits_right) { + if (info.expanded_right) { + auto &right_types = right.GetTypes(); + emitted.insert(emitted.end(), right_types.begin(), right_types.end()); + } else { + emitted.insert(emitted.end(), info.original_types.begin() + NumericCast(original_pos), + info.original_types.end()); + } + } + op.types = std::move(emitted); + return info; +} + +PhysicalOperator &PhysicalPlanGenerator::RestorePrunedJoinProjection(LogicalComparisonJoin &op, PhysicalOperator &join, + PrunedJoinProjection info) { + if (!info.active) { + return join; + } + auto &emitted_types = join.GetTypes(); + const bool emits_left = op.join_type != JoinType::RIGHT_SEMI && op.join_type != JoinType::RIGHT_ANTI; + const bool emits_right = + op.join_type != JoinType::SEMI && op.join_type != JoinType::ANTI && op.join_type != JoinType::MARK; + vector> select_list; + select_list.reserve(info.original_types.size()); + idx_t emitted_pos = 0; + if (emits_left) { + idx_t emitted_left_width; + if (info.expanded_left) { + emitted_left_width = join.children[0].get().GetTypes().size(); + for (auto &entry : info.left_map) { + auto index = entry.GetIndex(); + select_list.push_back(make_uniq(emitted_types[index], index)); + } + } else { + emitted_left_width = op.left_projection_map.empty() ? join.children[0].get().GetTypes().size() + : op.left_projection_map.size(); + for (idx_t i = 0; i < emitted_left_width; i++) { + select_list.push_back(make_uniq(emitted_types[i], i)); + } + } + emitted_pos += emitted_left_width; + } + if (op.join_type == JoinType::MARK) { + select_list.push_back(make_uniq(emitted_types[emitted_pos], emitted_pos)); + emitted_pos++; + } + if (emits_right) { + if (info.expanded_right) { + for (auto &entry : info.right_map) { + auto index = emitted_pos + entry.GetIndex(); + select_list.push_back(make_uniq(emitted_types[index], index)); + } + } else { + for (idx_t i = emitted_pos; i < emitted_types.size(); i++) { + select_list.push_back(make_uniq(emitted_types[i], i)); + } + } + } + D_ASSERT(select_list.size() == info.original_types.size()); + auto &projection = + Make(info.original_types, std::move(select_list), join.estimated_cardinality); + projection.children.emplace_back(join); + // callers of CreatePlan read the logical schema afterwards: restore it + op.types = std::move(info.original_types); + return projection; } PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalComparisonJoin &op) { diff --git a/src/duckdb/src/function/cast/bignum_casts.cpp b/src/duckdb/src/function/cast/bignum_casts.cpp index db75f6eee..ac0b007bb 100644 --- a/src/duckdb/src/function/cast/bignum_casts.cpp +++ b/src/duckdb/src/function/cast/bignum_casts.cpp @@ -5,6 +5,9 @@ #include "duckdb/common/bignum.hpp" #include "duckdb/common/bit_utils.hpp" +#include +#include + namespace duckdb { template @@ -166,28 +169,45 @@ bignum_t HugeintCastToBignum::Operation(hugeint_t int_value, StringHeap &heap) { template <> bool TryCastToBignum::Operation(string_t input_value, bignum_t &result_value, Vector &result, CastParameters ¶meters) { - idx_t start_pos, end_pos; - bool is_negative, is_zero; - bool should_round_up; - if (!Bignum::VarcharFormatting(input_value, start_pos, end_pos, is_negative, is_zero, should_round_up)) { - return false; - } + BignumCastScratch scratch; + return Bignum::TryVarcharToBignum(input_value, result_value, result, scratch); +} - auto blob_string = - Bignum::EncodeVarcharBignum(input_value, start_pos, end_pos, is_negative, is_zero, should_round_up); +struct VarcharToBignumCastData { + VarcharToBignumCastData(Vector &result, CastParameters ¶meters) : vector_cast_data(result, parameters) { + } - uint32_t blob_size = static_cast(blob_string.size()); - result_value = bignum_t(StringVector::EmptyString(result, blob_size)); - auto writable_blob = result_value.data.GetDataWriteable(); + VectorTryCastData vector_cast_data; + BignumCastScratch scratch; +}; - // Write string_blob into blob - for (idx_t i = 0; i < blob_string.size(); i++) { - writable_blob[i] = blob_string[i]; +struct VarcharToBignumOperator { + template + static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, VarcharToBignumCastData &data) { + RESULT_TYPE output; + if (DUCKDB_LIKELY(Bignum::TryVarcharToBignum(input, output, data.vector_cast_data.result, data.scratch))) { + return output; + } + return HandleVectorCastError::Operation( + CastExceptionText(input, data.vector_cast_data.result.GetType()), mask, idx, + data.vector_cast_data); } - result_value.data.Finalize(); +}; + +bool Bignum::BignumToVarcharCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { + D_ASSERT(result.GetType().InternalType() == PhysicalType::VARCHAR); + BignumCastScratch scratch; + UnaryExecutor::Execute( + source, result, count, [&](bignum_t input) { return Bignum::BignumToVarchar(input, result, scratch); }); return true; } +bool Bignum::VarcharToBignumCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { + VarcharToBignumCastData data(result, parameters); + UnaryExecutor::GenericExecute(source, result, count, data); + return data.vector_cast_data.all_converted; +} + template static bool DoubleToBignum(T double_value, bignum_t &result_value, Vector &result) { // Check if we can cast it @@ -200,35 +220,44 @@ static bool DoubleToBignum(T double_value, bignum_t &result_value, Vector &resul // Determine if the number is negative bool is_negative = double_value < 0; // Determine the number of data bytes - double abs_value = std::abs(double_value); + double abs_value = std::abs(static_cast(double_value)); if (abs_value == 0) { // Return Value 0 result_value = Bignum::InitializeBignumZero(result); return true; } - vector value; - while (abs_value > 0) { - double quotient = abs_value / 256; - double truncated = floor(quotient); - uint8_t byte = static_cast(abs_value - truncated * 256); - abs_value = truncated; - if (is_negative) { - value.push_back(static_cast(~byte)); + // abs_value = fraction * 2^exponent with 0.5 <= fraction < 1, i.e. mantissa * 2^(exponent - 53) with an integer + // mantissa of exactly 53 bits + int exponent; + const double fraction = std::frexp(abs_value, &exponent); + uint64_t top = 0; + idx_t top_bytes = 1; + idx_t zero_bytes = 0; + if (exponent > 0) { + constexpr int MANTISSA_BITS = 53; + const auto mantissa = static_cast(std::ldexp(fraction, MANTISSA_BITS)); + if (exponent <= MANTISSA_BITS) { + // the fraction is dropped, this leaves "exponent" bits + top = mantissa >> (MANTISSA_BITS - exponent); + top_bytes = (static_cast(exponent) + 7) / 8; } else { - value.push_back(static_cast(byte)); + // the mantissa is followed by (exponent - 53) zero bits: whole zero bytes, and a shift of the mantissa + const int shift = exponent - MANTISSA_BITS; + zero_bytes = static_cast(shift) / 8; + top = mantissa << (shift % 8); + top_bytes = (static_cast(exponent) + 7) / 8 - zero_bytes; } } - uint32_t data_byte_size = static_cast(value.size()); - uint32_t blob_size = data_byte_size + Bignum::BIGNUM_HEADER_SIZE; + // a magnitude below one has an integer part of zero, which keeps the sign of the input as before + const idx_t data_byte_size = top_bytes + zero_bytes; + const idx_t blob_size = data_byte_size + Bignum::BIGNUM_HEADER_SIZE; result_value.data = StringVector::EmptyString(result, blob_size); auto writable_blob = result_value.data.GetDataWriteable(); Bignum::SetHeader(writable_blob, data_byte_size, is_negative); - // Add data bytes to the blob, starting off after header bytes - idx_t blob_string_idx = value.size() - 1; - for (idx_t i = Bignum::BIGNUM_HEADER_SIZE; i < blob_size; i++) { - writable_blob[i] = value[blob_string_idx--]; - } + BignumLimb::StoreMagnitudePartial(data_ptr_cast(writable_blob + Bignum::BIGNUM_HEADER_SIZE), top_bytes, top, + is_negative); + memset(writable_blob + Bignum::BIGNUM_HEADER_SIZE + top_bytes, is_negative ? 0xFF : 0x00, zero_bytes); result_value.data.Finalize(); return true; } @@ -339,7 +368,7 @@ BoundCastInfo DefaultCasts::BignumCastSwitch(BindCastInput &input, const Logical return BoundCastInfo(&VectorCastHelpers::TryCastErrorLoop); case LogicalTypeId::VARCHAR: - return BoundCastInfo(&VectorCastHelpers::StringCast); + return BoundCastInfo(&Bignum::BignumToVarcharCast); case LogicalTypeId::DOUBLE: return BoundCastInfo(&VectorCastHelpers::TryCastErrorLoop); default: diff --git a/src/duckdb/src/function/cast/cast_function_set.cpp b/src/duckdb/src/function/cast/cast_function_set.cpp index f71650abe..d01c24f08 100644 --- a/src/duckdb/src/function/cast/cast_function_set.cpp +++ b/src/duckdb/src/function/cast/cast_function_set.cpp @@ -67,6 +67,10 @@ CollationBinding &CollationBinding::Get(ClientContext &context) { return DBConfig::GetConfig(context).GetCollationBinding(); } +CastFunctionSet &CastFunctionSet::Get(Context &context) { + return DBConfig::GetConfig(context.GetDatabase()).GetCastFunctions(); +} + CastFunctionSet &CastFunctionSet::Get(DatabaseInstance &db) { return DBConfig::GetConfig(db).GetCastFunctions(); } diff --git a/src/duckdb/src/function/cast/string_cast.cpp b/src/duckdb/src/function/cast/string_cast.cpp index ce5893030..9551b089c 100644 --- a/src/duckdb/src/function/cast/string_cast.cpp +++ b/src/duckdb/src/function/cast/string_cast.cpp @@ -526,7 +526,7 @@ BoundCastInfo DefaultCasts::StringCastSwitch(BindCastInput &input, const Logical input, LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR), target), InitMapCastLocalState); case LogicalTypeId::BIGNUM: - return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); + return BoundCastInfo(&Bignum::VarcharToBignumCast); default: return VectorStringCastNumericSwitch(input, source, target); } diff --git a/src/duckdb/src/function/scalar/list/list_extract.cpp b/src/duckdb/src/function/scalar/list/list_extract.cpp index 5c7910077..91df66b68 100644 --- a/src/duckdb/src/function/scalar/list/list_extract.cpp +++ b/src/duckdb/src/function/scalar/list/list_extract.cpp @@ -141,7 +141,7 @@ static unique_ptr StringExtractBind(BindScalarFunctionInput &input return nullptr; } string error; - auto index_value = index->DefaultTryCastAs(LogicalType::BIGINT, &error); + auto index_value = index->TryCastAs(input.GetClientContext(), LogicalType::BIGINT, &error); if (!index_value) { // the index is a constant that cannot be converted to an integer at all - report that directly throw ConversionException(error); diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index 2e9953f06..cbd9e05e3 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -473,17 +473,13 @@ static void BignumAdd(DataChunk &args, ExpressionState &state, Vector &result) { static void BignumSubtract(DataChunk &args, ExpressionState &state, Vector &result) { auto &heap = StringVector::GetStringHeap(result); - // negate a copy of the right operand - the input must not be modified, it can e.g. also be the left operand - vector negated_rhs; - BinaryExecutor::Execute( - args.data[0], args.data[1], result, [&](bignum_t a, bignum_t b) { - const BignumIntermediate lhs(a); - negated_rhs.resize(b.data.GetSize()); - memcpy(negated_rhs.data(), b.data.GetData(), b.data.GetSize()); - BignumIntermediate rhs(negated_rhs.data(), negated_rhs.size()); - rhs.NegateInPlace(); - return BignumIntermediate::Add(heap, lhs, rhs); - }); + BinaryExecutor::Execute(args.data[0], args.data[1], result, + [&](bignum_t a, bignum_t b) { + const BignumIntermediate lhs(a); + const BignumIntermediate rhs(b); + // the right operand is subtracted without being copied + return BignumIntermediate::Add(heap, lhs, rhs, true); + }); } //! The client context (if any) lets long BIGNUM multiplications and divisions check for interrupts diff --git a/src/duckdb/src/function/scalar/string/substring.cpp b/src/duckdb/src/function/scalar/string/substring.cpp index 048c6c8ba..a7e1dbd7c 100644 --- a/src/duckdb/src/function/scalar/string/substring.cpp +++ b/src/duckdb/src/function/scalar/string/substring.cpp @@ -334,14 +334,14 @@ unique_ptr SubstringBind(BindScalarFunctionInput &input) { if (!offset || offset->IsNull()) { return nullptr; } - auto offset_value = offset->DefaultCastAs(LogicalType::BIGINT).GetValue(); + auto offset_value = offset->CastAs(input.GetClientContext(), LogicalType::BIGINT).GetValue(); int64_t length_value = NumericLimits::Maximum(); if (input.GetArguments().size() == 3) { auto length = input.TryGetConstant(2); if (!length || length->IsNull()) { return nullptr; } - length_value = length->DefaultCastAs(LogicalType::BIGINT).GetValue(); + length_value = length->CastAs(input.GetClientContext(), LogicalType::BIGINT).GetValue(); } if (SubstringInSupportedRange(offset_value, length_value)) { input.GetBoundFunction().SetErrorMode(FunctionErrors::CANNOT_ERROR); diff --git a/src/duckdb/src/function/scalar/system/aggregate_export.cpp b/src/duckdb/src/function/scalar/system/aggregate_export.cpp index 45871a646..5126430d5 100644 --- a/src/duckdb/src/function/scalar/system/aggregate_export.cpp +++ b/src/duckdb/src/function/scalar/system/aggregate_export.cpp @@ -757,7 +757,7 @@ unique_ptr BindToAggregateState(INPUT &input) { } } // the arguments are not yet cast to the parameter types when binding - auto function_name_val = input.GetNonNullConstant(1).DefaultCastAs(LogicalType::VARCHAR); + auto function_name_val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::VARCHAR); auto function_name = StringValue::Get(function_name_val); auto signature_val = input.GetNonNullConstant(2); @@ -779,7 +779,7 @@ unique_ptr BindToAggregateState(INPUT &input) { } for (auto &entry : constant_parameters) { // cast each constant to the argument type declared in the signature - entry.second = entry.second.DefaultCastAs(argument_types[entry.first]); + entry.second = entry.second.CastAs(context, argument_types[entry.first]); } auto bind_data = BindExportedAggregate(context, function_name, argument_types, constant_parameters); diff --git a/src/duckdb/src/function/scalar/system/parse_log_message.cpp b/src/duckdb/src/function/scalar/system/parse_log_message.cpp index e21c4c65a..e5ec96718 100644 --- a/src/duckdb/src/function/scalar/system/parse_log_message.cpp +++ b/src/duckdb/src/function/scalar/system/parse_log_message.cpp @@ -79,7 +79,7 @@ void ParseLogMessageFunction(DataChunk &args, ExpressionState &state, Vector &re if (info.log_type.is_structured) { // TODO: allow more complex parsing operations than DefaultCast - VectorOperations::DefaultCast(args.data[1], result, args.size(), true); + VectorOperations::Cast(state.GetContext(), args.data[1], result, args.size(), true); } else { auto &struct_entries = StructVector::GetEntries(result); struct_entries[0].Reference(args.data[1]); diff --git a/src/duckdb/src/function/table/copy_csv.cpp b/src/duckdb/src/function/table/copy_csv.cpp index c5f3869a1..775e002e5 100644 --- a/src/duckdb/src/function/table/copy_csv.cpp +++ b/src/duckdb/src/function/table/copy_csv.cpp @@ -158,7 +158,7 @@ static unique_ptr WriteCSVBind(ClientContext &context, CopyFunctio // check all the options in the copy info for (auto &[option_name, option_values] : input.info.options) { - bind_data->options.SetWriteOption(option_name, ConvertVectorToValue(option_values)); + bind_data->options.SetWriteOption(context.GetContext(), option_name, ConvertVectorToValue(option_values)); } // verify the parsed options if (bind_data->options.force_quote.empty()) { diff --git a/src/duckdb/src/function/table/read_duckdb.cpp b/src/duckdb/src/function/table/read_duckdb.cpp index ae436a559..9626ae7f6 100644 --- a/src/duckdb/src/function/table/read_duckdb.cpp +++ b/src/duckdb/src/function/table/read_duckdb.cpp @@ -259,7 +259,7 @@ AttachedDatabase &DuckDBReader::GetAttachedDatabase() { info.name = GenerateInternalName("__duckdb_reader_"); info.on_conflict = OnCreateConflict::ERROR_ON_CONFLICT; unordered_map attach_kv; - AttachOptions attach_options(attach_kv, AccessMode::READ_ONLY); + AttachOptions attach_options(context.GetContext(), attach_kv, AccessMode::READ_ONLY); attach_options.visibility = AttachVisibility::HIDDEN; auto attached = db_manager.AttachDatabase(context, info, attach_options); diff --git a/src/duckdb/src/function/table/system/create_external_resource.cpp b/src/duckdb/src/function/table/system/create_external_resource.cpp index c5c7b030a..6f454fd29 100644 --- a/src/duckdb/src/function/table/system/create_external_resource.cpp +++ b/src/duckdb/src/function/table/system/create_external_resource.cpp @@ -128,7 +128,7 @@ static unique_ptr CreateExternalResourceBind(ClientContext &contex result->adopt_handle = np.second.type().id() == LogicalTypeId::MAP ? np.second - : np.second.DefaultCastAs(LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); + : np.second.CastAs(context, LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); } else if (key == "teardown_on_failure" && !np.second.IsNull()) { result->teardown_on_failure = BooleanValue::Get(np.second); } else if (key == "timeout_seconds" && !np.second.IsNull()) { diff --git a/src/duckdb/src/function/table/system/enable_profiling.cpp b/src/duckdb/src/function/table/system/enable_profiling.cpp index afe903ab8..8d450b8f3 100644 --- a/src/duckdb/src/function/table/system/enable_profiling.cpp +++ b/src/duckdb/src/function/table/system/enable_profiling.cpp @@ -59,7 +59,10 @@ static void EnableProfiling(ClientContext &context, TableFunctionInput &data, Da if (metrics_value.type().id() == LogicalTypeId::VARCHAR) { metrics_value = Value::LIST(LogicalType::VARCHAR, {metrics_value}); } - TrackedMetricsSetting::SetLocal(context, metrics_value); + // validate the metrics like SET tracked_metrics does + SettingCallbackInfo info(context, SetScope::SESSION); + TrackedMetricsSetting::OnSet(info, metrics_value); + Settings::Set(context, SetScope::SESSION, std::move(metrics_value)); } } diff --git a/src/duckdb/src/function/table/system/external_resources.cpp b/src/duckdb/src/function/table/system/external_resources.cpp index a7afe7f93..11c6a3b95 100644 --- a/src/duckdb/src/function/table/system/external_resources.cpp +++ b/src/duckdb/src/function/table/system/external_resources.cpp @@ -23,9 +23,11 @@ namespace duckdb { // `discover := true` also lists what exists externally. The call is then rewritten (bind_replace) into // plain SQL: the registry UNION ALL one `SELECT ... FROM ()` per type with a list callback, // each tagged with its type name and anti-joined against the registry, so a resource registered here is -// shown once, as managed. A `type` restriction leaves out the other types' branches up front, and a -// `WHERE type = ...` on the result is pushed into the branches by the optimizer, where it folds to a -// constant and drops the branch - so only the callbacks of the types asked for run. +// shown once, as managed. A list callback returns one row per resource: handle (MAP), name, reference and +// state. The name is the provider's own name for the resource (unique within the type), so a discovered +// row can be referred to by it; a registered row shows its local name instead. A `type` restriction leaves out the +// other types' branches up front, and a `WHERE type = ...` on the result is pushed into the branches by the optimizer, +// where it folds to a constant and drops the branch - so only the callbacks of the types asked for run. //===--------------------------------------------------------------------===// struct ExternalResourcesParameters { @@ -99,16 +101,16 @@ static unique_ptr ExternalResourcesBindReplace(ClientContext &context, "external resource discovery for type \"%s\": the list callback \"%s\" does not exist", type.name, type.list_function); } - // The callback returns handle (MAP), reference and state; the rows registered here are left out by handle. - // The callback's rows are aliased with its name, so a binder error about a missing column names it. + // The callback returns handle (MAP), name, reference and state; the rows registered here are left out by + // handle. The callback's rows are aliased with its name, so a binder error about a missing column names it. auto type_literal = Value(type.name).ToSQLString(); auto alias = KeywordHelper::WriteQuotedAndEscaped(type.list_function, '"'); branches.push_back(StringUtil::Format( - "SELECT NULL::VARCHAR AS name, %s AS type, false AS managed, %s.state::VARCHAR AS state, " + "SELECT %s.name::VARCHAR AS name, %s AS type, false AS managed, %s.state::VARCHAR AS state, " "%s.reference::VARCHAR AS reference, NULL::VARCHAR AS uri, NULL::VARCHAR AS attached_db_type, " "%s.handle::MAP(VARCHAR, VARCHAR) AS handle FROM %s(MAP {}::MAP(VARCHAR, VARCHAR)) AS %s " "ANTI JOIN %s AS registry ON %s.handle = registry.handle", - type_literal, alias, alias, alias, callback, alias, RegistryScan(type.name), alias)); + alias, type_literal, alias, alias, alias, callback, alias, RegistryScan(type.name), alias)); } // A type nothing provides but the registry knows (its extension is not loaded, or it was registered as an // opaque type) has nothing to discover, like a type without a list callback. A type neither knows is most diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index 2ecf50d61..d097e3018 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-alpha54042" +#define DUCKDB_PATCH_VERSION "0-alpha54418" #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-alpha54042" +#define DUCKDB_VERSION "v2.1.0-alpha54418" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "45c50f87c4" +#define DUCKDB_SOURCE_ID "23221edfd5" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/window/window_value_function.cpp b/src/duckdb/src/function/window/window_value_function.cpp index 09cfd8a6b..e1f2adcdf 100644 --- a/src/duckdb/src/function/window/window_value_function.cpp +++ b/src/duckdb/src/function/window/window_value_function.cpp @@ -367,7 +367,7 @@ class WindowLeadLagStreamingState : public WindowExecutorStreamingState { if (!ExpressionExecutor::TryEvaluateScalar(client, *offset_expr, offset_value) || offset_value.IsNull()) { return false; } - auto bigint_value = offset_value.DefaultTryCastAs(LogicalType::BIGINT); + auto bigint_value = offset_value.TryCastAs(client, LogicalType::BIGINT); if (!bigint_value) { return false; } @@ -398,7 +398,7 @@ class WindowLeadLagStreamingState : public WindowExecutorStreamingState { if (!ExpressionExecutor::TryEvaluateScalar(client, *default_expr, dflt_value)) { return false; } - auto cast_value = dflt_value.DefaultTryCastAs(wexpr.GetReturnType()); + auto cast_value = dflt_value.TryCastAs(client, wexpr.GetReturnType()); if (!cast_value) { return false; } @@ -1094,7 +1094,7 @@ class WindowNthValueStreamingState : public WindowValueStreamingState { if (!ExpressionExecutor::TryEvaluateScalar(client, *nth_expr, nth_value) || nth_value.IsNull()) { return false; } - auto bigint_value = nth_value.DefaultTryCastAs(LogicalType::BIGINT); + auto bigint_value = nth_value.TryCastAs(client, LogicalType::BIGINT); if (!bigint_value) { return false; } diff --git a/src/duckdb/src/include/duckdb/common/bignum.hpp b/src/duckdb/src/include/duckdb/common/bignum.hpp index 0815025f1..c9acf2053 100644 --- a/src/duckdb/src/include/duckdb/common/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/bignum.hpp @@ -14,6 +14,7 @@ #include "duckdb/common/optional_ptr.hpp" #include #include "duckdb/common/types/string_type.hpp" +#include "duckdb/common/bignum_limbs.hpp" namespace duckdb { class StringHeap; @@ -46,10 +47,6 @@ enum AbsoluteNumberComparison : uint8_t { SMALLER = 2, }; -//! A bignum magnitude is handled as base 2^32 digits -using digit_t = uint32_t; -using twodigit_t = uint64_t; - //! Per-vector scratch digit buffers and interrupt-check state for BIGNUM multiplication and division struct BignumArithmeticState { explicit BignumArithmeticState(optional_ptr context = nullptr) : context(context) { @@ -58,12 +55,14 @@ struct BignumArithmeticState { optional_ptr context; //! Digit operations performed since the last interrupt check idx_t work_since_interrupt_check = 0; - unsafe_vector lhs_digits; - unsafe_vector rhs_digits; - unsafe_vector result_digits; - unsafe_vector remainder_digits; - unsafe_vector normalized_dividend; - unsafe_vector normalized_divisor; + unsafe_vector lhs_digits; + unsafe_vector rhs_digits; + unsafe_vector result_digits; + //! Scratch digits of the Karatsuba multiplication, sized once per vector for the largest product so far + unsafe_vector karatsuba_scratch; + unsafe_vector remainder_digits; + unsafe_vector normalized_dividend; + unsafe_vector normalized_divisor; }; struct BignumIntermediate { @@ -92,10 +91,12 @@ struct BignumIntermediate { //! In case we have unnecessary extra 0's or 1's in our bignum we trim them static idx_t Trim(data_ptr_t data, uint32_t &size, bool is_negative); void Trim(); - //! Add a BignumIntermediate to another BignumIntermediate, equivalent of a += - void AddInPlace(ArenaAllocator &allocator, const BignumIntermediate &rhs); - //! Adds two BignumIntermediates and returns a string_t result, equivalent of a + - static string_t Add(StringHeap &heap, const BignumIntermediate &lhs, const BignumIntermediate &rhs); + //! Add a BignumIntermediate to another BignumIntermediate, equivalent of a += (or a -= with negate_rhs) + void AddInPlace(ArenaAllocator &allocator, const BignumIntermediate &rhs, bool negate_rhs = false); + //! Adds two BignumIntermediates and returns a string_t result, equivalent of a + (or a - with negate_rhs: the + //! right operand takes part with its sign flipped, without being modified or copied) + static string_t Add(StringHeap &heap, const BignumIntermediate &lhs, const BignumIntermediate &rhs, + bool negate_rhs = false); //! 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); diff --git a/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp b/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp new file mode 100644 index 000000000..84cb841a1 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp @@ -0,0 +1,283 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/bignum_limbs.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/bit_utils.hpp" +#include "duckdb/common/bswap.hpp" +#include "duckdb/common/typedefs.hpp" + +#include + +namespace duckdb { + +//! Helpers that treat the big-endian magnitude bytes of a BIGNUM blob as 64-bit limbs. The blob format itself is +//! untouched: limbs are loaded with memcpy (the string_t payload is unaligned) and byte swapped on little-endian hosts. +struct BignumLimb { + //! Bytes of a limb + static constexpr idx_t BYTES = sizeof(uint64_t); + + //! The multiplication, division and decimal conversion kernels handle a magnitude as base 2^64 digits with 128-bit + //! products where the compiler has a 128-bit integer type. MSVC and 32-bit targets have none and keep base 2^32 + //! digits with 64-bit products. +#if ((__GNUC__ >= 5) || defined(__clang__)) && defined(__SIZEOF_INT128__) + using digit_t = uint64_t; + __extension__ typedef unsigned __int128 twodigit_t; + + //! Returns the low 64 bits of a * b + add, and its high 64 bits in "high"; never overflows 128 bits + static inline uint64_t MultiplyAdd(uint64_t a, uint64_t b, uint64_t add, uint64_t &high) { + const twodigit_t product = static_cast(a) * b + add; + high = static_cast(product >> 64); + return static_cast(product); + } + + //! Divides high * 2^64 + low by a divisor larger than high, so that the quotient fits a digit; sets the remainder + static inline uint64_t DivRem(uint64_t high, uint64_t low, uint64_t divisor, uint64_t &remainder) { + D_ASSERT(high < divisor); +#ifdef _MSC_VER + // clang-cl has the 128-bit type but links no runtime support for dividing it + return DivRemPortable(high, low, divisor, remainder); +#else + const twodigit_t numerator = (static_cast(high) << 64) | low; + const auto quotient = static_cast(numerator / divisor); + remainder = static_cast(numerator - static_cast(quotient) * divisor); + return quotient; +#endif + } +#else + using digit_t = uint32_t; + using twodigit_t = uint64_t; + + //! Divides high * 2^32 + low by a divisor larger than high, so that the quotient fits a digit; sets the remainder + static inline uint32_t DivRem(uint32_t high, uint32_t low, uint32_t divisor, uint32_t &remainder) { + D_ASSERT(high < divisor); + const twodigit_t numerator = (static_cast(high) << 32) | low; + const auto quotient = static_cast(numerator / divisor); + remainder = static_cast(numerator - static_cast(quotient) * divisor); + return quotient; + } + + //! Returns the low 64 bits of a * b + add, and its high 64 bits in "high"; never overflows 128 bits + static inline uint64_t MultiplyAdd(uint64_t a, uint64_t b, uint64_t add, uint64_t &high) { + // portable 32-bit split + const uint64_t a_low = a & 0xFFFFFFFFULL; + const uint64_t a_high = a >> 32; + const uint64_t b_low = b & 0xFFFFFFFFULL; + const uint64_t b_high = b >> 32; + const uint64_t p0 = a_low * b_low; + const uint64_t p1 = a_low * b_high; + const uint64_t p2 = a_high * b_low; + const uint64_t p3 = a_high * b_high; + const uint64_t middle = (p0 >> 32) + (p1 & 0xFFFFFFFFULL) + (p2 & 0xFFFFFFFFULL); + uint64_t low = (p0 & 0xFFFFFFFFULL) | (middle << 32); + high = p3 + (p1 >> 32) + (p2 >> 32) + (middle >> 32); + low += add; + high += low < add ? 1 : 0; + return low; + } +#endif + + //! Bytes and bits of a multiplication / division digit + static constexpr idx_t DIGIT_BYTES = sizeof(digit_t); + static constexpr idx_t DIGIT_BITS = DIGIT_BYTES * 8; + + //! DivRem in two base 2^32 steps (Hacker's Delight divlu), for compilers without 128-bit division + static inline uint64_t DivRemPortable(uint64_t high, uint64_t low, uint64_t divisor, uint64_t &remainder) { + D_ASSERT(high < divisor); + constexpr uint64_t HALF_BASE = static_cast(1) << 32; + constexpr uint64_t HALF_MASK = HALF_BASE - 1; + // normalize so that the divisor has its top bit set; the quotient is unchanged, the remainder is scaled + const idx_t shift = LeadingZeros(divisor); + if (shift > 0) { + divisor <<= shift; + high = (high << shift) | (low >> (64 - shift)); + low <<= shift; + } + const uint64_t divisor_high = divisor >> 32; + const uint64_t divisor_low = divisor & HALF_MASK; + const uint64_t low_high = low >> 32; + const uint64_t low_low = low & HALF_MASK; + // the high half of the quotient: an estimate from the top halves that is corrected down until it is exact + uint64_t q_high = high / divisor_high; + uint64_t rhat = high - q_high * divisor_high; + while (q_high >= HALF_BASE || q_high * divisor_low > ((rhat << 32) | low_high)) { + q_high--; + rhat += divisor_high; + if (rhat >= HALF_BASE) { + break; + } + } + // the partial remainder is below the divisor, so the wrapping arithmetic yields the exact value + const uint64_t middle = (high << 32) + low_high - q_high * divisor; + uint64_t q_low = middle / divisor_high; + rhat = middle - q_low * divisor_high; + while (q_low >= HALF_BASE || q_low * divisor_low > ((rhat << 32) | low_low)) { + q_low--; + rhat += divisor_high; + if (rhat >= HALF_BASE) { + break; + } + } + remainder = ((middle << 32) + low_low - q_low * divisor) >> shift; + return (q_high << 32) | q_low; + } + + template + static inline T ToHostOrder(T value) { +#if DUCKDB_IS_BIG_ENDIAN + return value; +#else + return BSwap(value); +#endif + } + + //! Loads 8 big-endian bytes as an integer + static inline uint64_t LoadBE(const_data_ptr_t ptr) { + uint64_t value; + memcpy(&value, ptr, BYTES); + return ToHostOrder(value); + } + + //! Stores an integer as 8 big-endian bytes + static inline void StoreBE(data_ptr_t ptr, uint64_t value) { + value = ToHostOrder(value); + memcpy(ptr, &value, BYTES); + } + + //! Loads the count (1..8) big-endian bytes at ptr as an integer, i.e. a partial limb at the most significant end + static inline uint64_t LoadBEPartial(const_data_ptr_t ptr, idx_t count) { + D_ASSERT(count >= 1 && count <= BYTES); + if (count == BYTES) { + return LoadBE(ptr); + } + // fixed-size loads keep this free of variable-length memcpy calls + uint64_t value = 0; + if (count & 4) { + uint32_t part; + memcpy(&part, ptr, sizeof(part)); + value = ToHostOrder(part); + ptr += sizeof(part); + } + if (count & 2) { + uint16_t part; + memcpy(&part, ptr, sizeof(part)); + value = (value << 16) | ToHostOrder(part); + ptr += sizeof(part); + } + if (count & 1) { + value = (value << 8) | *ptr; + } + return value; + } + + //! Stores the low count (1..8) bytes of an integer as big-endian bytes at ptr + static inline void StoreBEPartial(data_ptr_t ptr, idx_t count, uint64_t value) { + D_ASSERT(count >= 1 && count <= BYTES); + if (count == BYTES) { + StoreBE(ptr, value); + return; + } + if (count & 4) { + const uint32_t part = ToHostOrder(static_cast(value >> (8 * (count - 4)))); + memcpy(ptr, &part, sizeof(part)); + ptr += sizeof(part); + } + if (count & 2) { + const uint16_t part = ToHostOrder(static_cast(value >> (8 * (count & 1)))); + memcpy(ptr, &part, sizeof(part)); + ptr += sizeof(part); + } + if (count & 1) { + *ptr = static_cast(value); + } + } + + //! Loads 8 magnitude bytes as a limb of the absolute value: the complement of a negative value is undone + static inline uint64_t LoadMagnitude(const_data_ptr_t ptr, bool is_negative) { + const uint64_t limb = LoadBE(ptr); + return is_negative ? ~limb : limb; + } + + //! Loads the count (1..8) most significant magnitude bytes of a value as a partial limb of the absolute value + static inline uint64_t LoadMagnitudePartial(const_data_ptr_t ptr, idx_t count, bool is_negative) { + const uint64_t limb = LoadBEPartial(ptr, count); + if (!is_negative) { + return limb; + } + return ~limb & (~uint64_t(0) >> (64 - 8 * count)); + } + + //! Stores a limb of the absolute value as 8 magnitude bytes, complemented for a negative value + static inline void StoreMagnitude(data_ptr_t ptr, uint64_t value, bool is_negative) { + StoreBE(ptr, is_negative ? ~value : value); + } + + //! Stores the low count (1..8) bytes of a limb of the absolute value as magnitude bytes, complemented for a + //! negative value + static inline void StoreMagnitudePartial(data_ptr_t ptr, idx_t count, uint64_t value, bool is_negative) { + StoreBEPartial(ptr, count, is_negative ? ~value : value); + } + + //! Loads the 8 magnitude bytes ending just before end_idx as one limb holding the absolute value: bytes before + //! the start of the value read as zero, bytes of a negative value are complemented + static inline uint64_t LoadAbsolute(const_data_ptr_t data, bool is_negative, int64_t end_idx) { + if (end_idx <= 0) { + return 0; + } + if (end_idx >= static_cast(BYTES)) { + return LoadMagnitude(data + end_idx - BYTES, is_negative); + } + // a partial limb at the most significant end of the value: only the low end_idx bytes are real + return LoadMagnitudePartial(data, static_cast(end_idx), is_negative); + } + + //! The number of leading zero bits of a non-zero limb + static inline idx_t LeadingZeros(uint64_t value) { + D_ASSERT(value != 0); +#if defined(__GNUC__) || defined(__clang__) + return static_cast(__builtin_clzll(value)); +#else + return CountZeros::Leading(value); +#endif + } + static inline idx_t LeadingZeros(uint32_t value) { + D_ASSERT(value != 0); + return CountZeros::Leading(value); + } + + //! The number of bytes needed to hold a magnitude, at least one + static inline idx_t ByteCount(uint64_t magnitude) { + if (magnitude == 0) { + return 1; + } + return (64 - LeadingZeros(magnitude) + 7) / 8; + } + + //! The number of bytes needed to hold a two-limb magnitude, at least one + static inline idx_t ByteCount(uint64_t hi, uint64_t lo) { + return hi ? BYTES + ByteCount(hi) : ByteCount(lo); + } + + //! Writes a two-limb magnitude as byte_count (1..16, see ByteCount) big-endian BIGNUM data bytes, complemented + //! for a negative value + static inline void StoreMagnitude(data_ptr_t out, idx_t byte_count, uint64_t hi, uint64_t lo, bool is_negative) { + D_ASSERT(byte_count >= 1 && byte_count <= 2 * BYTES); + if (byte_count > BYTES) { + StoreMagnitudePartial(out, byte_count - BYTES, hi, is_negative); + StoreMagnitude(out + byte_count - BYTES, lo, is_negative); + } else { + StoreMagnitudePartial(out, byte_count, lo, is_negative); + } + } +}; + +//! Base 2^64 (or 2^32, see BignumLimb) digits of the BIGNUM multiplication and division kernels +using bignum_digit_t = BignumLimb::digit_t; +using bignum_twodigit_t = BignumLimb::twodigit_t; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/bind_helpers.hpp b/src/duckdb/src/include/duckdb/common/bind_helpers.hpp index ce9c063be..d1aad7bf0 100644 --- a/src/duckdb/src/include/duckdb/common/bind_helpers.hpp +++ b/src/duckdb/src/include/duckdb/common/bind_helpers.hpp @@ -13,6 +13,8 @@ namespace duckdb { +class ClientContext; +class Context; class Value; struct BoundOrderByNode; struct BoundStatement; @@ -22,7 +24,7 @@ struct TableIndex; class Binder; Value ConvertVectorToValue(vector set); -idx_t ParseBytesArg(const Identifier &name, const Value &arg); +idx_t ParseBytesArg(Context &context, const Identifier &name, const Value &arg); vector ParseColumnList(const vector &set, const vector &names, const Identifier &option_name); vector ParseColumnList(const Value &value, const vector &names, const Identifier &option_name); vector ParseColumnsOrdered(const vector &set, const vector &names, diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp index 5985047ed..1906d26aa 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp @@ -238,7 +238,7 @@ class MultiFileFunction : public TableFunction { result->table_columns = IdentifiersToStrings(names); } result->columns = MultiFileColumnDefinition::ColumnsFromNamesAndTypes(result->names, result->types); - result->file_options.VerifyColumnStatistics(result->names, result->types); + result->file_options.VerifyColumnStatistics(context.GetContext(), result->names, result->types); return std::move(result); } @@ -311,7 +311,7 @@ class MultiFileFunction : public TableFunction { file_options.auto_detect_hive_partitioning = false; for (auto &[option_name, option_values] : input.info.options) { - if (multi_file_reader->ParseCopyOption(option_name, option_values, file_options)) { + if (multi_file_reader->ParseCopyOption(context.GetContext(), option_name, option_values, file_options)) { continue; } if (interface->ParseCopyOption(context, option_name, option_values, *options, expected_names, @@ -1154,10 +1154,8 @@ class MultiFileFunction : public TableFunction { auto &column_index = input.column_index; optional_ptr file = bind_data.union_readers.empty() ? nullptr : bind_data.union_readers[0].get(); - if (!file && !bind_data.initial_reader) { - return nullptr; - } - // scanning single file and we have the metadata read already + // a scan whose schema was given opens no file at bind - the column_statistics option below still applies + const bool opened_a_file = file || bind_data.initial_reader; if (column_index.IsVirtualColumn()) { return nullptr; } @@ -1167,7 +1165,7 @@ class MultiFileFunction : public TableFunction { auto &file_row_number_idx = bind_data.reader_bind.file_row_number_idx; if (file_row_number_idx.IsValid() && file_row_number_idx.GetIndex() == primary_index) { // the column is read from the row number virtual column of the reader - if (bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES) { + if (!opened_a_file || bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES) { return nullptr; } return bind_data.initial_reader @@ -1187,7 +1185,8 @@ class MultiFileFunction : public TableFunction { // statistics the caller gave for the column (the "column_statistics" option) stand in for the files' - // they describe the scan as a whole, which is what the optimizer asks about, where a file's describe one file if (!bind_data.file_options.column_statistics.IsNull()) { - auto explicit_stats = bind_data.file_options.GetColumnStatistics(col_name, bind_data.types[primary_index]); + auto explicit_stats = bind_data.file_options.GetColumnStatistics(context.GetContext(), col_name, + bind_data.types[primary_index]); if (explicit_stats) { if (!column_index.IsPushdownExtract()) { return explicit_stats; @@ -1201,6 +1200,9 @@ class MultiFileFunction : public TableFunction { // A physical shadow's bounds do not describe the generated path. Explicit scan statistics above still do. return nullptr; } + if (!opened_a_file) { + return nullptr; + } // NOTE: we do not want to parse the file metadata for the sole purpose of getting column statistics const bool multiple_files = bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES; // multiple files: only if every file was opened at bind (union_by_name, maximum_sample_files or diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp index 1cf970bc1..613c7040b 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_options.hpp @@ -87,18 +87,19 @@ struct MultiFileOptions { //! Validate owned declarations before binding or restoring even an empty file list. DUCKDB_API void ValidateBoundSchema() const; //! Set "column_statistics" from an option value - see column_statistics for its shape - DUCKDB_API void SetColumnStatistics(const Identifier &key, const Value &val); + DUCKDB_API void SetColumnStatistics(Context &context, const Identifier &key, const Value &val); //! Check "column_statistics" against the scan's columns once they are bound: every key must name a column, or a //! part of one, and every value must parse for it. Errors here, at bind, rather than when the optimizer asks. - DUCKDB_API void VerifyColumnStatistics(const vector &names, const vector &types) const; + DUCKDB_API void VerifyColumnStatistics(Context &context, const vector &names, + const vector &types) const; //! The statistics the "column_statistics" option gives for a column of the given type, or nullptr when it says //! nothing about it. The bounds are cast to the column's type; a value that does not cast is an error. - DUCKDB_API unique_ptr GetColumnStatistics(const Identifier &column_name, + DUCKDB_API unique_ptr GetColumnStatistics(Context &context, const Identifier &column_name, const LogicalType &type) const; //! Set "maximum_sample_files" from an option value - a positive count, or -1 for all files - DUCKDB_API void SetMaximumSampleFiles(const Identifier &key, const Value &val); + DUCKDB_API void SetMaximumSampleFiles(Context &context, const Identifier &key, const Value &val); //! Set "maximum_sample_files" from an option value, returning false if it is not a valid count - DUCKDB_API bool TrySetMaximumSampleFiles(const Value &val); + DUCKDB_API bool TrySetMaximumSampleFiles(Context &context, const Value &val); //! Whether the global schema is a union of the schemas of several files - individual files are then allowed to //! be missing columns that are present in the global schema bool SchemaIsUnion() const { diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp index cc6b12971..345831e17 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp @@ -148,7 +148,7 @@ struct MultiFileReader { //! Parse the named parameters of a multi-file reader //! Parse an option of a COPY ... FROM that the multi-file reader handles itself - DUCKDB_API virtual bool ParseCopyOption(const Identifier &key, const vector &values, + DUCKDB_API virtual bool ParseCopyOption(Context &context, const Identifier &key, const vector &values, MultiFileOptions &options); DUCKDB_API virtual bool ParseOption(const Identifier &key, const Value &val, MultiFileOptions &options, ClientContext &context); diff --git a/src/duckdb/src/include/duckdb/common/types/bignum.hpp b/src/duckdb/src/include/duckdb/common/types/bignum.hpp index 2982714b0..fe619193f 100644 --- a/src/duckdb/src/include/duckdb/common/types/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/types/bignum.hpp @@ -15,12 +15,24 @@ #include "duckdb/common/winapi.hpp" #include "duckdb/common/vector/string_vector.hpp" #include "duckdb/common/bignum.hpp" +#include "duckdb/common/bignum_limbs.hpp" +#include "duckdb/common/vector.hpp" namespace duckdb { struct BoundCastInfo; struct CastParameters; +//! Scratch space of the VARCHAR <-> BIGNUM conversions, reused across the values of a vector +struct BignumCastScratch { + //! 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; +}; + //! The Bignum class is a static class that holds helper functions for the Bignum type. class Bignum { public: @@ -29,14 +41,10 @@ class Bignum { DUCKDB_API static constexpr uint32_t MAX_DATA_SIZE = 8388607; //! Header size of a Bignum is always 3 bytes. DUCKDB_API static constexpr uint8_t BIGNUM_HEADER_SIZE = 3; - //! Max(e such that 10**e fits in a digit_t) - DUCKDB_API static constexpr uint8_t DECIMAL_SHIFT = 9; + //! Max(e such that 10**e fits in a 64-bit limb): the decimal conversions use limbs of DECIMAL_SHIFT digits + DUCKDB_API static constexpr uint8_t DECIMAL_SHIFT = 19; //! 10 ** DECIMAL_SHIFT - DUCKDB_API static constexpr digit_t DECIMAL_BASE = 1000000000; - //! Bytes of a digit_t - DUCKDB_API static constexpr uint8_t DIGIT_BYTES = sizeof(digit_t); - //! Bits of a digit_t - DUCKDB_API static constexpr uint8_t DIGIT_BITS = DIGIT_BYTES * 8; + DUCKDB_API static constexpr uint64_t DECIMAL_BASE = 10000000000000000000ULL; //! Verifies if a Bignum is valid. i.e., if it has 3 header bytes. The header correctly represents the number of //! data bytes, and the data bytes has no leading zero bytes. DUCKDB_API static void Verify(const bignum_t &input); @@ -62,6 +70,11 @@ class Bignum { //! Encodes a VARCHAR into a BIGNUM blob, applying decimal rounding if requested. 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); + //! 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); + //! The VARCHAR -> BIGNUM cast function + DUCKDB_API static bool VarcharToBignumCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters); //! Converts a char to a Digit DUCKDB_API static int CharToDigit(char c); //! Converts a Digit to a char @@ -72,55 +85,117 @@ class Bignum { 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); + //! 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); //! ----------------------------------- Double Cast ----------------------------------- // DUCKDB_API static bool BignumToDouble(const bignum_t &blob, double &result, bool &strict); [[noreturn]] DUCKDB_API static void ThrowInvalidBlobSize(idx_t size); + //! Converts a BIGNUM into an integer type, returns false if the value is out of range template static bool BignumToInt(const bignum_t &blob, T &result, bool &strict) { - if (blob.data.GetSize() < BIGNUM_HEADER_SIZE + 1) { - ThrowInvalidBlobSize(blob.data.GetSize()); + const idx_t blob_size = blob.data.GetSize(); + if (blob_size < BIGNUM_HEADER_SIZE + 1) { + ThrowInvalidBlobSize(blob_size); } - auto data_byte_size = blob.data.GetSize() - BIGNUM_HEADER_SIZE; - auto data = blob.data.GetData(); - bool is_negative = (data[0] & 0x80) == 0; - - uhugeint_t abs_value = 0; - for (idx_t i = 0; i < data_byte_size; ++i) { - uint8_t byte = static_cast(data[Bignum::BIGNUM_HEADER_SIZE + i]); - if (is_negative) { - byte = static_cast(~byte); - } - if (abs_value > (NumericLimits::Maximum() >> 8)) { - // the absolute value does not fit in 128 bits - return false; + auto data = const_data_ptr_cast(blob.data.GetData()); + const bool is_negative = (data[0] & 0x80) == 0; + auto magnitude = data + BIGNUM_HEADER_SIZE; + idx_t data_byte_size = blob_size - BIGNUM_HEADER_SIZE; + if (data_byte_size > 2 * BignumLimb::BYTES) { + // a well-formed BIGNUM carries no leading zero bytes, so this never fits a 128-bit integer; we tolerate + // leading zero bytes anyway (0xFF under the complement of a negative value) + const data_t zero = is_negative ? 0xFF : 0; + for (; data_byte_size > 2 * BignumLimb::BYTES; data_byte_size--, magnitude++) { + if (*magnitude != zero) { + return false; + } } - abs_value = (abs_value << 8) | byte; } + // load the magnitude as two 64-bit limbs + uint64_t upper = 0; + uint64_t lower; + if (data_byte_size > BignumLimb::BYTES) { + upper = BignumLimb::LoadMagnitudePartial(magnitude, data_byte_size - BignumLimb::BYTES, is_negative); + lower = BignumLimb::LoadMagnitude(magnitude + data_byte_size - BignumLimb::BYTES, is_negative); + } else { + lower = BignumLimb::LoadMagnitudePartial(magnitude, data_byte_size, is_negative); + } + return BignumCastFromMagnitude(upper, lower, is_negative, result); + } - const auto max_value = static_cast(NumericLimits::Maximum()); - if (!is_negative || abs_value == 0) { - if (abs_value > max_value) { + //! Converts a 128-bit magnitude and a sign into an integer type, returns false if the value is out of range + template + static bool BignumCastFromMagnitude(uint64_t upper, uint64_t lower, bool is_negative, T &result) { + if (upper == 0 && lower == 0) { + result = 0; + return true; + } + if (upper != 0) { + return false; + } + if (is_negative) { + if (!NumericLimits::IsSigned()) { + return false; + } + // the magnitude may be one larger than the maximum + const uint64_t limit = static_cast(NumericLimits::Maximum()) + 1; + if (lower > limit) { return false; } - result = static_cast(abs_value); + if (lower == limit) { + result = NumericLimits::Minimum(); + return true; + } + result = static_cast(-static_cast(lower)); return true; } - if (!NumericLimits::IsSigned()) { + if (lower > static_cast(NumericLimits::Maximum())) { return false; } - if (abs_value > max_value + 1) { + result = static_cast(lower); + return true; + } +}; + +template <> +inline bool Bignum::BignumCastFromMagnitude(uint64_t upper, uint64_t lower, bool is_negative, hugeint_t &result) { + constexpr uint64_t SIGN_BIT = static_cast(1) << 63; + if (upper == 0 && lower == 0) { + result = hugeint_t(0); + return true; + } + if (is_negative) { + if (upper > SIGN_BIT || (upper == SIGN_BIT && lower != 0)) { return false; } - if (abs_value == max_value + 1) { - result = NumericLimits::Minimum(); + if (upper == SIGN_BIT) { + result = NumericLimits::Minimum(); return true; } - result = static_cast(-static_cast(abs_value)); + // two's complement of the magnitude + result.lower = ~lower + 1; + result.upper = static_cast(~upper + (lower == 0 ? 1 : 0)); return true; } -}; + if (upper >= SIGN_BIT) { + return false; + } + result = hugeint_t(static_cast(upper), lower); + return true; +} + +template <> +inline bool Bignum::BignumCastFromMagnitude(uint64_t upper, uint64_t lower, bool is_negative, uhugeint_t &result) { + if (is_negative && (upper != 0 || lower != 0)) { + return false; + } + result = uhugeint_t(upper, lower); + return true; +} //! ----------------------------------- (u)Integral Cast ----------------------------------- // struct IntCastToBignum { diff --git a/src/duckdb/src/include/duckdb/common/types/value.hpp b/src/duckdb/src/include/duckdb/common/types/value.hpp index b389dcaa1..bb837459f 100644 --- a/src/duckdb/src/include/duckdb/common/types/value.hpp +++ b/src/duckdb/src/include/duckdb/common/types/value.hpp @@ -26,6 +26,7 @@ namespace duckdb { +class Context; class String; class CastFunctionSet; struct GetCastFunctionInput; @@ -264,6 +265,7 @@ class Value { DUCKDB_API Value CastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type, bool strict = false) const; DUCKDB_API Value CastAs(ClientContext &context, const LogicalType &target_type, bool strict = false) const; + DUCKDB_API Value CastAs(Context &context, const LogicalType &target_type, bool strict = false) const; DUCKDB_API Value DefaultCastAs(const LogicalType &target_type, bool strict = false) const; //! Tries to cast this value to another type - returns the result, or nullopt if the cast is not possible. //! Never throws on a failed cast; pass "error_message" to obtain the reason for the failure @@ -272,6 +274,8 @@ class Value { bool strict = false) const; DUCKDB_API optional TryCastAs(ClientContext &context, const LogicalType &target_type, string *error_message = nullptr, bool strict = false) const; + DUCKDB_API optional TryCastAs(Context &context, const LogicalType &target_type, + string *error_message = nullptr, bool strict = false) const; DUCKDB_API optional DefaultTryCastAs(const LogicalType &target_type, string *error_message = nullptr, bool strict = false) const; diff --git a/src/duckdb/src/include/duckdb/common/vector_operations/vector_operations.hpp b/src/duckdb/src/include/duckdb/common/vector_operations/vector_operations.hpp index 5a55ff32a..882678e88 100644 --- a/src/duckdb/src/include/duckdb/common/vector_operations/vector_operations.hpp +++ b/src/duckdb/src/include/duckdb/common/vector_operations/vector_operations.hpp @@ -15,6 +15,7 @@ namespace duckdb { class CastFunctionSet; struct GetCastFunctionInput; +class Context; // VectorOperations contains a set of operations that operate on sets of // vectors. In general, the operators must all have the same type, otherwise an @@ -193,6 +194,9 @@ struct VectorOperations { //! Cast the data from the source type to the target type. Throws an exception if the cast fails. DUCKDB_API static void Cast(ClientContext &context, Vector &source, Vector &result, idx_t count, bool strict = false); + DUCKDB_API static bool TryCast(Context &context, Vector &source, Vector &result, idx_t count, string *error_message, + bool strict = false, const bool nullify_parent = false); + DUCKDB_API static void Cast(Context &context, Vector &source, Vector &result, idx_t count, bool strict = false); DUCKDB_API static void DefaultCast(Vector &source, Vector &result, idx_t count, bool strict = false); // Copy the data of to the target vector diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp index 17913041e..292e83028 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/base_scanner.hpp @@ -15,6 +15,13 @@ #include "duckdb/common/helper.hpp" #include "duckdb/execution/operator/csv_scanner/csv_byte_skipper.hpp" +// the block scan loop's speed depends on where its code starts within a 64 byte line, so the function is aligned +#if defined(__GNUC__) +#define DUCKDB_BLOCK_SCAN_ALIGNED __attribute__((aligned(64))) +#else +#define DUCKDB_BLOCK_SCAN_ALIGNED +#endif + namespace duckdb { class CSVFileScan; @@ -207,16 +214,381 @@ class BaseScanner { //! Skips the content bytes of the current buffer, mutable because the line finder is const mutable CSVByteSkipper skipper; + //! Whether ProcessBlocks may drive this state machine, and the bytes it stops at + const bool block_scan; + const uint8_t block_delimiter; + const string block_delimiter_bytes; + const bool block_multi_byte_delimiter; + const uint8_t block_quote; + const bool block_crlf; + const bool block_cr; + const bool block_escape_is_quote; + const uint8_t block_comment; + + //! Whether the state machine can hand the current byte to ProcessBlocks + template + bool BlockScanPossible(const T &result) const { + if (result.quoted || result.escaped || result.comment) { + return false; + } + switch (states.states[1]) { + case CSVState::STANDARD: + case CSVState::DELIMITER: + case CSVState::RECORD_SEPARATOR: + case CSVState::EMPTY_SPACE: + case CSVState::NOT_SET: + return true; + default: + return false; + } + } + + static bool IsSeparatorState(const CSVState state) { + return state == CSVState::DELIMITER || state == CSVState::RECORD_SEPARATOR || + state == CSVState::CARRIAGE_RETURN || state == CSVState::NOT_SET; + } + + //! The state after the data bytes [from, to) given the state `before` them, as the eligible tables have it + CSVState StateAfterData(const CSVState before, const idx_t from, const idx_t to) const { + if (from == to) { + return before; + } + if (to - from == 1 && buffer_handle_ptr[from] == ' ' && IsSeparatorState(before)) { + return CSVState::EMPTY_SPACE; + } + return CSVState::STANDARD; + } + + //! Moves `states` from the pair before byte `last` to the pair before byte `at`, over data bytes + void SetStatesBefore(const idx_t at, const idx_t last) { + const auto before = states.states[1]; + const auto previous = at == last ? states.states[0] : StateAfterData(before, last, at - 1); + D_ASSERT(ReplayStates(last, at).states[1] == StateAfterData(before, last, at)); + D_ASSERT(ReplayStates(last, at).states[0] == previous); + states.states[1] = StateAfterData(before, last, at); + states.states[0] = previous; + } + + //! The pair the state machine reaches from `states` over the bytes [from, to), for the block scan assertions + CSVStates ReplayStates(const idx_t from, const idx_t to) const { + CSVStates replay = states; + for (idx_t i = from; i < to; i++) { + state_machine->Transition(replay, buffer_handle_ptr[i]); + } + return replay; + } + + //! Moves `states` from the pair before byte `last` to the pair before byte `at`, over quoted data bytes + void SetQuotedStatesBefore(const idx_t at, const idx_t last) { + const auto previous = at == last ? states.states[0] : at == last + 1 ? states.states[1] : CSVState::QUOTED; + D_ASSERT(ReplayStates(last, at).states[0] == previous); + D_ASSERT(ReplayStates(last, at).states[1] == (at == last ? states.states[1] : CSVState::QUOTED)); + states.states[1] = at == last ? states.states[1] : CSVState::QUOTED; + states.states[0] = previous; + } + + //! Leaves the block scan inside a comment at `at`, `before` is the state before the comment byte at `last - 1` + bool HandOverComment(const idx_t at, const idx_t last, const CSVState before) { + const auto previous = at == last ? before : CSVState::COMMENT; + D_ASSERT(ReplayStates(last, at).states[0] == previous); + D_ASSERT(ReplayStates(last, at).states[1] == CSVState::COMMENT); + states.states[0] = previous; + states.states[1] = CSVState::COMMENT; + iterator.pos.buffer_pos = at; + return false; + } + + //! Leaves the block scan inside a quoted value at `at` + bool HandOverQuoted(const idx_t at, const idx_t last) { + SetQuotedStatesBefore(at, last); + iterator.pos.buffer_pos = at; + return false; + } + + //! The bytes that end a row at `at`, 2 for a CRLF pair that fits before `limit`, 1 for a line feed, else 0 + idx_t RowEndBytes(const uint8_t byte, const idx_t at, const idx_t limit) const { + if (block_crlf) { + return byte == '\r' && at + 1 < limit && buffer_handle_ptr[at + 1] == '\n' ? 2 : 0; + } + if (block_cr) { + return byte == '\r' ? 1 : 0; + } + return byte == '\n' ? 1 : 0; + } + + //! The bytes of the whole multi byte delimiter when it starts at `at` and ends before `limit`, 0 when only part of + //! it is there. No loop here, a loop would be vectorized into the block scan and slow it down for every dialect + idx_t DelimiterBytes(const idx_t at, const idx_t limit) const { + const idx_t size = block_delimiter_bytes.size(); + if (at + size > limit || memcmp(buffer_handle_ptr + at + 1, block_delimiter_bytes.data() + 1, size - 1) != 0) { + return 0; + } + return size; + } + + //! The state before the last byte of a multi byte delimiter + CSVState DelimiterPenultimateState() const { + switch (block_delimiter_bytes.size()) { + case 2: + return CSVState::DELIMITER_FIRST_BYTE; + case 3: + return CSVState::DELIMITER_SECOND_BYTE; + default: + return CSVState::DELIMITER_THIRD_BYTE; + } + } + + //! Clears the candidate bits of the bytes [from, to) of the block starting at `pos`, fewer than 64 of them + static void ClearCandidates(uint64_t &candidates, const idx_t pos, const idx_t from, const idx_t to) { + candidates &= ~(((uint64_t(1) << (to - from)) - 1) << (from - pos)); + } + + //! The delimiter at `at`, `before` is the state before it + template + void BlockDelimiter(T &result, const idx_t at, const CSVState before) { + states.states[0] = before; + states.states[1] = CSVState::DELIMITER; + iterator.pos.buffer_pos = at; + T::AddValue(result, at); + } + + //! The row end at `at`, `before` is the state before it. Returns true when the result is full + template + bool BlockRowEnd(T &result, const idx_t at, const CSVState before, const bool crlf, uint64_t &candidates, + const idx_t pos) { + states.states[0] = before; + states.states[1] = crlf ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR; + iterator.pos.buffer_pos = at; + const bool full = T::AddRow(result, at); + lines_read++; + if (full) { + iterator.pos.buffer_pos = at + 1; + return true; + } + if (crlf) { + states.states[0] = CSVState::CARRIAGE_RETURN; + states.states[1] = CSVState::RECORD_SEPARATOR; + candidates &= ~(uint64_t(1) << (at + 1 - pos)); + } + return false; + } + + //! The row end at `at` closes a comment, as the byte loop's record separator case does. Returns true when the + //! result is full + template + bool BlockCommentEnd(T &result, const idx_t at, const bool crlf, uint64_t &candidates, const idx_t pos) { + states.states[0] = CSVState::COMMENT; + states.states[1] = crlf ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR; + iterator.pos.buffer_pos = at; + const bool full = T::UnsetComment(result, at); + lines_read++; + if (full) { + iterator.pos.buffer_pos = at + 1; + return true; + } + if (crlf) { + states.states[0] = CSVState::CARRIAGE_RETURN; + states.states[1] = CSVState::RECORD_SEPARATOR; + candidates &= ~(uint64_t(1) << (at + 1 - pos)); + } + return false; + } + + //! Scans unquoted fields and quoted values in their canonical form, and preserves the states when handing back + //! to Process. Returns true when the result is full. Repeated SetQuoted calls may be skipped because the setter + //! is idempotent. MULTI_BYTE_DELIMITER and COMMENT are the dialect's, so dialects without them pay nothing for them + template + DUCKDB_BLOCK_SCAN_ALIGNED bool ProcessBlocks(T &result, const idx_t to_pos) { + const auto buffer = buffer_handle_ptr; + // the first byte not consumed, and the first byte after the last structural or special byte + idx_t pos = iterator.pos.buffer_pos; + idx_t last = pos; + bool quoted = false; + // inside a comment only a row end matters, `comment_before` is the state before the comment byte + bool comment = false; + CSVState comment_before = CSVState::NOT_SET; + uint64_t candidates; + idx_t block_end; + while (pos < to_pos && skipper.BlockCandidates(pos, candidates, block_end)) { + const idx_t limit = MinValue(block_end, to_pos); + while (candidates) { + const idx_t at = pos + CountZeros::Trailing(candidates); + if (at >= limit) { + break; + } + candidates &= candidates - 1; + const auto byte = static_cast(buffer[at]); + if (COMMENT && comment) { + const idx_t row_end_bytes = RowEndBytes(byte, at, limit); + if (row_end_bytes == 0) { + if (byte == '\n' || byte == '\r') { + return HandOverComment(at, last, comment_before); + } + continue; + } + D_ASSERT(ReplayStates(last, at + 1).states[0] == CSVState::COMMENT); + D_ASSERT(ReplayStates(last, at + 1).states[1] == + (row_end_bytes == 2 ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR)); + if (BlockCommentEnd(result, at, row_end_bytes == 2, candidates, pos)) { + return true; + } + comment = false; + last = at + row_end_bytes; + continue; + } + if (quoted) { + if (byte == '\n' || byte == '\r') { + // QUOTED and QUOTED_NEW_LINE alternate on newline bytes inside the quotes + SetQuotedStatesBefore(at, last); + const bool new_line_state = states.states[1] == CSVState::QUOTED; + states.states[0] = states.states[1]; + states.states[1] = new_line_state ? CSVState::QUOTED_NEW_LINE : CSVState::QUOTED; + iterator.pos.buffer_pos = at; + if (new_line_state) { + T::QuotedNewLine(result); + } else { + ever_quoted = true; + T::SetQuoted(result, at); + } + last = at + 1; + continue; + } + if (byte != block_quote) { + continue; + } + if (at + 1 >= limit) { + return HandOverQuoted(at, last); + } + const auto next = static_cast(buffer[at + 1]); + const bool escape_pair = block_escape_is_quote && next == block_quote; + const idx_t delimiter_bytes = next != block_delimiter ? 0 + : MULTI_BYTE_DELIMITER ? DelimiterBytes(at + 1, limit) + : 1; + const idx_t row_end_bytes = RowEndBytes(next, at + 1, limit); + if (!escape_pair && delimiter_bytes == 0 && row_end_bytes == 0) { + return HandOverQuoted(at, last); + } + SetQuotedStatesBefore(at, last); + states.states[0] = states.states[1]; + states.states[1] = CSVState::UNQUOTED; + iterator.pos.buffer_pos = at; + T::SetUnquoted(result); + candidates &= ~(uint64_t(1) << (at + 1 - pos)); + if (escape_pair) { + states.states[0] = CSVState::UNQUOTED; + states.states[1] = CSVState::QUOTED; + iterator.pos.buffer_pos = at + 1; + ever_escaped = true; + T::SetEscaped(result); + ever_quoted = true; + T::SetQuoted(result, at + 1); + last = at + 2; + continue; + } + quoted = false; + if (delimiter_bytes != 0) { + if (MULTI_BYTE_DELIMITER) { + ClearCandidates(candidates, pos, at + 2, at + 1 + delimiter_bytes); + } + BlockDelimiter(result, at + delimiter_bytes, + MULTI_BYTE_DELIMITER ? DelimiterPenultimateState() : CSVState::UNQUOTED); + last = at + 1 + delimiter_bytes; + continue; + } + if (BlockRowEnd(result, at + 1, CSVState::UNQUOTED, row_end_bytes == 2, candidates, pos)) { + return true; + } + last = at + 1 + row_end_bytes; + continue; + } + const auto before = StateAfterData(states.states[1], last, at); + if (byte == block_delimiter) { + if (MULTI_BYTE_DELIMITER) { + const idx_t delimiter_bytes = DelimiterBytes(at, limit); + if (delimiter_bytes == 0) { + // part of a multi byte delimiter, the byte loop walks the delimiter byte states + return HandOver(at, last); + } + D_ASSERT(ReplayStates(last, at + delimiter_bytes).states[1] == CSVState::DELIMITER); + D_ASSERT(ReplayStates(last, at + delimiter_bytes).states[0] == DelimiterPenultimateState()); + ClearCandidates(candidates, pos, at + 1, at + delimiter_bytes); + BlockDelimiter(result, at + delimiter_bytes - 1, DelimiterPenultimateState()); + last = at + delimiter_bytes; + continue; + } + D_ASSERT(ReplayStates(last, at + 1).states[1] == CSVState::DELIMITER); + D_ASSERT(ReplayStates(last, at + 1).states[0] == before); + BlockDelimiter(result, at, before); + last = at + 1; + continue; + } + if (COMMENT && byte == block_comment) { + D_ASSERT(ReplayStates(last, at + 1).states[1] == CSVState::COMMENT); + D_ASSERT(ReplayStates(last, at + 1).states[0] == before); + states.states[0] = before; + states.states[1] = CSVState::COMMENT; + iterator.pos.buffer_pos = at; + T::SetComment(result, at); + comment = true; + comment_before = before; + last = at + 1; + continue; + } + if (block_quote != '\0' && byte == block_quote) { + if (before == CSVState::STANDARD) { + // a quote inside an unquoted value is data + continue; + } + D_ASSERT(ReplayStates(last, at + 1).states[1] == CSVState::QUOTED); + states.states[0] = before; + states.states[1] = CSVState::QUOTED; + iterator.pos.buffer_pos = at; + ever_quoted = true; + T::SetQuoted(result, at); + quoted = true; + last = at + 1; + continue; + } + const idx_t row_end_bytes = RowEndBytes(byte, at, limit); + if (row_end_bytes == 0) { + if (byte == '\n' || byte == '\r') { + return HandOver(at, last); + } + // a false candidate of the mask, data + continue; + } + if (before == CSVState::RECORD_SEPARATOR || before == CSVState::NOT_SET) { + // an empty line + return HandOver(at, last); + } + D_ASSERT(ReplayStates(last, at + 1).states[0] == before); + D_ASSERT(ReplayStates(last, at + 1).states[1] == + (row_end_bytes == 2 ? CSVState::CARRIAGE_RETURN : CSVState::RECORD_SEPARATOR)); + if (BlockRowEnd(result, at, before, row_end_bytes == 2, candidates, pos)) { + return true; + } + last = at + row_end_bytes; + } + pos = limit; + } + if (COMMENT && comment) { + return HandOverComment(pos, last, comment_before); + } + return quoted ? HandOverQuoted(pos, last) : HandOver(pos, last); + } + + //! Leaves the block scan at `at`, with the states before it + bool HandOver(const idx_t at, const idx_t last) { + SetStatesBefore(at, last); + iterator.pos.buffer_pos = at; + return false; + } + //! Process one chunk template void Process(T &result) { idx_t to_pos; const bool has_escaped_value = state_machine->dialect_options.state_machine_options.escape != '\0'; - const bool only_rn_newlines = - state_machine->state_machine_options.strict_mode.GetValue() && - state_machine->state_machine_options.strict_mode.IsSetByUser() && - state_machine->state_machine_options.new_line.GetValue() == NewLineIdentifier::CARRY_ON && - state_machine->state_machine_options.new_line.IsSetByUser(); const idx_t start_pos = iterator.pos.buffer_pos; if (iterator.IsBoundarySet()) { to_pos = iterator.GetEndPos(); @@ -228,6 +600,20 @@ class BaseScanner { } skipper.SetBuffer(*cur_buffer_handle); while (iterator.pos.buffer_pos < to_pos) { + if (T::BLOCK_SCAN && block_scan && BlockScanPossible(result)) { + const bool full = block_comment != '\0' + ? (block_multi_byte_delimiter ? ProcessBlocks(result, to_pos) + : ProcessBlocks(result, to_pos)) + : (block_multi_byte_delimiter ? ProcessBlocks(result, to_pos) + : ProcessBlocks(result, to_pos)); + if (full) { + bytes_read = iterator.pos.buffer_pos - start_pos; + return; + } + if (iterator.pos.buffer_pos >= to_pos) { + break; + } + } state_machine->Transition(states, buffer_handle_ptr[iterator.pos.buffer_pos]); switch (states.states[1]) { case CSVState::INVALID: @@ -281,7 +667,7 @@ class BaseScanner { lines_read++; return; } - } else if (!only_rn_newlines) { + } else { if (T::AddRow(result, iterator.pos.buffer_pos)) { iterator.pos.buffer_pos++; bytes_read = iterator.pos.buffer_pos - start_pos; @@ -380,3 +766,5 @@ class BaseScanner { }; } // namespace duckdb + +#undef DUCKDB_BLOCK_SCAN_ALIGNED diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/column_count_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/column_count_scanner.hpp index c2b6de9ae..a09fcd0d6 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/column_count_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/column_count_scanner.hpp @@ -33,6 +33,8 @@ struct ColumnCount { class ColumnCountResult : public ScannerResult { public: + static constexpr bool BLOCK_SCAN = false; + ColumnCountResult(CSVStates &states, CSVStateMachine &state_machine, idx_t result_size, CSVErrorHandler &error_handler); inline ColumnCount &operator[](size_t index) { diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_byte_skipper.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_byte_skipper.hpp index 369c68481..6b20c1173 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_byte_skipper.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_byte_skipper.hpp @@ -47,13 +47,11 @@ class CSVByteSkipper { //! Skips bytes that match no stop pattern, `pos` ends on a candidate stop, on `limit`, or in the buffer tail inline SkippedTo SkipToCandidate(const idx_t limit, idx_t &pos) { while (pos < limit) { - if (pos < block_start || pos >= block_end) { - if (pos + SwarBlock::SIZE > buffer_size) { - return SkippedTo::TAIL; - } - MaskBlock(pos); + uint64_t candidates; + idx_t block_end_p; + if (!BlockCandidates(pos, candidates, block_end_p)) { + return SkippedTo::TAIL; } - const uint64_t candidates = stop_mask >> (pos - block_start); if (candidates) { const idx_t candidate = pos + CountZeros::Trailing(candidates); if (candidate < limit) { @@ -66,6 +64,19 @@ class CSVByteSkipper { return SkippedTo::CANDIDATE_NOT_FOUND; } + //! The stop candidates of the block holding `pos`, bit i is byte pos + i, false in the buffer tail + inline bool BlockCandidates(const idx_t pos, uint64_t &candidates, idx_t &block_end_p) { + if (pos < block_start || pos >= block_end) { + if (pos + SwarBlock::SIZE > buffer_size) { + return false; + } + MaskBlock(pos); + } + candidates = stop_mask >> (pos - block_start); + block_end_p = block_end; + return true; + } + //! Skips every byte `skip_table` skips, `pos` ends on a stop or on the byte before `to_pos` inline void SkipToStop(const bool (&skip_table)[StateMachine::NUM_TRANSITIONS], const idx_t to_pos, idx_t &pos) { while (pos + 1 < to_pos) { diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp index 60905b57b..181485637 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp @@ -184,13 +184,14 @@ struct CSVReaderOptions { //! Set an option that is supported by both reading and writing functions, called by //! the SetReadOption and SetWriteOption methods - bool SetBaseOption(const Identifier &loption, const Value &value, bool write_option = false); + bool SetBaseOption(Context &context, const Identifier &loption, const Value &value, bool write_option = false); //! loption - lowercase string //! set - argument(s) to the option //! expected_names - names expected if the option is "columns" - void SetReadOption(const Identifier &loption, const Value &value, const vector &expected_names); - void SetWriteOption(const Identifier &loption, const Value &value); + void SetReadOption(Context &context, const Identifier &loption, const Value &value, + const vector &expected_names); + void SetWriteOption(Context &context, const Identifier &loption, const Value &value); void SetDateFormat(LogicalTypeId type, const string &format, bool read_format); void ToNamedParameters(named_parameter_map_t &out) const; void FromNamedParameters(const named_argument_map_t &in, ClientContext &context, MultiFileOptions &file_options); diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_state_machine_cache.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_state_machine_cache.hpp index ef86bf6c5..9ef44cd1e 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_state_machine_cache.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_state_machine_cache.hpp @@ -31,6 +31,8 @@ class StateMachine { bool skip_comment[256]; //! The byte patterns that cover every byte the skip tables stop at, for the byte skipper vector stop_patterns; + //! Whether BaseScanner::ProcessBlocks may drive this state machine, see BlockScanEligible + bool block_scan = false; const CSVState *operator[](const idx_t i) const { return state_machine[i]; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/skip_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/skip_scanner.hpp index 397a0406d..94a217c1a 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/skip_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/skip_scanner.hpp @@ -18,6 +18,8 @@ namespace duckdb { class SkipResult : public ScannerResult { public: + static constexpr bool BLOCK_SCAN = false; + SkipResult(CSVStates &states, CSVStateMachine &state_machine, idx_t rows_to_skip); idx_t row_count = 0; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp index 85c7e8159..ab4255cce 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp @@ -179,6 +179,9 @@ struct ParseTypeInfo { class StringValueResult : public ScannerResult { public: + //! Scanned block by block, see BaseScanner::ProcessBlocks + static constexpr bool BLOCK_SCAN = true; + StringValueResult(CSVStates &states, CSVStateMachine &state_machine, const shared_ptr &buffer_handle, Allocator &buffer_allocator, idx_t result_size_p, idx_t buffer_position, CSVErrorHandler &error_handler, CSVIterator &iterator, diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp index b525c1a98..2e9f37705 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp @@ -48,7 +48,7 @@ class PhysicalCopyToFile : public PhysicalOperator { static string GetTrimmedPath(ClientContext &context, const string &file_path); static void MoveTmpFile(ClientContext &context, const string &tmp_file_path); static string GetNonTmpFile(ClientContext &context, const string &tmp_file_path); - static void ReturnStatistics(DataChunk &chunk, CopyToFileInfo &written_file_info); + static void ReturnStatistics(Context &context, DataChunk &chunk, CopyToFileInfo &written_file_info); //! Adds the RETURN_STATS row of a COPY that wrote no file, so that RETURN_COLUMN_TYPES can still return the types static void ReturnNoFileStatistics(DataChunk &chunk); //! Sets the last column of every row in the chunk to the RETURN_COLUMN_TYPES value diff --git a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp index 09f472231..4e88cb2d3 100644 --- a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp +++ b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp @@ -49,7 +49,7 @@ class PhysicalPlan { public: template - PhysicalOperator &Make(ARGS &&... args) { + PhysicalOperator &Make(ARGS &&...args) { static_assert(std::is_base_of::value, "T must be a physical operator"); auto ptr = arena.Make(*this, std::forward(args)...); ops.push_back(*ptr); @@ -118,7 +118,7 @@ class PhysicalPlanGenerator { PhysicalOperator &child, vector &partition_columns); //! Make a physical operator in the physical plan. template - PhysicalOperator &Make(ARGS &&... args) { + PhysicalOperator &Make(ARGS &&...args) { return physical_plan->Make(std::forward(args)...); } @@ -189,6 +189,20 @@ class PhysicalPlanGenerator { PhysicalOperator &PlanAsOfJoin(LogicalComparisonJoin &op); PhysicalOperator &PlanComparisonJoin(LogicalComparisonJoin &op); + //! Pruning projection maps lifted off a join whose physical operator emits full input widths + struct PrunedJoinProjection { + bool active = false; + bool expanded_left = false; + bool expanded_right = false; + vector left_map; + vector right_map; + vector original_types; + }; + PrunedJoinProjection ExtractPrunedJoinProjection(LogicalComparisonJoin &op, const PhysicalOperator &left, + const PhysicalOperator &right, bool expand_left, + bool expand_right); + PhysicalOperator &RestorePrunedJoinProjection(LogicalComparisonJoin &op, PhysicalOperator &join, + PrunedJoinProjection info); PhysicalOperator &PlanDelimJoin(LogicalComparisonJoin &op); PhysicalOperator &ExtractAggregateExpressions(PhysicalOperator &child, vector> &expressions, vector> &groups, diff --git a/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp b/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp index c1dcc8ff9..719e97f04 100644 --- a/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp @@ -10,6 +10,7 @@ #include "duckdb/function/cast/default_casts.hpp" #include "duckdb/function/combine_types_rule.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { struct MapCastInfo; @@ -25,6 +26,8 @@ struct GetCastFunctionInput { } explicit GetCastFunctionInput(ClientContext &context) : context(&context) { } + explicit GetCastFunctionInput(Context &context) : context(context.TryGetClientContext()) { + } optional_ptr context; QueryLocation query_location; @@ -47,6 +50,7 @@ class CastFunctionSet { DUCKDB_API static CastFunctionSet &Get(ClientContext &context); DUCKDB_API static const CastFunctionSet &Get(const ClientContext &context); DUCKDB_API static CastFunctionSet &Get(DatabaseInstance &db); + DUCKDB_API static CastFunctionSet &Get(Context &context); //! Returns a cast function (from source -> target) //! Note that this always returns a function - since a cast is ALWAYS possible if the value is NULL diff --git a/src/duckdb/src/include/duckdb/main/attached_database.hpp b/src/duckdb/src/include/duckdb/main/attached_database.hpp index d3c3adffb..59fa7ee51 100644 --- a/src/duckdb/src/include/duckdb/main/attached_database.hpp +++ b/src/duckdb/src/include/duckdb/main/attached_database.hpp @@ -67,7 +67,7 @@ struct AttachOptions { //! Constructor for databases we attach outside of the ATTACH DATABASE statement. explicit AttachOptions(const DBConfigOptions &options); //! Constructor for databases we attach when using ATTACH DATABASE. - AttachOptions(const unordered_map &options, const AccessMode default_access_mode); + AttachOptions(Context &context, const unordered_map &options, const AccessMode default_access_mode); //! The setting an attach option controls, lower-cased. All four spellings of the access mode //! (readonly, read_only, readwrite, read_write) share one setting, so two of them in the same diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp index d41fdf263..7ce27d1db 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp @@ -135,7 +135,9 @@ class CV2ConstantBindInfo final : public CV2FunctionBindInfo { const named_argument_map_t &named; }; -//! The statistics a stats callback reads or narrows. Argument statistics are read-only: they have no mutable view +//! The statistics a stats callback reads or narrows, or statistics a function builds itself with +//! duckdb_v2_stats_create. Argument statistics are read-only: they have no mutable view. Created statistics own their +//! BaseStatistics. class CV2Stats { public: explicit CV2Stats(const BaseStatistics &stats) : stats(stats) { @@ -145,16 +147,27 @@ class CV2Stats { result.mutable_stats = &stats; return result; } + //! Heap-allocated owning statistics, freed by duckdb_v2_stats_destroy + static unique_ptr Owned(BaseStatistics &&stats) { + auto owned = make_uniq(std::move(stats)); + auto result = make_uniq(Writable(*owned)); + result->owned = std::move(owned); + return result; + } const BaseStatistics &GetStats() const { return stats; } //! Throws when the statistics are read-only BaseStatistics &GetMutableStats(const char *function_name); + bool IsOwned() const { + return owned != nullptr; + } private: const BaseStatistics &stats; optional_ptr mutable_stats; + unique_ptr owned; }; inline auto Convert(duckdb_v2_stats_handle stats) -> CV2Stats * { diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp index d11b1acbe..57312542b 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp @@ -1496,6 +1496,21 @@ typedef struct { (duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, const char **column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_expression_check_statistics) + (duckdb_v2_context_handle context, duckdb_v2_expression_handle expression, duckdb_v2_stats_handle stats, + DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_create) + (duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle type, duckdb_v2_stats_handle *stats, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_stats_destroy)(duckdb_v2_stats_handle *stats); + DUCKDB_V2_ERROR(*duckdb_v2_stats_merge) + (duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_assign) + (duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_get_value) + (duckdb_v2_stats_handle stats, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_set_value) + (duckdb_v2_stats_handle stats, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2177,6 +2192,13 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_query_metrics_node_get_metric_value = duckdb_v2_query_metrics_node_get_metric_value; result.duckdb_v2_query_metrics_node_get_name = duckdb_v2_query_metrics_node_get_name; result.duckdb_v2_statement_add_collection = duckdb_v2_statement_add_collection; + result.duckdb_v2_expression_check_statistics = duckdb_v2_expression_check_statistics; + result.duckdb_v2_stats_create = duckdb_v2_stats_create; + result.duckdb_v2_stats_destroy = duckdb_v2_stats_destroy; + result.duckdb_v2_stats_merge = duckdb_v2_stats_merge; + result.duckdb_v2_stats_assign = duckdb_v2_stats_assign; + result.duckdb_v2_stats_get_value = duckdb_v2_stats_get_value; + result.duckdb_v2_stats_set_value = duckdb_v2_stats_set_value; return result; } diff --git a/src/duckdb/src/include/duckdb/main/client_config.hpp b/src/duckdb/src/include/duckdb/main/client_config.hpp index fa0256cab..8c3aa3067 100644 --- a/src/duckdb/src/include/duckdb/main/client_config.hpp +++ b/src/duckdb/src/include/duckdb/main/client_config.hpp @@ -47,9 +47,6 @@ struct ClientConfig { //! The file to save query profiling information to, instead of printing it to the console //! (empty = print to console) string profiler_save_location; - //! Glob patterns for tracked_metrics (controls which metrics are gathered and displayed). - //! Default "*" means all metrics are tracked. - vector tracked_metrics = {"*"}; //! Settings that are passed to the renderer of the profiler output (e.g. 'maximum_render_width' for the text //! renderer). Settings that are not recognized by the active renderer are ignored. unordered_map profiling_renderer_settings; diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index a8023dd38..b79f5f3cc 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -58,7 +58,14 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"__aws__cloudformation__quack_on_ec2__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__aws__cloudformation__quack_on_ec2__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__aws__cloudformation__quack_on_ec2__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__cloudformation__quack_on_ec2__resolve", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__aws__cloudformation__quack_on_ec2__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__expired", "aws", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"__aws__s3tables__table_bucket__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__table_bucket__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__table_bucket__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__table_bucket__resolve", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__table_bucket__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__internal_json_copy_to_geojson", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"__internal_json_copy_to_json", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"abs", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -797,6 +804,13 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"rtree_index_dump", "spatial", CatalogType::TABLE_FUNCTION_ENTRY}, {"rtree_index_scan", "spatial", CatalogType::TABLE_FUNCTION_ENTRY}, {"rtrim", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"s3tables_create_table_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_delete_table_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_get_table_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_namespaces", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_table_bucket_tags", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_table_buckets", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_tables", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"scan_data_from_quack_client", "quack", CatalogType::TABLE_FUNCTION_ENTRY}, {"sem", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, {"set_bit", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -1542,6 +1556,7 @@ static constexpr ExtensionEntry EXTENSION_SECRET_TYPES[] = { // Resource types registered by extensions: CREATE/REGISTER EXTERNAL RESOURCE '' autoloads the extension static constexpr ExtensionEntry EXTENSION_EXTERNAL_RESOURCE_TYPES[] = { {"aws:cloudformation:quack-on-ec2", "aws"}, + {"aws:s3tables:table-bucket", "aws"}, }; // END_OF_EXTENSION_EXTERNAL_RESOURCE_TYPES // Note: these are currently hardcoded in scripts/generate_extensions_function.py diff --git a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp index 6188d096c..3cc882f3c 100644 --- a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp @@ -58,6 +58,8 @@ class ExtensionRepositoryManager { //! Whether the user has opted in to adding external extension repositories static ExtensionRepositoryAccess GetAccess(DatabaseInstance &db); + //! Whether the repositories that were already created are trusted: their extensions can be installed and loaded + static bool TrustsExistingRepositories(DatabaseInstance &db); //! Parse the access value of the allow_extension_repositories setting (throws on an invalid value) static ExtensionRepositoryAccess ParseAccess(const string &value); //! The string representation of an access value, as used by the allow_extension_repositories setting diff --git a/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp b/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp index 43a6c6954..6ac04f8b3 100644 --- a/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp +++ b/src/duckdb/src/include/duckdb/main/external_resource_type_registry.hpp @@ -34,7 +34,8 @@ struct ExternalResourceType { //! Function that reconnects to an existing resource. May be empty. string resolve_function; //! Function that enumerates the resources of this type that exist externally (for discovery / - //! `SHOW ALL EXTERNAL RESOURCES`). Returns a table of handles. May be empty. + //! `SHOW ALL EXTERNAL RESOURCES`). Returns one row per resource: handle (MAP), name (the provider's own + //! name for it, unique within the type), reference and state. May be empty. string list_function; //! Where it came from: "user" (register_external_resource_type) or "extension". string origin; diff --git a/src/duckdb/src/include/duckdb/main/http/http_retry_budget.hpp b/src/duckdb/src/include/duckdb/main/http/http_retry_budget.hpp index 98d972dee..3e8b3028f 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_retry_budget.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_retry_budget.hpp @@ -80,6 +80,8 @@ class HTTPRetryQuota { public: //! Take `cost` tokens; false (and nothing taken) when fewer are available. DUCKDB_API bool TryAcquire(int64_t cost, int64_t now_ms = TimePoint::GetTickMs()); + //! Take `cost` tokens, or all that are left when fewer are available; returns the number taken. + DUCKDB_API int64_t AcquireUpTo(int64_t cost, int64_t now_ms = TimePoint::GetTickMs()); //! Return tokens, never above the initial capacity. DUCKDB_API void Release(int64_t amount, int64_t now_ms = TimePoint::GetTickMs()); DUCKDB_API int64_t Available() const; @@ -203,6 +205,10 @@ class HTTPRetryBudget { const uint64_t retries; const uint64_t retry_wait_ms; const float retry_backoff; + //! Whether the host quota may refuse a throttled retry; when not, it is charged what the quota has left. + const bool retry_quota_throttled; + //! Smallest base wait of throttled retries. + const uint64_t retry_throttled_wait_ms; //! Who settles the outcome with the quota. const HTTPRetryOutcomeOwner owner; diff --git a/src/duckdb/src/include/duckdb/main/http/http_util.hpp b/src/duckdb/src/include/duckdb/main/http/http_util.hpp index 24ec50552..79217348c 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_util.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_util.hpp @@ -45,6 +45,10 @@ struct HTTPParams { uint64_t retries = DEFAULT_RETRIES; uint64_t retry_wait_ms = DEFAULT_RETRY_WAIT_MS; float retry_backoff = DEFAULT_RETRY_BACKOFF; + //! Whether the host's retry quota may refuse a throttled retry (http_retry_quota_throttled) + bool retry_quota_throttled = true; + //! Smallest base wait of the back-off between throttled retries (http_retry_throttled_wait_ms) + uint64_t retry_throttled_wait_ms = 0; bool keep_alive = DEFAULT_KEEP_ALIVE; bool follow_location = true; bool override_verify_ssl = false; diff --git a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp index d32be4236..f8e6d860b 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp @@ -127,7 +127,8 @@ class SecretManager { //! Create a secret from a CreateSecretInfo DUCKDB_API unique_ptr CreateSecret(ClientContext &context, const CreateSecretInput &info); //! The Bind for create secret is done by the secret manager - DUCKDB_API BoundStatement BindCreateSecret(CatalogTransaction transaction, CreateSecretInput &info); + DUCKDB_API BoundStatement BindCreateSecret(Context &context, CatalogTransaction transaction, + CreateSecretInput &info); //! Lookup the best matching secret by matching the secret scopes to the path DUCKDB_API SecretMatch LookupSecret(CatalogTransaction transaction, const string &path, const string &type); //! Get a secret by name, optionally from a specific storage diff --git a/src/duckdb/src/include/duckdb/main/setting_info.hpp b/src/duckdb/src/include/duckdb/main/setting_info.hpp index 0503712eb..1c50d2a6e 100644 --- a/src/duckdb/src/include/duckdb/main/setting_info.hpp +++ b/src/duckdb/src/include/duckdb/main/setting_info.hpp @@ -85,6 +85,7 @@ typedef void (*set_local_function_t)(ClientContext &context, const Value ¶me typedef void (*reset_global_function_t)(DatabaseInstance *db, DBConfig &config); typedef void (*reset_local_function_t)(ClientContext &context); typedef Value (*get_setting_function_t)(const ClientContext &context); +typedef Value (*get_default_value_function_t)(); struct ConfigurationOption { const char *name; @@ -101,6 +102,8 @@ struct ConfigurationOption { optional_idx setting_idx; bool is_debug = false; bool is_deprecated = false; + //! The typed default value of a generic setting + get_default_value_function_t get_default_value = nullptr; }; struct ConfigurationAlias { diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index 4529cfb32..ebdda19c2 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -15,78 +15,162 @@ namespace duckdb { class Context; +template +struct IsSettingList : std::false_type {}; + +template +struct IsSettingList> : std::true_type {}; + struct Settings { template - static typename std::enable_if::value, typename OP::RETURN_TYPE>::type - Get(const SOURCE &source) { + static typename OP::RETURN_TYPE Get(const SOURCE &source) { Value result; if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { - return EnumUtil::FromString(StringValue::Get(result)); + return FromValue(result); } - return EnumUtil::FromString(OP::DefaultValue); + return FromDefault(OP::DefaultValue); } - template - static typename std::enable_if::value, string>::type - Get(const SOURCE &source) { - Value result; - if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { - return StringValue::Get(result); - } - return OP::DefaultValue; + template + static void Set(SOURCE &source, idx_t setting_index, SetScope scope, Value target_value) { + SetSettingInternal(source, setting_index, scope, std::move(target_value)); } template - static typename std::enable_if::value, bool>::type - Get(const SOURCE &source) { - Value result; - if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { - return BooleanValue::Get(result); - } - return StringUtil::Equals(OP::DefaultValue, "true"); + static void Set(SOURCE &source, SetScope scope, Value target_value) { + Set(source, OP::SettingIndex, scope, std::move(target_value)); } - template - static typename std::enable_if::value, idx_t>::type - Get(const SOURCE &source) { - Value result; - if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { - return UBigIntValue::Get(result); - } - return StringUtil::ToUnsigned(OP::DefaultValue); + //! The default value of a setting as a Value of its input type + template + static Value GetDefaultValue() { + return DefaultToValue(OP::DefaultValue); } - template - static typename std::enable_if::value, int64_t>::type - Get(const SOURCE &source) { - Value result; - if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { - return BigIntValue::Get(result); +private: + //! Converts the value of a setting to its return type + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + return EnumUtil::FromString(StringValue::Get(value)); + } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + return StringValue::Get(value); + } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + return BooleanValue::Get(value); + } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + return UBigIntValue::Get(value); + } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + return BigIntValue::Get(value); + } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + return DoubleValue::Get(value); + } + template + static typename std::enable_if::value, T>::type FromValue(const Value &value) { + T result; + for (auto &child : ListValue::GetChildren(value)) { + result.push_back(FromValue(child)); } - return StringUtil::ToSigned(OP::DefaultValue); + return result; } - template - static typename std::enable_if::value, double>::type - Get(const SOURCE &source) { - Value result; - if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { - return DoubleValue::Get(result); + //! Parses the default value of a setting + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + return EnumUtil::FromString(default_value); + } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + return default_value; + } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + return StringUtil::Equals(default_value, "true"); + } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + return StringUtil::ToUnsigned(default_value); + } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + return StringUtil::ToSigned(default_value); + } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + return StringUtil::ToDouble(default_value); + } + template + static typename std::enable_if::value, T>::type FromDefault(const char *default_value) { + T result; + for (auto &entry : SplitListDefault(default_value)) { + result.push_back(FromDefault(entry.c_str())); } - return StringUtil::ToDouble(OP::DefaultValue); + return result; + } + //! Splits a list literal (e.g. "['a', 'b']") into its entries + static vector SplitListDefault(const char *default_value); + + //! String and enum settings are VARCHAR: their default is used as written + template + static typename std::enable_if::value || std::is_same::value, Value>::type + DefaultToValue(const char *default_value) { + return Value(default_value); + } + template + static typename std::enable_if::value && !std::is_same::value, Value>::type + DefaultToValue(const char *default_value) { + return ToSettingValue(FromDefault(default_value)); } - template - static void Set(SOURCE &source, idx_t setting_index, SetScope scope, Value target_value) { - SetSettingInternal(source, setting_index, scope, std::move(target_value)); + static Value ToSettingValue(const string &value) { + return Value(value); + } + static Value ToSettingValue(bool value) { + return Value::BOOLEAN(value); + } + static Value ToSettingValue(uint64_t value) { + return Value::UBIGINT(value); + } + static Value ToSettingValue(int64_t value) { + return Value::BIGINT(value); + } + static Value ToSettingValue(double value) { + return Value::DOUBLE(value); + } + template + static Value ToSettingValue(const vector &values) { + vector children; + for (auto &value : values) { + children.push_back(ToSettingValue(value)); + } + return Value::LIST(SettingLogicalType(static_cast(nullptr)), std::move(children)); } - template - static void Set(SOURCE &source, SetScope scope, Value target_value) { - Set(source, OP::SettingIndex, scope, std::move(target_value)); + //! The logical type of a setting value, selected by the (unused) pointer type + static LogicalType SettingLogicalType(const string *) { + return LogicalType::VARCHAR; + } + static LogicalType SettingLogicalType(const bool *) { + return LogicalType::BOOLEAN; + } + static LogicalType SettingLogicalType(const uint64_t *) { + return LogicalType::UBIGINT; + } + static LogicalType SettingLogicalType(const int64_t *) { + return LogicalType::BIGINT; + } + static LogicalType SettingLogicalType(const double *) { + return LogicalType::DOUBLE; } -private: static bool TryGetSettingInternal(const DatabaseInstance &db, idx_t setting_index, Value &result); static bool TryGetSettingInternal(const DBConfig &config, idx_t setting_index, Value &result); static bool TryGetSettingInternal(const ClientContext &context, idx_t setting_index, Value &result); @@ -1756,6 +1840,34 @@ struct HTTPProxyUsernameSetting { static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; +struct HTTPRetryQuotaThrottledSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "http_retry_quota_throttled"; + static constexpr const char *Description = + "Whether the per-host retry quota can refuse the retry of a throttled request (HTTP 429 or 503). When false, a " + "throttled retry is still charged to the quota but is not refused when the quota is empty."; + static constexpr const char *InputType = "BOOLEAN"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "true"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + +struct HTTPRetryThrottledWaitMsSetting { + using RETURN_TYPE = idx_t; + static constexpr const char *Name = "http_retry_throttled_wait_ms"; + static constexpr const char *Description = + "Smallest base wait, in milliseconds, of the back-off between retries of a throttled request (HTTP 429 or " + "503). Throttled retries back off from the larger of this and http_retry_wait_ms."; + static constexpr const char *InputType = "UBIGINT"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "0"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct IeeeFloatingPointOpsSetting { using RETURN_TYPE = bool; static constexpr const char *Name = "ieee_floating_point_ops"; @@ -2585,9 +2697,10 @@ struct TrackedMetricsSetting { static constexpr const char *InputType = "VARCHAR[]"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetLocal(ClientContext &context, const Value ¶meter); - static void ResetLocal(ClientContext &context); - static Value GetSetting(const ClientContext &context); + static constexpr const char *DefaultValue = "['*']"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct UsernameSetting { diff --git a/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp b/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp index 727361208..3abc00692 100644 --- a/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp @@ -33,7 +33,6 @@ class ApplyFunctionalDependencies : public LogicalOperatorVisitor { private: void VisitLogicalGet(LogicalGet &get); void VisitLogicalAggregate(LogicalAggregate &aggr); - void VisitLogicalDistinct(LogicalDistinct &distinct); void VisitLogicalProjection(LogicalProjection &projection); void VisitLogicalOrder(LogicalOrder &order); diff --git a/src/duckdb/src/include/duckdb/optimizer/column_lifetime_analyzer.hpp b/src/duckdb/src/include/duckdb/optimizer/column_lifetime_analyzer.hpp index 8e9f313dd..0a29328c3 100644 --- a/src/duckdb/src/include/duckdb/optimizer/column_lifetime_analyzer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/column_lifetime_analyzer.hpp @@ -50,6 +50,6 @@ class ColumnLifetimeAnalyzer : public LogicalOperatorVisitor { static void GenerateProjectionMap(vector bindings, column_binding_set_t &unused_bindings, vector &map); void Verify(LogicalOperator &op); - void AddVerificationProjection(unique_ptr &child); + void AddVerificationProjection(unique_ptr &child, vector &projection_map); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp b/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp index b9d04cb0d..81478c5e4 100644 --- a/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp @@ -115,7 +115,6 @@ class CompressedMaterialization { //! Compress materializing operators void CompressAggregate(unique_ptr &op); void CompressComparisonJoin(unique_ptr &op); - void CompressDistinct(unique_ptr &op); void CompressOrder(unique_ptr &op); //! Update statistics after compressing diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp index 7547fd138..6e7a5ffe8 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp @@ -52,8 +52,6 @@ class FilterPullup { unique_ptr PullupSemiJoin(unique_ptr op); //! Pullup filter in an inner join unique_ptr PullupInnerJoin(unique_ptr op); - //! Pullup filter through a distinct - unique_ptr PullupDistinct(unique_ptr op); //! Pullup the filters on the partitions of a window unique_ptr PullupWindow(unique_ptr op); //! Pullup filter in LogicalIntersect or LogicalExcept op diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp index 75f0c856a..c14531db0 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp @@ -68,8 +68,6 @@ class FilterPushdown { vector> filters; //! Push down a LogicalAggregate op unique_ptr PushdownAggregate(unique_ptr op); - //! Push down a distinct operator - unique_ptr PushdownDistinct(unique_ptr op); //! Push down a LogicalFilter op unique_ptr PushdownFilter(unique_ptr op); //! Push down a LogicalCrossProduct op @@ -129,6 +127,8 @@ class FilterPushdown { // Finish pushing down at this operator, creating a LogicalFilter to store any of the stored filters and recursively // pushing down into its children (if any) unique_ptr FinishPushdown(unique_ptr op); + //! Rewrite a child of op with this pushdown, keeping op's projection map of that child on its new layout + void RewriteChild(LogicalOperator &op, idx_t child_idx); //! Adds a filter to the set of filters. Returns FilterResult::UNSATISFIABLE if the subtree should be stripped, or //! FilterResult::SUCCESS otherwise diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp index 42976f54f..b66db90b3 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp @@ -23,7 +23,6 @@ class LogicalAggregate; class LogicalColumnDataGet; class LogicalComparisonJoin; class LogicalDelimGet; -class LogicalDistinct; class LogicalDummyScan; class LogicalEmptyResult; class LogicalExpressionGet; @@ -68,7 +67,6 @@ class RelationStatisticsHelper { const RelationStats &child_stats, RelationStatsExtractor &extractor); static optional ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats); - static optional ExtractDistinctStats(LogicalDistinct &distinct, const RelationStats &child_stats); static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats); static optional ExtractLimitStats(LogicalLimit &limit, const RelationStats &child_stats); static RelationStats ExtractEmptyResultStats(LogicalEmptyResult &empty); diff --git a/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp b/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp index a6b6a4af5..1063a3716 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp @@ -26,11 +26,26 @@ struct ParsedOperator { bool is_any = true; }; +//! A '->' or '->>' operator that directly follows the operand of a '->' +struct ArrowChainLink { + bool is_double_arrow = false; + unique_ptr expression; +}; + struct OtherOperatorTail { ParsedOperator op; unique_ptr expression; //! Whether the right-hand side is a subquery, as in ANY(SELECT ...) bool is_subquery = false; + //! Set for the '->' operator, whose operand may be followed by a chain of arrows + bool is_arrow = false; + vector arrow_chain; +}; + +//! The operand of a '->' and the arrows chained behind it +struct ArrowBody { + unique_ptr expression; + vector arrow_chain; }; enum class ExpressionTailType : uint8_t { IS_TEST, DISTINCT, COMPARISON, OTHER_OPERATOR, CAST }; 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 bcfb1e9b2..04867892b 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -60,6 +60,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 82, 101, 115, 101, 114, 118, 101, 100, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 32, 60, 45, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, 82, 101, 115, 101, 114, 118, 101, 100, 84, 121, 112, 101, 78, 97, 109, 101, 32, 60, 45, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 32, 60, 45, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, + 82, 101, 115, 101, 114, 118, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 32, 60, 45, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, 67, 111, 110, 115, 116, 114, 97, 105, 110, 116, 78, 97, 109, 101, 32, 60, 45, 32, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 10, 83, 101, 113, 117, 101, 110, 99, 101, 78, 97, 109, 101, 32, 60, 45, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, 67, 111, 108, 108, 97, 116, 105, 111, 110, 78, 97, 109, 101, 32, 60, 45, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, @@ -1673,11 +1674,8 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 32, 32, 32, 32, 80, 111, 115, 105, 116, 105, 111, 110, 97, 108, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 47, 10, 32, 32, 32, 32, 68, 101, 102, 97, 117, 108, 116, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 35, 32, 76, 69, 86, 69, 76, 32, 49, 32, 40, 76, 111, 119, 101, 115, 116, 41, 10, - 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 76, 97, 109, 98, 100, 97, 65, 114, 114, 111, 119, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 67, 111, 108, 117, 109, 110, 68, 101, 102, 97, 117, 108, 116, 69, 120, 112, 114, 32, 60, 45, 32, 67, 111, 108, 68, 101, 102, 79, 114, 69, 120, 112, 114, 10, - 35, 32, 76, 69, 86, 69, 76, 32, 49, 46, 53, 10, - 76, 97, 109, 98, 100, 97, 65, 114, 114, 111, 119, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 80, 97, 105, 114, 42, 10, - 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 80, 97, 105, 114, 32, 60, 45, 32, 39, 45, 62, 39, 32, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 76, 111, 103, 105, 99, 97, 108, 65, 110, 100, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 42, 10, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 32, 60, 45, 32, 39, 79, 82, 39, 32, 76, 111, 103, 105, 99, 97, 108, 65, 110, 100, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 67, 111, 108, 68, 101, 102, 79, 114, 69, 120, 112, 114, 32, 60, 45, 32, 67, 111, 108, 68, 101, 102, 65, 110, 100, 69, 120, 112, 114, 32, 67, 111, 108, 68, 101, 102, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 42, 10, @@ -1760,9 +1758,17 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 35, 32, 76, 69, 86, 69, 76, 32, 56, 10, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 73, 110, 102, 105, 120, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 73, 110, 102, 105, 120, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 84, 97, 105, 108, 42, 10, - 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 84, 97, 105, 108, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 83, 117, 98, 113, 117, 101, 114, 121, 84, 97, 105, 108, 32, 47, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 10, + 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 84, 97, 105, 108, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 83, 117, 98, 113, 117, 101, 114, 121, 84, 97, 105, 108, 32, 47, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 32, 47, 32, 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 84, 97, 105, 108, 10, 65, 110, 121, 65, 108, 108, 83, 117, 98, 113, 117, 101, 114, 121, 84, 97, 105, 108, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 80, 97, 114, 115, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 83, 117, 98, 113, 117, 101, 114, 121, 82, 101, 102, 101, 114, 101, 110, 99, 101, 10, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 32, 60, 45, 32, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 35, 32, 39, 45, 62, 39, 32, 105, 115, 32, 116, 104, 101, 32, 108, 97, 109, 98, 100, 97, 32, 97, 114, 114, 111, 119, 32, 111, 114, 32, 116, 104, 101, 32, 74, 83, 79, 78, 32, 101, 120, 116, 114, 97, 99, 116, 32, 111, 112, 101, 114, 97, 116, 111, 114, 46, 32, 73, 116, 115, 32, 111, 112, 101, 114, 97, 110, 100, 32, 101, 120, 116, 101, 110, 100, 115, 32, 97, 115, 32, 102, 97, 114, 32, 97, 115, 32, 112, 111, 115, 115, 105, 98, 108, 101, 32, 40, 116, 104, 101, 32, 108, 97, 109, 98, 100, 97, 32, 98, 111, 100, 121, 41, 44, 10, + 35, 32, 117, 110, 108, 101, 115, 115, 32, 97, 110, 111, 116, 104, 101, 114, 32, 97, 114, 114, 111, 119, 32, 102, 111, 108, 108, 111, 119, 115, 32, 100, 105, 114, 101, 99, 116, 108, 121, 58, 32, 116, 104, 101, 110, 32, 116, 104, 101, 32, 97, 114, 114, 111, 119, 115, 32, 99, 104, 97, 105, 110, 32, 116, 111, 32, 116, 104, 101, 32, 108, 101, 102, 116, 44, 32, 108, 105, 107, 101, 32, 105, 110, 32, 80, 111, 115, 116, 103, 114, 101, 83, 81, 76, 46, 10, + 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 84, 97, 105, 108, 32, 60, 45, 32, 39, 45, 62, 39, 32, 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 66, 111, 100, 121, 10, + 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 66, 111, 100, 121, 32, 60, 45, 32, 65, 114, 114, 111, 119, 67, 104, 97, 105, 110, 66, 111, 100, 121, 32, 47, 32, 65, 114, 114, 111, 119, 70, 117, 108, 108, 66, 111, 100, 121, 10, + 65, 114, 114, 111, 119, 67, 104, 97, 105, 110, 66, 111, 100, 121, 32, 60, 45, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 65, 114, 114, 111, 119, 67, 104, 97, 105, 110, 84, 97, 105, 108, 43, 10, + 65, 114, 114, 111, 119, 67, 104, 97, 105, 110, 84, 97, 105, 108, 32, 60, 45, 32, 68, 111, 117, 98, 108, 101, 65, 114, 114, 111, 119, 84, 97, 105, 108, 32, 47, 32, 83, 105, 110, 103, 108, 101, 65, 114, 114, 111, 119, 84, 97, 105, 108, 10, + 68, 111, 117, 98, 108, 101, 65, 114, 114, 111, 119, 84, 97, 105, 108, 32, 60, 45, 32, 39, 45, 62, 62, 39, 32, 66, 105, 116, 119, 105, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 65, 114, 114, 111, 119, 70, 117, 108, 108, 66, 111, 100, 121, 32, 60, 45, 32, 76, 111, 103, 105, 99, 97, 108, 79, 114, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 10, 32, 32, 32, 32, 65, 110, 121, 65, 108, 108, 80, 97, 114, 115, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 47, 32, 78, 97, 109, 101, 100, 79, 116, 104, 101, 114, 79, 112, 101, 114, 97, 116, 111, 114, 10, 65, 110, 121, 65, 108, 108, 80, 97, 114, 115, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 65, 110, 121, 65, 108, 108, 79, 112, 101, 114, 97, 116, 111, 114, 10, @@ -2126,7 +2132,10 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 76, 97, 116, 101, 114, 97, 108, 79, 112, 116, 32, 60, 45, 32, 76, 97, 116, 101, 114, 97, 108, 63, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 115, 32, 87, 105, 116, 104, 79, 114, 100, 105, 110, 97, 108, 105, 116, 121, 63, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 32, 60, 45, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 67, 111, 108, 111, 110, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 32, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 115, 32, 87, 105, 116, 104, 79, 114, 100, 105, 110, 97, 108, 105, 116, 121, 63, 32, 83, 97, 109, 112, 108, 101, 67, 108, 97, 117, 115, 101, 63, 10, 87, 105, 116, 104, 79, 114, 100, 105, 110, 97, 108, 105, 116, 121, 32, 60, 45, 32, 39, 87, 73, 84, 72, 39, 32, 39, 79, 82, 68, 73, 78, 65, 76, 73, 84, 89, 39, 10, - 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 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, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 10, + 81, 117, 97, 108, 105, 102, 105, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 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, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 32, 47, 32, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 65, 115, 81, 117, 97, 108, 105, 102, 105, 101, 100, 78, 97, 109, 101, 10, + 35, 32, 97, 102, 116, 101, 114, 32, 97, 32, 113, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 32, 97, 32, 114, 101, 115, 101, 114, 118, 101, 100, 32, 107, 101, 121, 119, 111, 114, 100, 32, 99, 97, 110, 32, 110, 97, 109, 101, 32, 97, 32, 116, 97, 98, 108, 101, 32, 102, 117, 110, 99, 116, 105, 111, 110, 44, 32, 97, 115, 32, 105, 110, 32, 103, 46, 100, 101, 115, 99, 114, 105, 98, 101, 40, 39, 97, 39, 41, 10, + 67, 97, 116, 97, 108, 111, 103, 82, 101, 115, 101, 114, 118, 101, 100, 83, 99, 104, 101, 109, 97, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 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, 32, 83, 99, 104, 101, 109, 97, 81, 117, 97, 108, 105, 102, 105, 99, 97, 116, 105, 111, 110, 42, 32, 82, 101, 115, 101, 114, 118, 101, 100, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 10, + 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 65, 115, 81, 117, 97, 108, 105, 102, 105, 101, 100, 78, 97, 109, 101, 32, 60, 45, 32, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 78, 97, 109, 101, 10, 84, 97, 98, 108, 101, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 115, 32, 60, 45, 32, 80, 97, 114, 101, 110, 115, 40, 76, 105, 115, 116, 40, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 41, 63, 41, 10, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 32, 60, 45, 32, 78, 97, 109, 101, 100, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 32, 47, 32, 80, 111, 115, 105, 116, 105, 111, 110, 97, 108, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 10, 78, 97, 109, 101, 100, 70, 117, 110, 99, 116, 105, 111, 110, 65, 114, 103, 117, 109, 101, 110, 116, 32, 60, 45, 32, 84, 121, 112, 101, 70, 117, 110, 99, 78, 97, 109, 101, 32, 78, 97, 109, 101, 100, 80, 97, 114, 97, 109, 101, 116, 101, 114, 65, 115, 115, 105, 103, 110, 109, 101, 110, 116, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, diff --git a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp index 95f715f2f..8f5e99fef 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp @@ -96,6 +96,7 @@ enum class PEGRuleId : uint32_t { ReservedFunctionName, ReservedTypeName, TableFunctionName, + ReservedTableFunctionName, ConstraintName, SequenceName, CollationName, @@ -626,8 +627,6 @@ enum class PEGRuleId : uint32_t { SingleExpression, Expression, ColumnDefaultExpr, - LambdaArrowExpression, - SingleArrowPair, LogicalOrExpression, LogicalOrExpressionTail, ColDefOrExpr, @@ -699,6 +698,12 @@ enum class PEGRuleId : uint32_t { OtherOperatorTail, AnyAllSubqueryTail, OtherOperatorExpressionTail, + SingleArrowTail, + SingleArrowBody, + ArrowChainBody, + ArrowChainTail, + DoubleArrowTail, + ArrowFullBody, OtherOperator, AnyAllParsedOperator, NamedOtherOperator, @@ -1033,6 +1038,8 @@ enum class PEGRuleId : uint32_t { TableFunctionAliasColon, WithOrdinality, QualifiedTableFunction, + CatalogReservedSchemaTableFunctionName, + TableFunctionNameAsQualifiedName, TableFunctionArguments, FunctionArgument, NamedFunctionArgument, 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 97dd55f69..a5825dccd 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 @@ -90,6 +90,7 @@ struct GroupByExpressionInfo { //===--------------------------------------------------------------------===// DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.AddColumnEntry", AddColumnEntry); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.AnalyzeTarget", AnalyzeTarget); +DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.ArrowBody", ArrowBody); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.BetweenInLikeOperator", BetweenInLikeOperator); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.BinaryExpressionTail", BinaryExpressionTail); DUCKDB_REGISTER_TRANSFORM_RESULT_TYPE("duckdb.transform_result.CaseCheck", CaseCheck); @@ -1796,10 +1797,6 @@ class PEGTransformerFactory { FinalizeMeasureSemanticsExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnDefaultExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeSingleArrowPairTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalOrExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr @@ -1920,6 +1917,14 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeOtherOperatorExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeSingleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeArrowChainBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeDoubleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr FinalizeArrowFullBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeAnyAllParsedOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNamedOtherOperatorTrampoline(PEGTransformer &transformer, @@ -2426,8 +2431,11 @@ class PEGTransformerFactory { FinalizeTableFunctionAliasColonTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeWithOrdinalityTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeQualifiedTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); + static arena_ptr + FinalizeCatalogReservedSchemaTableFunctionNameTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr + FinalizeTableFunctionNameAsQualifiedNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeTableFunctionArgumentsTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeNamedFunctionArgumentTrampoline(PEGTransformer &transformer, @@ -3643,11 +3651,6 @@ class PEGTransformerFactory { static unique_ptr TransformColumnDefaultExpr(PEGTransformer &transformer, unique_ptr col_def_or_expr); static unique_ptr - TransformLambdaArrowExpression(PEGTransformer &transformer, unique_ptr logical_or_expression, - optional>> single_arrow_pair); - static unique_ptr TransformSingleArrowPair(PEGTransformer &transformer, - unique_ptr logical_or_expression); - static unique_ptr TransformLogicalOrExpression(PEGTransformer &transformer, unique_ptr logical_and_expression, optional>> logical_or_expression_tail); static unique_ptr @@ -3762,6 +3765,14 @@ class PEGTransformerFactory { static OtherOperatorTail TransformOtherOperatorExpressionTail(PEGTransformer &transformer, ParsedOperator other_operator, unique_ptr bitwise_expression); + static OtherOperatorTail TransformSingleArrowTail(PEGTransformer &transformer, ArrowBody single_arrow_body); + static ArrowBody TransformArrowChainBody(PEGTransformer &transformer, + unique_ptr bitwise_expression, + vector arrow_chain_tail); + static OtherOperatorTail TransformDoubleArrowTail(PEGTransformer &transformer, + unique_ptr bitwise_expression); + static ArrowBody TransformArrowFullBody(PEGTransformer &transformer, + unique_ptr logical_or_expression); static ParsedOperator TransformAnyAllParsedOperator(PEGTransformer &transformer, const pair &any_all_operator); static ParsedOperator TransformNamedOtherOperator(PEGTransformer &transformer, const string &child); @@ -4303,10 +4314,11 @@ class PEGTransformerFactory { const optional &with_ordinality, optional> sample_clause); static bool TransformWithOrdinality(PEGTransformer &transformer); - static QualifiedName TransformQualifiedTableFunction(PEGTransformer &transformer, - const optional &catalog_qualification, - const optional> &schema_qualification, - const Identifier &table_function_name); + static QualifiedName TransformCatalogReservedSchemaTableFunctionName( + PEGTransformer &transformer, const Identifier &catalog_qualification, + const optional> &schema_qualification, const Identifier &reserved_table_function_name); + static QualifiedName TransformTableFunctionNameAsQualifiedName(PEGTransformer &transformer, + const Identifier &table_function_name); static vector TransformTableFunctionArguments(PEGTransformer &transformer, optional> function_argument); static FunctionArgument TransformNamedFunctionArgument(PEGTransformer &transformer, diff --git a/src/duckdb/src/include/duckdb/planner/binder.hpp b/src/duckdb/src/include/duckdb/planner/binder.hpp index 00b716e5c..746079f3f 100644 --- a/src/duckdb/src/include/duckdb/planner/binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/binder.hpp @@ -98,6 +98,8 @@ struct TrySubqueryPlanIndexes { bool recorded = false; //! The select list projection TableIndex projection_index; + //! The projection that restores the select list above the aggregate of a DISTINCT, only set for DISTINCT + TableIndex distinct_index; //! The prune projection above the result modifiers, only set when pruning is needed TableIndex prune_index; //! The aggregate node of the select node @@ -609,6 +611,9 @@ class Binder : public enable_shared_from_this { BoundStatement BindNode(CopyQueryNode &node); unique_ptr VisitQueryNode(BoundQueryNode &node, unique_ptr root); + //! Plans a DISTINCT (ON) as an aggregate that groups on the targets and takes the first value of other columns + unique_ptr PlanDistinct(BoundDistinctModifier &distinct, optional_ptr order, + unique_ptr root); unique_ptr CreatePlan(BoundSelectNode &statement); unique_ptr CreatePlan(BoundSetOperationNode &node); unique_ptr CreatePlan(BoundQueryNode &node); diff --git a/src/duckdb/src/include/duckdb/planner/bound_tokens.hpp b/src/duckdb/src/include/duckdb/planner/bound_tokens.hpp index 31d5dc8b7..e6a433aed 100644 --- a/src/duckdb/src/include/duckdb/planner/bound_tokens.hpp +++ b/src/duckdb/src/include/duckdb/planner/bound_tokens.hpp @@ -14,6 +14,8 @@ namespace duckdb { // Query Node //===--------------------------------------------------------------------===// class BoundQueryNode; +class BoundDistinctModifier; +class BoundOrderModifier; class BoundSelectNode; class BoundSetOperationNode; diff --git a/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp b/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp index 57d6c9386..32a484431 100644 --- a/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp +++ b/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp @@ -50,6 +50,8 @@ class ColumnQualifier { optional_ptr> lambda_bindings; optional_ptr alias_binder; optional_ptr having_binder; + //! The parameters of enclosing keyword-syntax lambdas, pushed while qualifying their bodies + vector definite_lambda_params; private: unique_ptr QualifyColumnNameWithManyDotsInternal(ColumnRefExpression &col_ref, ErrorData &error, @@ -58,6 +60,8 @@ class ColumnQualifier { bool TableBindingExists(const BindingAlias &alias); //! Whether any binding in the current bind context has the given table name (ignoring catalog/schema) bool TableNameExists(const Identifier &table_name); + //! Whether the name is a lambda parameter of an enclosing lambda (while qualifying or binding its body) + bool IsActiveLambdaParameter(const Identifier &name); unique_ptr QualifyColumnNameInternal(ColumnRefExpression &col_ref, ErrorData &error); }; diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp index cb3643fd5..18b800c63 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp @@ -58,6 +58,14 @@ struct BoundCastExpression { //! Returns true if a cast is invertible (i.e. CAST(s -> t -> s) = s for all values of s). This is not true for e.g. //! boolean casts, because that can be e.g. -1 -> TRUE -> 1. This is necessary to prevent some optimizer bugs. static bool CastIsInvertible(const LogicalType &source_type, const LogicalType &target_type); + //! Returns true if every value of the integral source type is exactly representable in the floating target type + static bool IsLosslessIntegralToFloatingCast(const LogicalType &source_type, const LogicalType &target_type); + //! Returns true if CAST(s -> t -> s) = s for all values of s, possibly without preserving their order (e.g. INTEGER + //! -> VARCHAR). An (in)equality comparison of the cast with a constant can then be applied to the source values. + static bool CastIsInvertibleForEquality(const LogicalType &source_type, const LogicalType &target_type); + //! Returns the source value s with CAST(s) = constant, or nullopt if the constant does not round-trip exactly + static optional TryInvertConstant(ClientContext &context, const BoundFunctionExpression &cast_expr, + const Value &constant); //! Returns true if a cast from source_type to target_type can throw a runtime error static bool CastCanThrow(const LogicalType &source_type, const LogicalType &target_type, bool try_cast); diff --git a/src/duckdb/src/include/duckdb/planner/expression_binder/match_recognize_binder.hpp b/src/duckdb/src/include/duckdb/planner/expression_binder/match_recognize_binder.hpp index 850870744..15f46cf7f 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_binder/match_recognize_binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_binder/match_recognize_binder.hpp @@ -220,7 +220,7 @@ struct MatchRecognizeSteppedNavigation { }; //! Peel what the step reads with off its argument, leaving the expression the row it reaches supplies -MatchRecognizeSteppedNavigation MatchRecognizePeelStep(unique_ptr &inner); +MatchRecognizeSteppedNavigation MatchRecognizePeelStep(Context &context, unique_ptr &inner); //! A step starts from a row the match names, and a step inside one names no row, so refuse the nesting void MatchRecognizeRejectNestedStep(const ParsedExpression &inner, const string &function_name); @@ -242,7 +242,8 @@ string MatchRecognizeNavigationVariable(unique_ptr &inner, con //! FIRST() and LAST() count from the end of the match they read from, by a constant the two clauses //! spell the same way. -idx_t MatchRecognizeNavigationOffset(const string &function_name, const ParsedExpression &offset_expr); +idx_t MatchRecognizeNavigationOffset(Context &context, const string &function_name, + const ParsedExpression &offset_expr); //! One field of the matcher's state, read from the column it travels in unique_ptr MatchRecognizeStateField(const string &state, const string &field); diff --git a/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp b/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp index a60cd69e0..fba1c7345 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp @@ -35,12 +35,12 @@ class LogicalOperatorVisitor { const std::function *child)> &callback); //! Return the projection map owned by an operator for the given child, if any static optional_ptr> GetProjectionMap(LogicalOperator &op, idx_t child_index); - -protected: //! Preserve the selected binding identities after a child rewrite changes its output layout static void RemapProjectionMap(vector &projection_map, const vector &child_bindings_before, const vector &child_bindings_after); + +protected: //! Automatically calls the Visit method for LogicalOperator children of the current operator. Can be overloaded to //! change this behavior. void VisitOperatorChildren(LogicalOperator &op); diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp index 39574d026..cedaa4c11 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp @@ -44,6 +44,8 @@ class LogicalAggregate : public LogicalOperator { vector> group_stats; //! Whether the inputs to all expression are non-NULL TupleDataValidityType distinct_validity; + //! Whether each group takes its first row in input order (DISTINCT ON without ORDER BY) + bool preserve_input_order = false; public: InsertionOrderPreservingMap ParamsToString() const override; diff --git a/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp b/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp index 8e74f37ea..25924eed0 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp @@ -70,6 +70,8 @@ class FlattenDependentJoins { void InvalidateAccessCache(); //! Checks whether a subtree must be evaluated in this flattener's active domain. bool RequiresDomain(LogicalOperator &op) const; + //! Checks whether a join's condition operands owned by the given side pin that child to the domain. + bool JoinOperandRequiresDomain(LogicalOperator &op, idx_t side) const; SubtreeAccess GetSubtreeAccess(LogicalOperator &op) const; idx_t GetDelimKeyIndex(idx_t index) const; @@ -135,8 +137,6 @@ class FlattenDependentJoins { UnnestingState PushDownWindow(unique_ptr &plan, bool propagate_null_values, vector state); UnnestingState PushDownSetOperation(unique_ptr &plan, vector state); - UnnestingState PushDownDistinct(unique_ptr &plan, bool propagate_null_values, - vector state); UnnestingState PushDownExpressionGet(unique_ptr &plan, bool propagate_null_values, vector state); UnnestingState PushDownDML(unique_ptr &plan, bool propagate_null_values, diff --git a/src/duckdb/src/include/duckdb/planner/subquery/recursive_dependent_join_planner.hpp b/src/duckdb/src/include/duckdb/planner/subquery/recursive_dependent_join_planner.hpp index 9e253e2d2..f1422cb9b 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/recursive_dependent_join_planner.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/recursive_dependent_join_planner.hpp @@ -40,6 +40,7 @@ class RecursiveDependentJoinPlanner : public LogicalOperatorVisitor { JoinType join_type); BindingReplacementGraph PlanOperator(unique_ptr &op); BindingReplacementGraph PlanAnyJoinCondition(unique_ptr &op); + BindingReplacementGraph NormalizeJoinConditionOperands(unique_ptr &op); void PlanJoinChildFilters(LogicalOperator &op); void PlanJoinExpressions(LogicalOperator &op); void PlanJoinSubqueries(LogicalJoin &join, unique_ptr &expr, JoinSide uncorrelated_side); diff --git a/src/duckdb/src/include/duckdb/storage/statistics/array_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/array_stats.hpp index 20660bd64..1babbc18b 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/array_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/array_stats.hpp @@ -20,6 +20,7 @@ class Vector; class Serializer; class Deserializer; class Value; +class StatsStructFields; struct ArrayStats { DUCKDB_API static void Construct(BaseStatistics &stats); @@ -33,7 +34,9 @@ struct ArrayStats { DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); - DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats, bool exact); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other, StatsMergeType merge_type = StatsMergeType::MERGE_STATS); 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 140672394..59401e69b 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/base_statistics.hpp @@ -138,8 +138,14 @@ class BaseStatistics { void Verify(const Vector &vector, const SelectionVector &sel, idx_t count, bool ignore_has_null = false) const; void Verify(const Vector &vector, idx_t count) const; - Value ToStruct() const; + //! The statistics as a struct, by default the rendering stats() shows. With exact, the statistics as they are: + //! string bounds are VARCHAR / BLOB values holding their bytes instead of text with \xNN escapes, and geometry + //! statistics list the geometry types the column holds + Value ToStruct(bool exact = false) const; string ToString() const; + //! Sets the parts of the statistics a struct (or VARIANT object) in the shape ToStruct produces describes; + //! `path` prefixes the field names in error messages + DUCKDB_API void SetFromStruct(const Value &value, const string &path = string()); idx_t GetDistinctCount(); static BaseStatistics FromConstant(const Value &input); diff --git a/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp index b870f59f2..5c54c5f96 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp @@ -15,6 +15,7 @@ namespace duckdb { class BaseStatistics; +class StatsStructFields; struct SelectionVector; class GeometryTypeSet { @@ -338,7 +339,9 @@ struct GeometryStats { DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); - DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats, bool exact); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); DUCKDB_API static void Update(BaseStatistics &stats, const string_t &value); DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other); diff --git a/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp index 66021f686..da4518733 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/list_stats.hpp @@ -19,6 +19,7 @@ class BaseStatistics; struct SelectionVector; class Vector; class Value; +class StatsStructFields; struct ListStatsData { //! Whether or not the minimum list length is known @@ -74,7 +75,9 @@ struct ListStats { DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); - DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats, bool exact); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other, StatsMergeType merge_type = StatsMergeType::MERGE_STATS); diff --git a/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp index 5038b16b2..10a863be5 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/numeric_stats.hpp @@ -24,6 +24,7 @@ class BaseStatistics; struct SelectionVector; class Vector; class Value; +class StatsStructFields; struct NumericStatsData { //! Whether or not the value has a max value @@ -86,6 +87,8 @@ struct NumericStats { DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &stats); DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); template static inline void UpdateValue(T new_value, T &min, T &max) { diff --git a/src/duckdb/src/include/duckdb/storage/statistics/stats_struct_fields.hpp b/src/duckdb/src/include/duckdb/storage/statistics/stats_struct_fields.hpp new file mode 100644 index 000000000..32330b878 --- /dev/null +++ b/src/duckdb/src/include/duckdb/storage/statistics/stats_struct_fields.hpp @@ -0,0 +1,53 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/storage/statistics/stats_struct_fields.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/types/value.hpp" + +namespace duckdb { + +//! The fields of a struct value in the shape BaseStatistics::ToStruct produces, read by name (or index) +class StatsStructFields { +public: + //! Throws unless the value is a non-NULL STRUCT (a VARIANT object is converted); `path` names it in errors + DUCKDB_API StatsStructFields(const Value &value, string path); + +public: + //! The non-NULL value of a field, or nullptr when the struct has no such field or it is NULL + DUCKDB_API optional_ptr Get(const string &name); + //! The value of a field cast to `type`; false when it is absent or NULL, throws when it does not cast + DUCKDB_API bool TryGet(const string &name, const LogicalType &type, Value &result); + + DUCKDB_API idx_t FieldCount() const; + DUCKDB_API const string &FieldName(idx_t index) const; + //! The value of a field by index, which counts as read; nullptr when it is NULL + DUCKDB_API optional_ptr FieldValue(idx_t index); + //! The type of a field's value (of what a VARIANT holds), which does not count as read + DUCKDB_API LogicalType FieldType(idx_t index) const; + + //! The dotted path of this struct, and of one of its fields, for error messages + DUCKDB_API const string &Path() const; + DUCKDB_API string FieldPath(const string &name) const; + //! Throws an InvalidInputException about this struct, or about one of its fields + [[noreturn]] DUCKDB_API void Throw(const string &problem) const; + [[noreturn]] DUCKDB_API void Throw(const string &name, const string &problem) const; + //! Throws for fields that were never read: statistics of `type` have no such part + DUCKDB_API void VerifyAllRead(const LogicalType &type) const; + + //! A VARIANT value as a plain value (objects become STRUCTs, arrays LISTs); other values unchanged + DUCKDB_API static Value Plain(const Value &value); + +private: + Value value; + string path; + vector read; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/statistics/string_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/string_stats.hpp index 5e9bfd039..ef8d3baae 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/string_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/string_stats.hpp @@ -20,6 +20,7 @@ class BaseStatistics; struct SelectionVector; class Vector; class Value; +class StatsStructFields; template struct StatsWriter; @@ -112,7 +113,9 @@ struct StringStats { DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); - DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats, bool exact); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type, array_ptr constants); diff --git a/src/duckdb/src/include/duckdb/storage/statistics/struct_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/struct_stats.hpp index 5e00d14d0..9748ec86a 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/struct_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/struct_stats.hpp @@ -18,6 +18,7 @@ class BaseStatistics; struct SelectionVector; class Vector; class Value; +class StatsStructFields; struct StorageIndex; struct StructStats { @@ -34,7 +35,9 @@ struct StructStats { DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); - DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats, bool exact); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other, StatsMergeType merge_type = StatsMergeType::MERGE_STATS); diff --git a/src/duckdb/src/include/duckdb/storage/statistics/variant_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/variant_stats.hpp index 654e8798c..098b7b57b 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/variant_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/variant_stats.hpp @@ -16,6 +16,7 @@ namespace duckdb { class BaseStatistics; class Value; +class StatsStructFields; enum class VariantStatsShreddingState : uint8_t { //! Uninitialized, not unshredded/shredded @@ -106,7 +107,9 @@ struct VariantStats { DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer); DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base); - DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats); + DUCKDB_API static child_list_t ToStruct(const BaseStatistics &stats, bool exact); + //! Sets the parts of the statistics the struct fields describe (the inverse of ToStruct) + DUCKDB_API static void SetFromStruct(BaseStatistics &stats, StatsStructFields &fields); DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other); DUCKDB_API static void Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, diff --git a/src/duckdb/src/include/duckdb/storage/storage_options.hpp b/src/duckdb/src/include/duckdb/storage/storage_options.hpp index 468de410c..5b92eee38 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_options.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_options.hpp @@ -55,7 +55,7 @@ struct StorageOptions { EncryptionTypes::EncryptionVersion encryption_version = EncryptionTypes::NONE; void SetEncryptionVersion(string &storage_version_user_provided); - void Initialize(unordered_map &options); + void Initialize(Context &context, unordered_map &options); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp b/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp index 2bbc078b2..9349682b5 100644 --- a/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp @@ -482,10 +482,12 @@ class SegmentTree { D_ASSERT(segment); // add the node to the list of nodes auto node = make_uniq>(row_start, std::move(segment), nodes.size()); - if (!nodes.empty()) { - nodes.back()->SetNext(*node); - } + auto &new_node = *node; + optional_ptr> previous_node = nodes.empty() ? nullptr : nodes.back().get(); nodes.push_back(std::move(node)); + if (previous_node) { + previous_node->SetNext(new_node); + } } void AppendSegmentInternal(SegmentLock &l, shared_ptr segment) const { idx_t row_start; diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index e55b081a2..4ee4651ce 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1570,6 +1570,21 @@ typedef struct { (duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, const char **column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_expression_check_statistics) + (duckdb_v2_context_handle context, duckdb_v2_expression_handle expression, duckdb_v2_stats_handle stats, + DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_create) + (duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle type, duckdb_v2_stats_handle *stats, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_stats_destroy)(duckdb_v2_stats_handle *stats); + DUCKDB_V2_ERROR(*duckdb_v2_stats_merge) + (duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_assign) + (duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_get_value) + (duckdb_v2_stats_handle stats, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_stats_set_value) + (duckdb_v2_stats_handle stats, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -3583,6 +3598,27 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_statement_add_collection duckdb_ext_api.duckdb_v2_statement_add_collection #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_expression_check_statistics duckdb_ext_api.duckdb_v2_expression_check_statistics +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_stats_create duckdb_ext_api.duckdb_v2_stats_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_stats_destroy duckdb_ext_api.duckdb_v2_stats_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_stats_merge duckdb_ext_api.duckdb_v2_stats_merge +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_stats_assign duckdb_ext_api.duckdb_v2_stats_assign +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_stats_get_value duckdb_ext_api.duckdb_v2_stats_get_value +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_stats_set_value duckdb_ext_api.duckdb_v2_stats_set_value +#endif // capigen:end appended #endif // DUCKDB_BUILD_STATIC_EXTENSION diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index 2ae65767b..f57da675d 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -4831,12 +4831,17 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_schema_destroy(duckdb_v2_schema_handle *s /* --- Types for stats --- */ /*! - * A borrowed opaque handle to the statistics of an expression or a column. A stats callback receives it for the result - * it describes and for each of its arguments; it is valid only for the duration of that callback. + * An opaque handle to the statistics of an expression or a column: whether it can hold NULLs and non-NULL values, a + * minimum and a maximum for numeric and string columns, the statistics of the children of a LIST / ARRAY / STRUCT + * column, the shredding of a VARIANT column and the extent of a GEOMETRY column. * - * The statistics of an argument are read-only, and the setters fail on them. The statistics of the result start out - * unknown, with every kind of value possible, and the callback narrows them through the setters. A callback that leaves - * the result unchanged tells the engine nothing. + * A stats callback receives borrowed statistics for the result it describes and for each of its arguments; they are + * valid only for the duration of that callback. The statistics of an argument are read-only, and the setters fail on + * them. The statistics of the result start out unknown, with every kind of value possible, and the callback narrows + * them through the setters. A callback that leaves the result unchanged tells the engine nothing. + * + * Statistics created with `duckdb_v2_stats_create()` are owned by the caller: they start out unknown, are narrowed with + * the setters, combined with `duckdb_v2_stats_merge()`, and destroyed with `duckdb_v2_stats_destroy()`. */ typedef struct _duckdb_v2_stats { void *internal_ptr; @@ -4928,6 +4933,189 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_set_can_have_valid(duckdb_v2_stats_ duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the statistics as a STRUCT value with one field per known statistic, the shape the SQL function `stats()` + * shows for the same statistics: `stats(42)` for example gives `{'min': 42, 'max': 42, 'has_null': false, + * 'has_no_null': true, 'approx_unique': 1}`. Every field keeps the type of what it describes, so a bound is a value of + * the column's type: a DATE for a DATE column, a DECIMAL for a DECIMAL column. Read the fields with + * `duckdb_v2_value_get_child_count()` and `duckdb_v2_value_get_child()`, and their names from the struct type + * (`duckdb_v2_value_get_logical_type()`, `duckdb_v2_logical_type_get_param()`). + * + * Every statistics struct has `has_null` and `has_no_null` (whether NULLs and non-NULL values can occur) and, when + * known, `approx_unique` (the estimated number of distinct values). The other fields depend on the type, and a field is + * absent when that statistic is unknown: + * + * - numeric types (integers, floating point numbers, DECIMAL, dates, times, timestamps, INTERVAL, UUID, BOOLEAN): `min` + * and `max`, values of the column's type; + * - VARCHAR and BLOB: `min` and `max` (bounds in binary order, possibly truncated prefixes), `has_unicode`, + * `min_string_length`, `max_string_length` and `total_string_length`. A bound holds its bytes as they are: as a VARCHAR + * for a VARCHAR column, unless a truncated prefix is not valid UTF-8, in which case it is a BLOB; as a BLOB for a BLOB + * column. (`stats()` instead renders string bounds as text, with `\xNN` escapes for bytes outside printable ASCII); + * - LIST: `min_list_length`, `max_list_length` and `total_list_length`, and `child_stats`, the statistics struct of the + * elements; + * - ARRAY: `child_stats`, the statistics struct of the elements; + * - STRUCT: `child_stats`, a struct with the statistics of each field by name; a MAP is a LIST of `STRUCT(key, value)` + * entries, so its keys and values are `child_stats.child_stats.key` and `child_stats.child_stats.value`; + * - TUPLE: `child_stats`, a TUPLE with the statistics struct of each element in order (`stats()` shows it as an array); + * - GEOMETRY: `extent`, a struct with the bounding box `x_min`, `x_max`, `y_min`, `y_max` and, when the geometries have + * those coordinates, `z_min`, `z_max`, `m_min`, `m_max`; `types`, the list of geometry types the column holds + * (`'point'`, `'linestring_z'`, `'polygon_m'`, `'multipoint_zm'`, ...; `stats()` does not show this field); and the + * flags `has_empty_geom`, `has_non_empty_geom`, `has_empty_part` and `has_non_empty_part`; + * - VARIANT: `shredding_state` (`'SHREDDED'` when the values are stored in a structured layout, `'NOT_SHREDDED'`, + * `'INCONSISTENT'` or `'UNINITIALIZED'`), and for a shredded column `fully_shredded` and `partially_shredded`: trees + * over the structured layout whose leaves are `{'type': , 'stats': }` for the values + * shredded on that type, whose arrays are `{'child_stats': }` and whose objects hold a node per field. A node + * under `fully_shredded` has every value in the structured layout, so that a filter on it can be answered from its + * statistics; a node under `partially_shredded` also has values that fell back to the generic layout. + * `{'shredding_state': 'SHREDDED', 'fully_shredded': {'x': {'type': 'INTEGER', 'stats': {'min': 1, 'max': 5, + * 'has_null': false, 'has_no_null': true}}}}` describes objects whose field `x` is an INTEGER in [1, 5] throughout. + * + * The returned value is owned by the caller and must be destroyed via `duckdb_v2_value_destroy()`. + * + * history: + * - unstable: v2.0.0 + * + * @param stats The statistics to read. + * @param value Receives the owned STRUCT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_get_value(duckdb_v2_stats_handle stats, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the statistics from a STRUCT value in the shape `duckdb_v2_stats_get_value()` returns: every field whose value + * is not NULL replaces that statistic, a NULL field or an absent one leaves it unchanged. The result statistics of a + * stats callback start out unknown, so `{'min': 20, 'max': 30, 'has_null': false}` on an INTEGER column reports exactly + * those bounds and the absence of NULLs; a nested field such as `child_stats.x` or `extent.z_min` narrows that part + * only, and a `fully_shredded` / `partially_shredded` tree replaces the shredding of a VARIANT column as a whole. The + * `child_stats` of a TUPLE is a TUPLE (`duckdb_v2_value_create_tuple()`) or a LIST with one statistics struct per + * element in order, a NULL element leaving that element's statistics unchanged; an error names an element + * `child_stats.element1`, `child_stats.element2`, ... + * + * The simplest way to build the value is `duckdb_v2_value_create_struct()` over the fields: for the example above the + * names `min`, `max` and `has_null` with the values of `duckdb_v2_value_create_int()` and + * `duckdb_v2_value_create_bool()`. A bound is a value of the column's type, or one that casts to it: a DATE column + * takes `duckdb_v2_value_create_date()` or the VARCHAR `'2024-01-01'`, but not a number. A string bound is taken as it + * is: the bytes of a VARCHAR or BLOB value are the bound, nothing in them is interpreted (`'C:\temp'` is the seven + * characters it shows), and a bound may be a truncated prefix, as a file format stores them. A geometry `types` list + * names the types the column holds with the names `duckdb_v2_stats_get_value()` returns; a shredded `type` is a type + * name such as `'INTEGER'` or `'DECIMAL(10, 2)'`. + * + * The output of the SQL function `stats()` is accepted too: a VARIANT is read as the struct it holds, with the field + * values cast as above. Note that `stats()` renders string bounds as text, with `\xNN` escapes for bytes outside + * printable ASCII, and that text is the bound it sets; copy exact bounds with `duckdb_v2_stats_get_value()`. + * + * Each statistic states what can occur: a bound that excludes a value the scan then produces, or `has_null: false` for + * a column with NULLs, produces wrong query results. + * + * Fails with `ERROR_INPUT_INVALID` for a NULL value, a value that is not a STRUCT (or a VARIANT holding one), a field + * the statistics of the type do not have, a field whose value does not convert (the message names the field, e.g. + * `child_stats.a.min`), or read-only statistics such as those of an argument. A failure leaves the statistics as they + * were. + * + * history: + * - unstable: v2.0.0 + * + * @param stats The statistics to set. + * @param value The statistics as a STRUCT value, or the output of `stats()`. Borrowed. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_set_value(duckdb_v2_stats_handle stats, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates the statistics of a column of the given type through a factory. + * + * The statistics start out unknown: they claim nothing about the values (NULLs and non-NULL values may occur, no + * bounds, and the statistics of the children of a nested type are unknown too). Narrow them with + * `duckdb_v2_stats_set_value()`, `duckdb_v2_stats_set_can_have_null()` and `duckdb_v2_stats_set_can_have_valid()`. The + * caller owns the returned handle and must destroy it with `duckdb_v2_stats_destroy()`. A stats callback does not need + * this: it narrows the result statistics it receives in place. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the statistics through. + * @param type The type of the column the statistics describe. Borrowed and copied. + * @param stats On success, receives the newly created statistics. Owned by the caller. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_create(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle type, duckdb_v2_stats_handle *stats, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys statistics created with `duckdb_v2_stats_create()`, releasing their resources. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Fails with `ERROR_INPUT_INVALID` for the borrowed statistics a stats callback receives, which the + * engine owns. Statistics that were merged into or assigned to others were copied, so destroying them afterwards does + * not affect those. + * + * history: + * - unstable: v2.0.0 + * + * @param stats The statistics to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_destroy(duckdb_v2_stats_handle *stats); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Merges the statistics of another part of the column into these: afterwards the statistics hold for the values of both + * parts together (the bounds widen, NULLs can occur when they can in either, the children are merged, a VARIANT + * shredded differently in the two parts becomes inconsistently shredded). This is how the statistics of the row groups + * of a file are combined into those of the file. Both must be of the same type; `other` is borrowed and left unchanged. + * Fails with `ERROR_INPUT_INVALID` for statistics of different types or read-only statistics. + * + * history: + * - unstable: v2.0.0 + * + * @param stats The statistics to widen. + * @param other The statistics of the other part of the column. Borrowed. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_merge(duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Replaces the statistics with a copy of `other`: afterwards they claim exactly what `other` claims, nothing that was + * set before remains. This is how a stats callback hands the engine statistics the function built with + * `duckdb_v2_stats_create()`, e.g. combined from the files of a scan with `duckdb_v2_stats_merge()`. Both must be of + * the same type; `other` is borrowed and left unchanged. Fails with `ERROR_INPUT_INVALID` for statistics of different + * types or read-only statistics. + * + * history: + * - unstable: v2.0.0 + * + * @param stats The statistics to replace. + * @param other The statistics to copy. Borrowed. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_stats_assign(duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, + duckdb_v2_error_info_handle *err); +#endif + /* --- Struct definitions for stats --- */ /* ============================================================================ @@ -8752,6 +8940,28 @@ typedef enum DUCKDB_V2_EXPRESSION_TYPE { DUCKDB_V2_EXPRESSION_TYPE_MAX_ENUM = 0x7FFFFFFF, } DUCKDB_V2_EXPRESSION_TYPE; +/*! + * What checking a predicate against the statistics of its column found out (`FilterPropagateResult`): whether every row + * the statistics describe passes the predicate, none does, or the statistics do not tell. + */ +typedef enum DUCKDB_V2_FILTER_PROPAGATE_RESULT { + //! The statistics do not decide the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_NO_PRUNING_POSSIBLE = 0, + + //! Every row passes the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_TRUE = 1, + + //! No row passes the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_FALSE = 2, + + //! Every row passes the predicate or evaluates it to NULL. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_TRUE_OR_NULL = 3, + + //! No row passes the predicate: each evaluates it to false or to NULL. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_FALSE_OR_NULL = 4, + DUCKDB_V2_FILTER_PROPAGATE_RESULT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_FILTER_PROPAGATE_RESULT; + /* --- Struct forward declarations for expression --- */ /* --- Types for expression --- */ @@ -8965,6 +9175,33 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_cast_get_mode(duckdb_v2_expres duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Checks a predicate over one column against the statistics of that column (`ExpressionFilter::CheckStatistics`): the + * statistics of the column are propagated through the expression - comparisons, conjunctions, IS NULL, IN, casts and + * the functions the engine knows the statistics of - to find out whether every row the statistics describe passes the + * predicate, none does, or nothing can be told. A table function uses it to skip a row group (or a file) whose + * statistics, built with `duckdb_v2_stats_create()`, make a pushed-down filter it did not take over false for every + * row. Every column reference of the predicate stands for the column described by `stats`. + * + * history: + * - unstable: v2.0.0 + * + * @param context The context of the query; the statistics of function calls in the predicate are derived through it. + * @param expression The predicate: a boolean expression over one column, referenced by its column references. + * @param stats The statistics of that column over the rows in question. + * @param result Receives what the statistics decide about the predicate. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_check_statistics(duckdb_v2_context_handle context, + duckdb_v2_expression_handle expression, + duckdb_v2_stats_handle stats, + DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, + duckdb_v2_error_info_handle *err); +#endif + /* --- Struct definitions for expression --- */ /* ============================================================================ @@ -13033,7 +13270,8 @@ typedef struct _duckdb_v2_table_function_partition_data_info { /*! * A borrowed opaque handle to the arguments supplied to a table function during the "stats" phase of query * optimization. The engine invokes the callback once per column the query reads, and the callback can use the handle to - * narrow the statistics of that column. + * find out which column is asked about and to report what it knows about the column's values (its minimum and maximum, + * whether it holds NULLs, ...) by narrowing the statistics of that column. */ typedef struct _duckdb_v2_table_function_stats_info { void *internal_ptr; @@ -13461,9 +13699,15 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_partitioning_callback( /*! * Sets the optional stats callback of the table function. * - * The stats callback is invoked during query optimization once for each declared column the query reads. Through its - * `duckdb_v2_table_function_stats_info_handle` it narrows the statistics of that column, which the engine then uses to - * simplify the query. A function without a stats callback gives the engine no statistics for its columns. + * The stats callback is invoked during query optimization once for each declared column the query reads, when the + * engine wants to know about the column's values without reading them - e.g. to prune a scan whose filter no value can + * satisfy, to answer `min()` / `max()` from the statistics, or to estimate the selectivity of a filter. Through its + * `duckdb_v2_table_function_stats_info_handle` the callback narrows the statistics of that column (see + * `duckdb_v2_table_function_stats_get_result_stats()`): its minimum and maximum, whether it holds NULLs, the statistics + * of the children of a nested column, ... Leaving the statistics unchanged tells the engine nothing about the column. + * The statistics must hold for every row the call produces: a bound that excludes a value the scan then produces leads + * to wrong results. A function without a stats callback gives the engine no statistics for its columns. The callback is + * only asked about whole declared columns, never about virtual columns or about fields extracted from a column. * * history: * - unstable: v2.0.0 @@ -14499,7 +14743,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_bind_data( * Returns which declared column the statistics describe. * * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order. + * order. It is never the index of a virtual column or of a field extracted from a column; the callback is not asked + * about those. * * history: * - unstable: v2.0.0 @@ -14518,8 +14763,13 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_column_index( /*! * Retrieves the statistics of the column, for the callback to narrow. * - * The statistics start out unknown, with every kind of value possible. They describe every value the scan produces for - * the column. Borrowed; valid only for the duration of the callback. + * The statistics start out unknown, with every kind of value possible, and are of the column's type as the bind + * callback declared it. The callback narrows them with `duckdb_v2_stats_set_value()`, from a STRUCT value in the shape + * `duckdb_v2_stats_get_value()` returns - e.g. `{'min': 20, 'max': 30, 'has_null': false}` for an INTEGER column, or + * the statistics of the fields of a STRUCT column under `child_stats` - and with `duckdb_v2_stats_set_can_have_null()` + * / `duckdb_v2_stats_set_can_have_valid()`. Statistics built with `duckdb_v2_stats_create()`, e.g. combined from the + * files of a scan with `duckdb_v2_stats_merge()`, are copied in with `duckdb_v2_stats_assign()`. They describe every + * value the scan produces for the column. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 diff --git a/src/duckdb/src/main/attached_database.cpp b/src/duckdb/src/main/attached_database.cpp index a6253e5f8..1e477ed60 100644 --- a/src/duckdb/src/main/attached_database.cpp +++ b/src/duckdb/src/main/attached_database.cpp @@ -56,20 +56,21 @@ string AttachOptions::OptionSetting(const string &name) { return lower; } -AttachOptions::AttachOptions(const unordered_map &attach_options, const AccessMode default_access_mode) +AttachOptions::AttachOptions(Context &context, const unordered_map &attach_options, + const AccessMode default_access_mode) : access_mode(default_access_mode) { for (auto &entry : attach_options) { auto access_mode_option = ACCESS_MODE_OPTIONS.find(entry.first); if (access_mode_option != ACCESS_MODE_OPTIONS.end()) { // Extract the access mode; the option reads inverted for the readwrite spellings. - auto value = BooleanValue::Get(entry.second.DefaultCastAs(LogicalType::BOOLEAN)); + auto value = BooleanValue::Get(entry.second.CastAs(context, LogicalType::BOOLEAN)); access_mode = value == access_mode_option->second ? AccessMode::READ_ONLY : AccessMode::READ_WRITE; continue; } if (entry.first == "recovery_mode") { // Extract the recovery mode. - auto mode_str = StringValue::Get(entry.second.DefaultCastAs(LogicalType::VARCHAR)); + auto mode_str = StringValue::Get(entry.second.CastAs(context, LogicalType::VARCHAR)); recovery_mode = EnumUtil::FromString(mode_str); continue; } @@ -78,17 +79,17 @@ AttachOptions::AttachOptions(const unordered_map &attach_options, // Extract the database type. Normalize case so that // `TYPE sqlite` and `TYPE 'SQLite'` are equivalent. // `TYPE sqlite` and `TYPE 'sqlite3'` are NOT equivalent, aliasing to be applied on comparison - db_type = StringUtil::Lower(StringValue::Get(entry.second.DefaultCastAs(LogicalType::VARCHAR))); + db_type = StringUtil::Lower(StringValue::Get(entry.second.CastAs(context, LogicalType::VARCHAR))); continue; } if (entry.first == "default_table") { - default_table = QualifiedName::Parse(StringValue::Get(entry.second.DefaultCastAs(LogicalType::VARCHAR))); + default_table = QualifiedName::Parse(StringValue::Get(entry.second.CastAs(context, LogicalType::VARCHAR))); continue; } if (entry.first == "hidden") { - auto is_hidden = BooleanValue::Get(entry.second.DefaultCastAs(LogicalType::BOOLEAN)); + auto is_hidden = BooleanValue::Get(entry.second.CastAs(context, LogicalType::BOOLEAN)); if (is_hidden) { visibility = AttachVisibility::HIDDEN; } @@ -96,7 +97,7 @@ AttachOptions::AttachOptions(const unordered_map &attach_options, } if (entry.first == "vacuum_rebuild_indexes") { - const auto threshold = UBigIntValue::Get(entry.second.DefaultCastAs(LogicalType::UBIGINT)); + const auto threshold = UBigIntValue::Get(entry.second.CastAs(context, LogicalType::UBIGINT)); try { vacuum_rebuild_indexes_threshold = threshold; } catch (InternalException &e) { @@ -125,7 +126,8 @@ AttachedDatabase::AttachedDatabase(DatabaseInstance &db, AttachedDatabaseType ty D_ASSERT(type == AttachedDatabaseType::TEMP_DATABASE || type == AttachedDatabaseType::SYSTEM_DATABASE); if (type == AttachedDatabaseType::TEMP_DATABASE) { unordered_map options; - AttachOptions attach_options(options, AccessMode::READ_WRITE); + auto services = db.Services(); + AttachOptions attach_options(*services, options, AccessMode::READ_WRITE); options["storage_version"] = "latest"; storage = make_uniq(*this, string(IN_MEMORY_PATH), attach_options); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp b/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp index f86af63db..023e6f1b0 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_expression.cpp @@ -1,9 +1,13 @@ #include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/common/enums/filter_propagate_result.hpp" namespace duckdb::capiv2 { @@ -109,6 +113,49 @@ static auto CV2ExpressionRequireFunction(const Expression &expression, const cha return expression.Cast().Function(); } +// The public enum mirrors FilterPropagateResult numerically, so the mapping below is a plain cast. +#define CV2_ASSERT_FILTER_PROPAGATE(NAME, V2_NAME) \ + static_assert(static_cast(FilterPropagateResult::NAME) == DUCKDB_V2_FILTER_PROPAGATE_RESULT_##V2_NAME, \ + "FILTER_PROPAGATE_RESULT numeric drift: " #NAME) +CV2_ASSERT_FILTER_PROPAGATE(NO_PRUNING_POSSIBLE, NO_PRUNING_POSSIBLE); +CV2_ASSERT_FILTER_PROPAGATE(FILTER_ALWAYS_TRUE, ALWAYS_TRUE); +CV2_ASSERT_FILTER_PROPAGATE(FILTER_ALWAYS_FALSE, ALWAYS_FALSE); +CV2_ASSERT_FILTER_PROPAGATE(FILTER_TRUE_OR_NULL, TRUE_OR_NULL); +CV2_ASSERT_FILTER_PROPAGATE(FILTER_FALSE_OR_NULL, FALSE_OR_NULL); +#undef CV2_ASSERT_FILTER_PROPAGATE + +//! The predicate may refer to one column only, the one the statistics describe, and that column must have their type +static void CV2CheckPredicateColumn(const Expression &expr, const LogicalType &stats_type, + optional_ptr &seen) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &colref = expr.Cast(); + if (seen && seen->Binding() != colref.Binding()) { + throw InvalidInputException("duckdb_v2_expression_check_statistics: the predicate refers to more than one " + "column, the statistics describe a single column"); + } + if (colref.GetReturnType() != stats_type) { + throw InvalidInputException("duckdb_v2_expression_check_statistics: the statistics are of type %s, the " + "column the predicate refers to is of type %s", + stats_type.ToString(), colref.GetReturnType().ToString()); + } + seen = &colref; + return; + } + ExpressionIterator::EnumerateChildren( + expr, [&](const Expression &child) { CV2CheckPredicateColumn(child, stats_type, seen); }); +} + +//! Replaces every column reference of a predicate with a reference to the single column described by the statistics: +//! a predicate over one column refers to its column by column references, which all stand for that one column. +static void CV2ReplaceColumnRefsWithReference(unique_ptr &expr) { + if (expr->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + expr = make_uniq(expr->GetAlias(), expr->GetReturnType(), 0ULL); + return; + } + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { CV2ReplaceColumnRefsWithReference(child); }); +} + } // namespace duckdb::capiv2 //---------------------------------------------------------------------------------------------------------------------- @@ -221,3 +268,31 @@ DUCKDB_V2_ERROR duckdb_v2_expression_cast_get_mode(duckdb_v2_expression_handle e *mode = duckdb::BoundCastExpression::IsTryCast(cast) ? DUCKDB_V2_CAST_MODE_TRY : DUCKDB_V2_CAST_MODE_NORMAL; }); } + +DUCKDB_V2_ERROR duckdb_v2_expression_check_statistics(duckdb_v2_context_handle context, + duckdb_v2_expression_handle expression, + duckdb_v2_stats_handle stats, + DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(context); + DUCKDB_CHECK_ARG(expression); + DUCKDB_CHECK_ARG(stats); + DUCKDB_CHECK_ARG(result); + *result = DUCKDB_V2_FILTER_PROPAGATE_RESULT_NO_PRUNING_POSSIBLE; + return WithErrorHandler(err, [&]() { + auto &client_context = Convert(context)->context; + const auto &column_stats = Convert(stats)->GetStats(); + const auto &predicate_expr = *Convert(expression); + if (predicate_expr.GetReturnType().id() != duckdb::LogicalTypeId::BOOLEAN) { + throw duckdb::InvalidInputException( + "duckdb_v2_expression_check_statistics: the expression is not a predicate (it is not BOOLEAN)"); + } + duckdb::optional_ptr column; + CV2CheckPredicateColumn(predicate_expr, column_stats.GetType(), column); + auto predicate = predicate_expr.Copy(); + CV2ReplaceColumnRefsWithReference(predicate); + const auto outcome = duckdb::ExpressionFilter::CheckExpressionStatistics( + &client_context, *predicate, duckdb::array_ptr(&column_stats, 1)); + *result = static_cast(outcome); + }); +} diff --git a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp index 1f32709ed..d2b8c7cf9 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp @@ -56,7 +56,8 @@ void CV2Instance::Attach(const string &path, const Identifier &name, if (attach_options) { info.options = attach_options->options; } - AttachOptions options(info.options, instance.config.options.access_mode); + auto services = instance.Services(); + AttachOptions options(*services, info.options, instance.config.options.access_mode); options.original_path = path; if (options.db_type.empty()) { DBPathAndType::ExtractExtensionPrefix(info.path, options.db_type); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_stats.cpp b/src/duckdb/src/main/capi/v2/capi_v2_stats.cpp index 26a7f507d..e5d4adbc8 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_stats.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_stats.cpp @@ -18,6 +18,15 @@ BaseStatistics &CV2Stats::GetMutableStats(const char *function_name) { using namespace duckdb::capiv2; +using duckdb::BaseStatistics; +using duckdb::InvalidInputException; +using duckdb::StatsInfo; +using duckdb::Value; + +//---------------------------------------------------------------------------------------------------------------------- +// Validity +//---------------------------------------------------------------------------------------------------------------------- + DUCKDB_V2_ERROR duckdb_v2_stats_can_have_null(duckdb_v2_stats_handle stats, bool *out, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(stats); @@ -37,7 +46,7 @@ DUCKDB_V2_ERROR duckdb_v2_stats_set_can_have_null(duckdb_v2_stats_handle stats, DUCKDB_CHECK_ARG(stats); return WithErrorHandler(err, [&]() { auto &result = Convert(stats)->GetMutableStats("duckdb_v2_stats_set_can_have_null"); - result.Set(value ? duckdb::StatsInfo::CAN_HAVE_NULL_VALUES : duckdb::StatsInfo::CANNOT_HAVE_NULL_VALUES); + result.Set(value ? StatsInfo::CAN_HAVE_NULL_VALUES : StatsInfo::CANNOT_HAVE_NULL_VALUES); }); } @@ -46,6 +55,105 @@ DUCKDB_V2_ERROR duckdb_v2_stats_set_can_have_valid(duckdb_v2_stats_handle stats, DUCKDB_CHECK_ARG(stats); return WithErrorHandler(err, [&]() { auto &result = Convert(stats)->GetMutableStats("duckdb_v2_stats_set_can_have_valid"); - result.Set(value ? duckdb::StatsInfo::CAN_HAVE_VALID_VALUES : duckdb::StatsInfo::CANNOT_HAVE_VALID_VALUES); + result.Set(value ? StatsInfo::CAN_HAVE_VALID_VALUES : StatsInfo::CANNOT_HAVE_VALID_VALUES); + }); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Statistics as a value +//---------------------------------------------------------------------------------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_stats_get_value(duckdb_v2_stats_handle stats, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stats); + DUCKDB_CHECK_ARG(value); + *value = nullptr; + return WithErrorHandler(err, [&]() { + // the statistics as they are (string bounds as their bytes, geometry types), not the rendering stats() shows + *value = Convert(new Value(Convert(stats)->GetStats().ToStruct(true))); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_stats_set_value(duckdb_v2_stats_handle stats, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stats); + DUCKDB_CHECK_ARG(value); + return WithErrorHandler(err, [&]() { + auto &result = Convert(stats)->GetMutableStats("duckdb_v2_stats_set_value"); + // set a copy so that a refused value leaves the statistics as they were + auto updated = result.Copy(); + updated.SetFromStruct(*Convert(value)); + result = std::move(updated); + }); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Construction +//---------------------------------------------------------------------------------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_stats_create(duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle type, + duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(factory); + DUCKDB_CHECK_ARG(type); + DUCKDB_CHECK_ARG(stats); + *stats = nullptr; + return WithErrorHandler(err, [&]() { + auto type_ref = Convert(type); + const auto &logical_type = *type_ref; + if (logical_type.id() == duckdb::LogicalTypeId::INVALID) { + throw InvalidInputException("duckdb_v2_stats_create: cannot create statistics of an INVALID type"); + } + *stats = Convert(CV2Stats::Owned(BaseStatistics::CreateUnknown(logical_type)).release()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_stats_destroy(duckdb_v2_stats_handle *stats) { + return WithErrorHandler(nullptr, [&]() { + if (!stats || !*stats) { + return; + } + auto handle = Convert(*stats); + if (!handle->IsOwned()) { + throw InvalidInputException("duckdb_v2_stats_destroy: the statistics are borrowed, only statistics from " + "duckdb_v2_stats_create can be destroyed"); + } + delete handle; + *stats = nullptr; + }); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Combining statistics +//---------------------------------------------------------------------------------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_stats_merge(duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stats); + DUCKDB_CHECK_ARG(other); + return WithErrorHandler(err, [&]() { + auto &result = Convert(stats)->GetMutableStats("duckdb_v2_stats_merge"); + auto &other_stats = Convert(other)->GetStats(); + if (result.GetType() != other_stats.GetType()) { + throw InvalidInputException( + "duckdb_v2_stats_merge: cannot merge statistics of type %s into statistics of type %s", + other_stats.GetType().ToString(), result.GetType().ToString()); + } + result.Merge(other_stats); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_stats_assign(duckdb_v2_stats_handle stats, duckdb_v2_stats_handle other, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stats); + DUCKDB_CHECK_ARG(other); + return WithErrorHandler(err, [&]() { + auto &result = Convert(stats)->GetMutableStats("duckdb_v2_stats_assign"); + auto &other_stats = Convert(other)->GetStats(); + if (result.GetType() != other_stats.GetType()) { + throw InvalidInputException( + "duckdb_v2_stats_assign: cannot assign statistics of type %s to statistics of type %s", + other_stats.GetType().ToString(), result.GetType().ToString()); + } + result = other_stats.Copy(); }); } diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index a9ddf600c..e59fd28ff 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -33,13 +33,14 @@ DebugVerificationMode DBConfigOptions::global_verification_mode = DebugVerificat #define DUCKDB_SETTING(_PARAM) \ { \ _PARAM::Name, _PARAM::Description, _PARAM::InputType, nullptr, nullptr, nullptr, nullptr, nullptr, \ - _PARAM::Scope, _PARAM::DefaultValue, nullptr, _PARAM::SettingIndex, _PARAM::IsDebug, _PARAM::IsDeprecated \ + _PARAM::Scope, _PARAM::DefaultValue, nullptr, _PARAM::SettingIndex, _PARAM::IsDebug, _PARAM::IsDeprecated, \ + Settings::GetDefaultValue<_PARAM> \ } #define DUCKDB_SETTING_CALLBACK(_PARAM) \ { \ _PARAM::Name, _PARAM::Description, _PARAM::InputType, nullptr, nullptr, nullptr, nullptr, nullptr, \ _PARAM::Scope, _PARAM::DefaultValue, _PARAM::OnSet, _PARAM::SettingIndex, _PARAM::IsDebug, \ - _PARAM::IsDeprecated \ + _PARAM::IsDeprecated, Settings::GetDefaultValue<_PARAM> \ } #define DUCKDB_GLOBAL(_PARAM) \ { \ @@ -198,6 +199,8 @@ static const ConfigurationOption internal_options[] = { DUCKDB_GLOBAL(HTTPProxySetting), DUCKDB_SETTING(HTTPProxyPasswordSetting), DUCKDB_SETTING(HTTPProxyUsernameSetting), + DUCKDB_SETTING(HTTPRetryQuotaThrottledSetting), + DUCKDB_SETTING(HTTPRetryThrottledWaitMsSetting), DUCKDB_SETTING(IeeeFloatingPointOpsSetting), DUCKDB_SETTING(IgnoreUnknownCrsSetting), DUCKDB_SETTING(ImmediateTransactionModeSetting), @@ -260,7 +263,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_GLOBAL(TempDirectorySetting), DUCKDB_SETTING_CALLBACK(TempFileEncryptionSetting), DUCKDB_GLOBAL(ThreadsSetting), - DUCKDB_LOCAL(TrackedMetricsSetting), + DUCKDB_SETTING_CALLBACK(TrackedMetricsSetting), DUCKDB_SETTING(UsernameSetting), DUCKDB_SETTING_CALLBACK(VacuumRebuildIndexesSetting), DUCKDB_SETTING_CALLBACK(ValidateExternalFileCacheSetting), @@ -882,8 +885,10 @@ SettingLookupResult DBConfig::TryGetDefaultValue(optional_ptrdefault_value) { return SettingLookupResult(); } - auto input_type = ParseLogicalType(option->parameter_type); - result = Value(option->default_value).DefaultCastAs(input_type); + if (!option->get_default_value) { + throw InternalException("Generic setting \"%s\" has no typed default value", option->name); + } + result = option->get_default_value(); return SettingLookupResult(SettingScope::GLOBAL); } diff --git a/src/duckdb/src/main/extension/extension_helper.cpp b/src/duckdb/src/main/extension/extension_helper.cpp index 072bffe4a..59c9cf1b2 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -876,8 +876,8 @@ vector ExtensionHelper::GetTrustedPublicKeys(DatabaseInstance &db, Exten case ExtensionRepositoryType::USER_PROVIDED: { // when adding repositories has been forbidden, the user repositories are distrusted entirely: their keys are // no longer trusted, so extensions installed from them can no longer be loaded. Note that 'undecided' still - // trusts existing repositories - only 'forbidden' distrusts them - if (ExtensionRepositoryManager::GetAccess(db) == ExtensionRepositoryAccess::FORBIDDEN) { + // trusts existing repositories + if (!ExtensionRepositoryManager::TrustsExistingRepositories(db)) { return keys; } // only the keys of the repository the extension came from are trusted diff --git a/src/duckdb/src/main/extension/extension_install_dynamic.cpp b/src/duckdb/src/main/extension/extension_install_dynamic.cpp index 2703ec7f7..3aadea291 100644 --- a/src/duckdb/src/main/extension/extension_install_dynamic.cpp +++ b/src/duckdb/src/main/extension/extension_install_dynamic.cpp @@ -436,12 +436,13 @@ unique_ptr InstallExternalExtension(DatabaseInstance &db, // repositories. Core and community extensions keep the flat top-level layout for backwards compatibility string install_path = local_path; if (options.repository && options.repository->type == ExtensionRepositoryType::USER_PROVIDED) { - // installing native code from a user-provided repository trusts that repository's signing keys, so it requires - // the same explicit opt-in as adding one. Without this, pointing extension_repository_directory at an - // attacker-controlled directory and installing from it would bypass the opt-in entirely - if (ExtensionRepositoryManager::GetAccess(db) != ExtensionRepositoryAccess::ALLOWED) { - throw PermissionException("Installing extensions from a user-provided repository requires " - "allow_extension_repositories='allowed'"); + // the opt-in gates adding a repository, i.e. trusting a new signing key. An existing repository stays trusted + // while 'undecided' or 'allowed', as it does for LOAD + if (!ExtensionRepositoryManager::TrustsExistingRepositories(db)) { + throw PermissionException( + "Installing extensions from a user-provided repository is not permitted while " + "allow_extension_repositories='%s'", + ExtensionRepositoryManager::AccessToString(ExtensionRepositoryManager::GetAccess(db))); } install_path = fs.JoinPath(fs.JoinPath(local_path, "repositories"), options.repository->name); FileSystem::GetLocal(db).CreateDirectoriesRecursive(install_path); diff --git a/src/duckdb/src/main/extension/extension_repository_manager.cpp b/src/duckdb/src/main/extension/extension_repository_manager.cpp index 5fb65a6b8..e69c0a277 100644 --- a/src/duckdb/src/main/extension/extension_repository_manager.cpp +++ b/src/duckdb/src/main/extension/extension_repository_manager.cpp @@ -229,6 +229,17 @@ ExtensionRepositoryAccess ExtensionRepositoryManager::GetAccess(DatabaseInstance return ParseAccess(Settings::Get(db)); } +bool ExtensionRepositoryManager::TrustsExistingRepositories(DatabaseInstance &db) { + // the access values that trust existing repositories are listed explicitly, any other value distrusts them + switch (GetAccess(db)) { + case ExtensionRepositoryAccess::UNDECIDED: + case ExtensionRepositoryAccess::ALLOWED: + return true; + default: + return false; + } +} + void ExtensionRepositoryManager::CheckNotLocked(DatabaseInstance &db) { // modifying the trusted repositories changes the set of keys that are trusted to sign extensions, so it is gated // by the configuration lock: a locked configuration freezes the trust store diff --git a/src/duckdb/src/main/http/http_retry_budget.cpp b/src/duckdb/src/main/http/http_retry_budget.cpp index 2327b51c0..07e44926a 100644 --- a/src/duckdb/src/main/http/http_retry_budget.cpp +++ b/src/duckdb/src/main/http/http_retry_budget.cpp @@ -61,6 +61,14 @@ bool HTTPRetryQuota::TryAcquire(int64_t cost, int64_t now_ms) { return true; } +int64_t HTTPRetryQuota::AcquireUpTo(int64_t cost, int64_t now_ms) { + lock_guard guard(lock); + Touch(now_ms); + const auto taken = MinValue(cost, capacity); + capacity -= taken; + return taken; +} + void HTTPRetryQuota::Release(int64_t amount, int64_t now_ms) { lock_guard guard(lock); Touch(now_ms); @@ -79,11 +87,13 @@ int64_t HTTPRetryQuota::IdleMs(int64_t now_ms) const { HTTPRetryBudget::HTTPRetryBudget(const HTTPParams ¶ms, HTTPRetryOutcomeOwner owner_p) : retries(params.retries), retry_wait_ms(params.retry_wait_ms), retry_backoff(params.retry_backoff), + retry_quota_throttled(params.retry_quota_throttled), retry_throttled_wait_ms(params.retry_throttled_wait_ms), owner(owner_p) { #ifdef DUCKDB_NO_THREADS // Without threads there is no back-off sleep, so the schedule settings go unused. (void)retry_wait_ms; (void)retry_backoff; + (void)retry_throttled_wait_ms; #endif } @@ -337,7 +347,12 @@ bool HTTPRetryBudget::ConsumeAndWait(const HTTPRetryDecision &decision) { } const auto cost = decision.type == HTTPRetryDecision::Type::TRANSIENT ? HTTPRetryQuota::TRANSIENT_RETRY_COST : HTTPRetryQuota::RETRY_COST; - if (quota && !quota->TryAcquire(cost)) { + auto charged = cost; + if (quota && throttled && !retry_quota_throttled) { + // The server asked to slow down, not to stop: the retry is charged what the quota has left, and a success + // refunds only that, but an empty quota does not refuse it. + charged = quota->AcquireUpTo(cost); + } else if (quota && !quota->TryAcquire(cost)) { quota_exhausted = true; ForgetLastRetry(); return false; @@ -347,7 +362,7 @@ bool HTTPRetryBudget::ConsumeAndWait(const HTTPRetryDecision &decision) { earlier_throttled_retries.push_back(HTTPThrottledRetryCharge {std::move(last_retry_quota), last_retry_cost}); } last_retry_quota = quota; - last_retry_cost = cost; + last_retry_cost = charged; last_retry_throttled = throttled; outcome_settled = false; retries_used++; @@ -359,9 +374,11 @@ bool HTTPRetryBudget::ConsumeAndWait(const HTTPRetryDecision &decision) { if (throttled && !decision.retry_after.empty()) { TryParseRetryAfterMs(decision.retry_after, floor_ms); } + // Throttled retries back off from at least http_retry_throttled_wait_ms. + const auto wait_ms = throttled ? MaxValue(retry_wait_ms, retry_throttled_wait_ms) : retry_wait_ms; RandomEngine random; const auto sleep_ms = - BackoffMs(retry_wait_ms, retry_backoff, retries_used, floor_ms, random.NextRandomInteger64(), throttled); + BackoffMs(wait_ms, retry_backoff, retries_used, floor_ms, random.NextRandomInteger64(), throttled); if (sleep_ms > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms)); } diff --git a/src/duckdb/src/main/http/http_util.cpp b/src/duckdb/src/main/http/http_util.cpp index 9fd3193a0..7792c9041 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -574,12 +574,19 @@ void HTTPParams::Initialize(optional_ptr opener) { } http_proxy_username = Settings::Get(*db); http_proxy_password = Settings::Get(*db); + retry_quota_throttled = Settings::Get(*db); + retry_throttled_wait_ms = Settings::Get(*db); } auto context = FileOpener::TryGetContext(opener); if (context && context->IsClient()) { logger = context->GetLoggerPtr(); } + if (context) { + // A session's own value wins over the database's + retry_quota_throttled = Settings::Get(*context); + retry_throttled_wait_ms = Settings::Get(*context); + } } unique_ptr HTTPUtil::InitializeParameters(DatabaseInstance &db, const string &url) { diff --git a/src/duckdb/src/main/prepared_statement_data.cpp b/src/duckdb/src/main/prepared_statement_data.cpp index 6b258a02f..c7d2c9808 100644 --- a/src/duckdb/src/main/prepared_statement_data.cpp +++ b/src/duckdb/src/main/prepared_statement_data.cpp @@ -156,7 +156,7 @@ void PreparedStatementData::Bind(ClientContext &context, const identifier_map_t< auto parameter_value = GetParameterValue(context, values, it.first, can_read_user_variable); D_ASSERT(it.second); const auto &value = parameter_value.GetValue(); - auto cast_value = value.DefaultTryCastAs(it.second->return_type); + auto cast_value = value.TryCastAs(context, it.second->return_type); if (!cast_value) { throw BinderException( "Type mismatch for binding parameter with identifier %s, expected type %s but got type %s", identifier, diff --git a/src/duckdb/src/main/query_profiler.cpp b/src/duckdb/src/main/query_profiler.cpp index 203d273ce..b31b9c537 100644 --- a/src/duckdb/src/main/query_profiler.cpp +++ b/src/duckdb/src/main/query_profiler.cpp @@ -103,8 +103,7 @@ bool QueryProfiler::PrintOptimizerOutput() const { return metrics->MetricIsTracked("optimizer.join_order"); } // Fall back to checking tracked_metrics patterns directly - auto &config = ClientConfig::GetConfig(context); - for (const auto &pattern : config.tracked_metrics) { + for (const auto &pattern : Settings::Get(context)) { if (pattern == "*" || StringUtil::StartsWith(pattern, "optimizer")) { return true; } @@ -126,7 +125,7 @@ QueryProfiler &QueryProfiler::Get(Context &context) { void QueryProfiler::Start(const string &query) { Reset(); - tracked_metric_patterns = make_uniq(ClientConfig::GetConfig(context).tracked_metrics); + tracked_metric_patterns = make_uniq(Settings::Get(context)); running = true; query_metrics.query_sql = query; query_metrics.latency_timer = make_uniq(StartTimer()); @@ -1159,8 +1158,7 @@ void QueryProfiler::Initialize(const PhysicalOperator &root_op) { tree_map.clear(); root = nullptr; } else { - auto &client_config = ClientConfig::GetConfig(context); - metrics = make_uniq(client_config.tracked_metrics); + metrics = make_uniq(Settings::Get(context)); } } diff --git a/src/duckdb/src/main/secret/secret_manager.cpp b/src/duckdb/src/main/secret/secret_manager.cpp index 03cd4188f..4e5140930 100644 --- a/src/duckdb/src/main/secret/secret_manager.cpp +++ b/src/duckdb/src/main/secret/secret_manager.cpp @@ -286,7 +286,8 @@ unique_ptr SecretManager::CreateSecret(ClientContext &context, cons input.storage_type); } -BoundStatement SecretManager::BindCreateSecret(CatalogTransaction transaction, CreateSecretInput &info) { +BoundStatement SecretManager::BindCreateSecret(Context &context, CatalogTransaction transaction, + CreateSecretInput &info) { if (info.persist_type == SecretPersistType::TRANSACTION || info.storage_type == TRANSACTION_STORAGE_NAME) { throw BinderException("Transaction-scoped secrets cannot be created through SQL"); } @@ -323,7 +324,7 @@ BoundStatement SecretManager::BindCreateSecret(CatalogTransaction transaction, C // Cast the provided value to the expected type string error_msg; - auto cast_value = param.second.DefaultTryCastAs(matched_param->second, &error_msg); + auto cast_value = param.second.TryCastAs(context, matched_param->second, &error_msg); if (!cast_value) { throw BinderException("Failed to cast option %s to type '%s': '%s'", matched_param->first, matched_param->second.ToString(), error_msg); diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index c5fa71d98..90e998c57 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -1794,33 +1794,15 @@ void TempFileEncryptionSetting::OnSet(SettingCallbackInfo &info, Value &input) { //===----------------------------------------------------------------------===// // Tracked Metrics //===----------------------------------------------------------------------===// -void TrackedMetricsSetting::SetLocal(ClientContext &context, const Value &input) { +void TrackedMetricsSetting::OnSet(SettingCallbackInfo &info, Value &input) { if (input.IsNull()) { throw InvalidInputException("%s setting cannot be NULL", TrackedMetricsSetting::Name); } - auto &config = ClientConfig::GetConfig(context); - config.tracked_metrics.clear(); - if (input.type() == LogicalType::LIST(LogicalType::VARCHAR)) { - for (auto &child : ListValue::GetChildren(input)) { - config.tracked_metrics.push_back(child.GetValue()); + for (auto &pattern : ListValue::GetChildren(input)) { + if (pattern.IsNull()) { + throw InvalidInputException("%s setting cannot contain NULL entries", TrackedMetricsSetting::Name); } - } else { - throw InvalidInputException("Invalid tracked_metrics type \"%s\", expected LIST(VARCHAR)", - input.type().ToString()); - } -} - -void TrackedMetricsSetting::ResetLocal(ClientContext &context) { - ClientConfig::GetConfig(context).tracked_metrics = ClientConfig().tracked_metrics; -} - -Value TrackedMetricsSetting::GetSetting(const ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - vector children; - for (const auto &pattern : config.tracked_metrics) { - children.emplace_back(pattern); } - return Value::LIST(LogicalType::VARCHAR, std::move(children)); } //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/main/settings/settings.cpp b/src/duckdb/src/main/settings/settings.cpp index 64457c027..cfb558018 100644 --- a/src/duckdb/src/main/settings/settings.cpp +++ b/src/duckdb/src/main/settings/settings.cpp @@ -5,6 +5,49 @@ namespace duckdb { +vector Settings::SplitListDefault(const char *default_value) { + string input(default_value); + StringUtil::Trim(input); + if (input.size() < 2 || input.front() != '[' || input.back() != ']') { + throw InternalException("Default value \"%s\" of a list setting is not a list literal", default_value); + } + vector result; + string entry; + bool in_quotes = false; + bool has_entry = false; + for (idx_t i = 1; i + 1 < input.size(); i++) { + auto c = input[i]; + if (in_quotes) { + if (c != '\'') { + entry += c; + } else if (i + 2 < input.size() && input[i + 1] == '\'') { + // an escaped quote + entry += c; + i++; + } else { + in_quotes = false; + } + } else if (c == '\'') { + in_quotes = true; + has_entry = true; + } else if (c == ',') { + result.push_back(std::move(entry)); + entry.clear(); + has_entry = false; + } else if (!StringUtil::CharacterIsSpace(c)) { + entry += c; + has_entry = true; + } + } + if (in_quotes) { + throw InternalException("Default value \"%s\" of a list setting has an unterminated quote", default_value); + } + if (has_entry || !result.empty()) { + result.push_back(std::move(entry)); + } + return result; +} + bool Settings::TryGetSettingInternal(const ClientContext &context, idx_t setting_index, Value &result) { return context.TryGetCurrentUserSetting(setting_index, result); } diff --git a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp index f4ea11e44..4759d8616 100644 --- a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp +++ b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp @@ -8,7 +8,6 @@ #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/expression_binder/base_select_binder.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_order.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -97,26 +96,6 @@ void ApplyFunctionalDependencies::VisitLogicalAggregate(LogicalAggregate &aggr) } } -void ApplyFunctionalDependencies::VisitLogicalDistinct(LogicalDistinct &distinct) { - VisitOperatorChildren(distinct); - - // TODO: use child FDs to simplify groupings. - result.clear(); - - column_binding_set_t key; - bool all_columns = true; - for (auto &target : distinct.distinct_targets) { - if (target->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - all_columns = false; - break; - } - key.insert(target->Cast().Binding()); - } - if (all_columns && !key.empty()) { - result.push_back(std::move(key)); - } -} - void ApplyFunctionalDependencies::VisitLogicalProjection(LogicalProjection &projection) { VisitOperatorChildren(projection); @@ -324,9 +303,6 @@ void ApplyFunctionalDependencies::VisitOperator(LogicalOperator &op) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: VisitLogicalAggregate(op.Cast()); break; - case LogicalOperatorType::LOGICAL_DISTINCT: - VisitLogicalDistinct(op.Cast()); - break; default: VisitOperatorChildren(op); // Clear the keys because we don't know if the operator preserves them. diff --git a/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp b/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp index 316844711..3efdc44bc 100644 --- a/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp +++ b/src/duckdb/src/optimizer/column_lifetime_analyzer.cpp @@ -8,7 +8,6 @@ #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_order.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -151,35 +150,6 @@ void ColumnLifetimeAnalyzer::VisitOperator(LogicalOperator &op) { GenerateProjectionMap(op.children[0]->GetColumnBindings(), unused_bindings, order.projection_map); return; } - case LogicalOperatorType::LOGICAL_DISTINCT: { - // DISTINCT ON only references the expressions specified in the target list (and optional ORDER BY), - auto &distinct = op.Cast(); - if (distinct.distinct_type == DistinctType::DISTINCT_ON) { - auto add_bindings = [&](Expression &expr) { - vector bindings; - ExtractColumnBindings(expr, bindings); - for (auto &binding : bindings) { - column_references.insert(binding); - } - }; - for (auto &target : distinct.distinct_targets) { - if (target) { - add_bindings(*target); - } - } - if (distinct.order_by) { - for (auto &order : distinct.order_by->orders) { - if (order.expression) { - add_bindings(*order.expression); - } - } - } - break; - } - // DISTINCT without targets references the entire projection list - everything_referenced = true; - break; - } case LogicalOperatorType::LOGICAL_FILTER: { auto &filter = op.Cast(); if (everything_referenced) { @@ -213,22 +183,27 @@ void ColumnLifetimeAnalyzer::Verify(LogicalOperator &op) { switch (op.type) { case LogicalOperatorType::LOGICAL_ASOF_JOIN: case LogicalOperatorType::LOGICAL_DELIM_JOIN: - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - AddVerificationProjection(op.children[0]); - if (op.Cast().join_type != JoinType::MARK) { // Can't mess up the mark_index - AddVerificationProjection(op.children[1]); + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { + auto &join = op.Cast(); + AddVerificationProjection(op.children[0], join.left_projection_map); + if (join.join_type != JoinType::MARK) { // Can't mess up the mark_index + AddVerificationProjection(op.children[1], join.right_projection_map); } break; + } case LogicalOperatorType::LOGICAL_ORDER_BY: + AddVerificationProjection(op.children[0], op.Cast().projection_map); + break; case LogicalOperatorType::LOGICAL_FILTER: - AddVerificationProjection(op.children[0]); + AddVerificationProjection(op.children[0], op.Cast().projection_map); break; default: break; } } -void ColumnLifetimeAnalyzer::AddVerificationProjection(unique_ptr &child) { +void ColumnLifetimeAnalyzer::AddVerificationProjection(unique_ptr &child, + vector &projection_map) { child->ResolveOperatorTypes(); const auto child_types = child->types; const auto child_bindings = child->GetColumnBindings(); @@ -236,6 +211,11 @@ void ColumnLifetimeAnalyzer::AddVerificationProjection(unique_ptr> expressions; expressions.reserve(projection_column_count); diff --git a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index 2fd688281..3e7c65527 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -32,7 +32,6 @@ GetExpandedColumnBindings(LogicalOperator &op, optional_ptr &op) { switch (op->type) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - case LogicalOperatorType::LOGICAL_DISTINCT: case LogicalOperatorType::LOGICAL_ORDER_BY: break; default: @@ -464,9 +463,6 @@ void CompressedMaterialization::Compress(unique_ptr &op) { case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: CompressComparisonJoin(op); break; - case LogicalOperatorType::LOGICAL_DISTINCT: - CompressDistinct(op); - break; case LogicalOperatorType::LOGICAL_ORDER_BY: CompressOrder(op); break; diff --git a/src/duckdb/src/optimizer/compressed_materialization/compress_distinct.cpp b/src/duckdb/src/optimizer/compressed_materialization/compress_distinct.cpp deleted file mode 100644 index e533bfaac..000000000 --- a/src/duckdb/src/optimizer/compressed_materialization/compress_distinct.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "duckdb/optimizer/compressed_materialization.hpp" -#include "duckdb/planner/expression/bound_columnref_expression.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" - -namespace duckdb { - -void CompressedMaterialization::CompressDistinct(unique_ptr &op) { - auto &distinct = op->Cast(); - auto &distinct_targets = distinct.distinct_targets; - - column_binding_set_t referenced_bindings; - for (auto &target : distinct_targets) { - if (target->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { // LCOV_EXCL_START - GetReferencedBindings(*target, referenced_bindings); - } // LCOV_EXCL_STOP - } - - if (distinct.order_by) { - for (auto &order : distinct.order_by->orders) { - if (order.expression->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { // LCOV_EXCL_START - GetReferencedBindings(*order.expression, referenced_bindings); - } // LCOV_EXCL_STOP - } - } - - // Create info for compression - CompressedMaterializationInfo info(*op, {0}, referenced_bindings); - - // Create binding mapping - const auto bindings = distinct.GetColumnBindings(); - const auto &types = distinct.types; - D_ASSERT(bindings.size() == types.size()); - for (idx_t col_idx = 0; col_idx < bindings.size(); col_idx++) { - // Distinct does not change bindings, input binding is output binding - info.binding_map.emplace(bindings[col_idx], CMBindingInfo(bindings[col_idx], types[col_idx])); - } - - // Now try to compress - CreateProjections(op, info); -} - -} // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_inlining.cpp b/src/duckdb/src/optimizer/cte_inlining.cpp index f0f98f973..b2ea273c8 100644 --- a/src/duckdb/src/optimizer/cte_inlining.cpp +++ b/src/duckdb/src/optimizer/cte_inlining.cpp @@ -70,7 +70,6 @@ static bool ContainsLimit(const LogicalOperator &op) { bool CTEInlining::EndsInAggregateOrDistinct(const LogicalOperator &op) { switch (op.type) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: - case LogicalOperatorType::LOGICAL_DISTINCT: case LogicalOperatorType::LOGICAL_WINDOW: return true; default: diff --git a/src/duckdb/src/optimizer/cte_join_filter_collector.cpp b/src/duckdb/src/optimizer/cte_join_filter_collector.cpp index 9d8a15d2a..819241377 100644 --- a/src/duckdb/src/optimizer/cte_join_filter_collector.cpp +++ b/src/duckdb/src/optimizer/cte_join_filter_collector.cpp @@ -8,7 +8,6 @@ #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cteref.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -144,11 +143,6 @@ static optional_ptr FindCTEJoinSource(LogicalOperator &op, return nullptr; } break; - case LogicalOperatorType::LOGICAL_DISTINCT: - if (op.Cast().distinct_type != DistinctType::DISTINCT) { - return nullptr; - } - break; case LogicalOperatorType::LOGICAL_FILTER: break; default: @@ -287,11 +281,6 @@ void CTEJoinFilterCollector::PushFilter(LogicalOperator &op, const CTEJoinSource case LogicalOperatorType::LOGICAL_FILTER: case LogicalOperatorType::LOGICAL_ORDER_BY: break; - case LogicalOperatorType::LOGICAL_DISTINCT: - if (op.Cast().distinct_type != DistinctType::DISTINCT) { - return; - } - break; case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: if (!MapCTEJoinAggregate(op.Cast(), target_keys)) { return; diff --git a/src/duckdb/src/optimizer/empty_result_pullup.cpp b/src/duckdb/src/optimizer/empty_result_pullup.cpp index 0b6c17343..27ae4ef5d 100644 --- a/src/duckdb/src/optimizer/empty_result_pullup.cpp +++ b/src/duckdb/src/optimizer/empty_result_pullup.cpp @@ -74,7 +74,6 @@ unique_ptr EmptyResultPullup::Optimize(unique_ptrtype) { case LogicalOperatorType::LOGICAL_PROJECTION: case LogicalOperatorType::LOGICAL_FILTER: - case LogicalOperatorType::LOGICAL_DISTINCT: case LogicalOperatorType::LOGICAL_WINDOW: case LogicalOperatorType::LOGICAL_GET: case LogicalOperatorType::LOGICAL_INTERSECT: diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index 66317666a..d3ef2cc5d 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -1249,7 +1249,8 @@ FilterResult FilterCombiner::AddBoundComparisonFilter(Expression &expr) { } FilterResult FilterCombiner::AddFilter(Expression &expr) { - if (expr.HasParameter()) { + // every occurrence of a volatile expression is its own evaluation, so it cannot share an equivalence set + if (expr.HasParameter() || expr.IsVolatile()) { return FilterResult::UNSUPPORTED; } if (expr.IsFoldable()) { @@ -1258,7 +1259,7 @@ FilterResult FilterCombiner::AddFilter(Expression &expr) { if (!ExpressionExecutor::TryEvaluateScalar(context, expr, result)) { return FilterResult::UNSUPPORTED; } - result = result.DefaultCastAs(LogicalType::BOOLEAN); + result = result.CastAs(context, LogicalType::BOOLEAN); // check if the filter passes if (result.IsNull() || !BooleanValue::Get(result)) { // the filter does not pass the scalar test, create an empty result diff --git a/src/duckdb/src/optimizer/filter_pullup.cpp b/src/duckdb/src/optimizer/filter_pullup.cpp index b0970b4e8..1e66a7b4e 100644 --- a/src/duckdb/src/optimizer/filter_pullup.cpp +++ b/src/duckdb/src/optimizer/filter_pullup.cpp @@ -7,7 +7,6 @@ #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" #include "duckdb/planner/operator/logical_join.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_window.hpp" namespace duckdb { @@ -28,8 +27,6 @@ unique_ptr FilterPullup::Rewrite(unique_ptr op case LogicalOperatorType::LOGICAL_INTERSECT: case LogicalOperatorType::LOGICAL_EXCEPT: return PullupSetOperation(std::move(op)); - case LogicalOperatorType::LOGICAL_DISTINCT: - return PullupDistinct(std::move(op)); case LogicalOperatorType::LOGICAL_WINDOW: return PullupWindow(std::move(op)); case LogicalOperatorType::LOGICAL_ORDER_BY: { @@ -149,25 +146,6 @@ unique_ptr FilterPullup::PullupCrossProduct(unique_ptr FilterPullup::PullupDistinct(unique_ptr op) { - const auto &distinct = op->Cast(); - if (distinct.distinct_type == DistinctType::DISTINCT) { - // Can pull up through a DISTINCT - op->children[0] = Rewrite(std::move(op->children[0])); - for (auto &expr : filters_expr_pullup) { - if (expr->IsVolatile()) { - // Keep volatile predicates below the DISTINCT, where they run once per input row - op->children[0] = GeneratePullupFilter(std::move(op->children[0]), filters_expr_pullup); - return op; - } - } - return op; - } - // Cannot pull up through a DISTINCT ON (see #19327) - D_ASSERT(distinct.distinct_type == DistinctType::DISTINCT_ON); - return FinishPullup(std::move(op)); -} - unique_ptr FilterPullup::PullupWindow(unique_ptr op) { if (!can_pullup) { return FinishPullup(std::move(op)); diff --git a/src/duckdb/src/optimizer/filter_pushdown.cpp b/src/duckdb/src/optimizer/filter_pushdown.cpp index d262b32a9..e6bf854f7 100644 --- a/src/duckdb/src/optimizer/filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/filter_pushdown.cpp @@ -133,11 +133,9 @@ unique_ptr FilterPushdown::Rewrite(unique_ptr case LogicalOperatorType::LOGICAL_EXCEPT: case LogicalOperatorType::LOGICAL_UNION: return PushdownSetOperation(std::move(op)); - case LogicalOperatorType::LOGICAL_DISTINCT: - return PushdownDistinct(std::move(op)); case LogicalOperatorType::LOGICAL_ORDER_BY: // we can just push directly through these operations without any rewriting - op->children[0] = Rewrite(std::move(op->children[0])); + RewriteChild(*op, 0); return op; case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { // we can't push filters into the materialized CTE (LHS), but we do want to recurse into it @@ -272,11 +270,11 @@ unique_ptr FilterPushdown::PushFinalFilters(unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr op) { for (idx_t i = 0; i < filters.size(); i++) { auto &f = *filters[i]; - for (auto &child : op->children) { + for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { FilterPushdown pushdown(optimizer, convert_mark_joins, projection_mode); // check if filter bindings can be applied to the child bindings. - auto child_bindings = child->GetColumnBindings(); + auto child_bindings = op->children[child_idx]->GetColumnBindings(); unordered_set child_bindings_table; for (auto &binding : child_bindings) { child_bindings_table.insert(binding.table_index); @@ -303,7 +301,7 @@ unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr< // push the filter into the child. pushdown.GenerateFilters(); - child = pushdown.Rewrite(std::move(child)); + pushdown.RewriteChild(*op, child_idx); // Don't push same filter again filters.erase_at(i); @@ -316,14 +314,26 @@ unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr< unique_ptr FilterPushdown::FinishPushdown(unique_ptr op) { // unhandled type, first perform filter pushdown in its children - for (auto &child : op->children) { + for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { FilterPushdown pushdown(optimizer, convert_mark_joins, projection_mode); - child = pushdown.Rewrite(std::move(child)); + pushdown.RewriteChild(*op, child_idx); } // now push any existing filters return PushFinalFilters(std::move(op)); } +void FilterPushdown::RewriteChild(LogicalOperator &op, idx_t child_idx) { + auto projection_map = LogicalOperatorVisitor::GetProjectionMap(op, child_idx); + if (!projection_map || projection_map->empty()) { + op.children[child_idx] = Rewrite(std::move(op.children[child_idx])); + return; + } + auto child_bindings_before = op.children[child_idx]->GetColumnBindings(); + op.children[child_idx] = Rewrite(std::move(op.children[child_idx])); + LogicalOperatorVisitor::RemapProjectionMap(*projection_map, child_bindings_before, + op.children[child_idx]->GetColumnBindings()); +} + void FilterPushdown::Filter::ExtractBindings() { bindings.clear(); LogicalJoin::GetExpressionBindings(*filter, bindings); diff --git a/src/duckdb/src/optimizer/join_elimination.cpp b/src/duckdb/src/optimizer/join_elimination.cpp index 079f05fea..1a814a70a 100644 --- a/src/duckdb/src/optimizer/join_elimination.cpp +++ b/src/duckdb/src/optimizer/join_elimination.cpp @@ -13,7 +13,6 @@ #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include @@ -29,6 +28,9 @@ void JoinElimination::OptimizeChildren(LogicalOperator &op, optional_ptrVisitOperatorExpressions(op); + right_child->VisitOperatorExpressions(op); left_child->OptimizeInternal(std::move(op.children[0])); right_child->OptimizeInternal(std::move(op.children[1])); return; @@ -37,31 +39,6 @@ void JoinElimination::OptimizeChildren(LogicalOperator &op, optional_ptr(); - if (distinct.distinct_type != DistinctType::DISTINCT) { - break; - } - column_binding_set_t distinct_group; - if (distinct.distinct_targets[0]->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - break; - } - auto table_idx = distinct.distinct_targets[0]->Cast().Binding().table_index; - bool can_add = true; - for (auto &target : distinct.distinct_targets) { - if (target->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - can_add = false; - break; - } - auto &col_ref = target->Cast(); - distinct_group.insert(col_ref.Binding()); - D_ASSERT(table_idx == col_ref.Binding().table_index); - } - if (can_add) { - pipe_info.distinct_groups[table_idx] = std::move(distinct_group); - } - break; - } case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { auto &aggr = op.Cast(); if (aggr.grouping_sets.size() > 1) { @@ -76,6 +53,28 @@ void JoinElimination::OptimizeChildren(LogicalOperator &op, optional_ptrGetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + single_input = false; + break; + } + auto &binding = group->Cast().Binding(); + if (!input_group.empty() && binding.table_index != input_index) { + single_input = false; + break; + } + input_index = binding.table_index; + input_group.insert(binding); + } + if (single_input) { + pipe_info.distinct_groups[input_index] = std::move(input_group); + } + } break; } case LogicalOperatorType::LOGICAL_PROJECTION: { diff --git a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp index 401e81099..d6f83ab55 100644 --- a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp @@ -18,7 +18,6 @@ #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cteref.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" @@ -592,11 +591,6 @@ static void FindFilterTargets(LogicalOperator &op, vector(), columns, targets, context); break; - case LogicalOperatorType::LOGICAL_DISTINCT: - if (op.Cast().distinct_type == DistinctType::DISTINCT) { - FindFilterTargets(*op.children[0], std::move(columns), targets, context); - } - break; case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: FindJoinFilterTargets(op, std::move(columns), targets, context, expansion); diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 4e3394065..e80cc24c0 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -314,6 +314,14 @@ static bool JoinIsReorderable(LogicalOperator &op) { if (join.HasProjectionMap()) { return false; } + // Preserve the input rows on which volatile condition operands are evaluated. + for (auto &cond : join.conditions) { + bool is_volatile = cond.IsComparison() ? cond.GetLHS().IsVolatile() || cond.GetRHS().IsVolatile() + : cond.GetJoinExpression().IsVolatile(); + if (is_volatile) { + return false; + } + } if ((join.join_type == JoinType::LEFT || join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) && ContainsRecurringCTERef(*join.children[1])) { @@ -919,6 +927,10 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, reference_map_t> operator_predicates; reference_map_t> operator_conditions; expression_set_t filter_set; + // two equal volatile filters are two evaluations, so neither is a duplicate of the other + auto is_new_filter = [&](const Expression &expr) { + return expr.IsVolatile() || filter_set.insert(expr).second; + }; auto normalize_conditions = [&](LogicalComparisonJoin &join, const column_binding_set_t &semantic_left_bindings, const column_binding_set_t &semantic_right_bindings) { vector result; @@ -1085,8 +1097,7 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, is_residual = true; } - if (filter_set.find(*expr) == filter_set.end()) { - filter_set.insert(*expr); + if (is_new_filter(*expr)) { unordered_set bindings; ExtractBindings(*expr, bindings); auto &set = set_manager.GetJoinRelation(bindings); @@ -1110,8 +1121,7 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, // in this case we do not create a FilterInfo for it. (duckdb-internal/#1493) continue; } - if (filter_set.find(*expression) == filter_set.end()) { - filter_set.insert(*expression); + if (is_new_filter(*expression)) { auto &set = set_manager.GetJoinRelation(bindings); auto filter_info = make_uniq(expression->Copy(), set, filters_and_bindings.size()); filter_info->from_logical_filter = true; diff --git a/src/duckdb/src/optimizer/projection_pullup.cpp b/src/duckdb/src/optimizer/projection_pullup.cpp index 1883c4b17..2f1d4ae09 100644 --- a/src/duckdb/src/optimizer/projection_pullup.cpp +++ b/src/duckdb/src/optimizer/projection_pullup.cpp @@ -74,15 +74,6 @@ void ProjectionPullup::InsertProjectionBelowOp(unique_ptr &op, void ProjectionPullup::PullUpColrefProjection(unique_ptr &op, LogicalProjection &proj, vector &proj_bindings) { - // LOGICAL_DISTINCT sets `everything_referenced = true` in RemoveUnusedColumns - // for its subtree. The projection above it acts as a binding barrier; removing - // it lets upstream references point past DISTINCT and breaks column pruning - // down to READ_PARQUET. Repro: TPC-DS Q54 regresses 4-5x without this guard. - if (proj.children[0]->type == LogicalOperatorType::LOGICAL_DISTINCT) { - ProjectionPullup next(optimizer, root); - next.Optimize(proj.children[0]); - return; - } ColumnBindingReplacer replacer; for (idx_t i = 0; i < proj.expressions.size(); i++) { auto &colref = proj.expressions[i]->Cast(); @@ -265,7 +256,6 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { } return; } - case LogicalOperatorType::LOGICAL_DISTINCT: case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: case LogicalOperatorType::LOGICAL_CTE_REF: diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_distinct.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_distinct.cpp deleted file mode 100644 index c1d3a0d30..000000000 --- a/src/duckdb/src/optimizer/pushdown/pushdown_distinct.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "duckdb/optimizer/filter_pushdown.hpp" -#include "duckdb/planner/expression_iterator.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" - -namespace duckdb { - -unique_ptr FilterPushdown::PushdownDistinct(unique_ptr op) { - D_ASSERT(op->type == LogicalOperatorType::LOGICAL_DISTINCT); - auto &distinct = op->Cast(); - if (!distinct.order_by) { - // volatile filters stay above the DISTINCT, where they run once per distinct row - vector> volatile_filters; - for (idx_t i = 0; i < filters.size(); i++) { - if (!filters[i]->filter->IsVolatile()) { - continue; - } - volatile_filters.push_back(std::move(filters[i]->filter)); - filters.erase_at(i); - i--; - } - op->children[0] = Rewrite(std::move(op->children[0])); - return AddLogicalFilter(std::move(op), std::move(volatile_filters)); - } - // no pushdown through DISTINCT ON (yet?) - return FinishPushdown(std::move(op)); -} - -} // namespace duckdb diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp index 045497783..58f6e0f58 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" @@ -40,6 +41,8 @@ unique_ptr FilterPushdown::PushdownInnerJoin(unique_ptrchildren[0]->GetColumnBindings(); + auto right_bindings_before = op->children[1]->GetColumnBindings(); // turn the inner join into a cross product auto cross_product = make_uniq(std::move(op->children[0]), std::move(op->children[1])); @@ -58,6 +61,10 @@ unique_ptr FilterPushdown::PushdownInnerJoin(unique_ptrCast(); result_join.left_projection_map = std::move(join.left_projection_map); result_join.right_projection_map = std::move(join.right_projection_map); + LogicalOperatorVisitor::RemapProjectionMap(result_join.left_projection_map, left_bindings_before, + result_join.children[0]->GetColumnBindings()); + LogicalOperatorVisitor::RemapProjectionMap(result_join.right_projection_map, right_bindings_before, + result_join.children[1]->GetColumnBindings()); break; } default: diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp index 129dc95ce..b9c5115c6 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp @@ -97,7 +97,7 @@ static bool FilterRemovesNull(ClientContext &context, ExpressionRewriter &rewrit // an error does not show that the NULL rows are filtered out: it may never be evaluated continue; } - val = val.DefaultCastAs(LogicalType::BOOLEAN); + val = val.CastAs(context, LogicalType::BOOLEAN); // if the result of the expression with all expressions replaced with NULL is "NULL" or "false" // then any extra entries generated by the LEFT OUTER JOIN will be filtered out! // hence the LEFT OUTER JOIN is equivalent to an inner join @@ -186,7 +186,7 @@ unique_ptr FilterPushdown::PushdownLeftJoin(unique_ptrchildren[0] = left_pushdown.Rewrite(std::move(op->children[0])); + left_pushdown.RewriteChild(*op, 0); bool rewrite_right = true; bool has_unsatisfiable_condition = false; @@ -216,7 +216,7 @@ unique_ptr FilterPushdown::PushdownLeftJoin(unique_ptrchildren[1] = right_pushdown.Rewrite(std::move(op->children[1])); + right_pushdown.RewriteChild(*op, 1); } for (auto &filter : remaining_filters) { diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp index 076734c30..3b2a43326 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp @@ -100,8 +100,8 @@ unique_ptr FilterPushdown::PushdownMarkJoin(unique_ptrchildren[0] = left_pushdown.Rewrite(std::move(op->children[0])); - op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); + left_pushdown.RewriteChild(*op, 0); + right_pushdown.RewriteChild(*op, 1); if (join.join_type == JoinType::SEMI) { SimplifyNullSafeSemiJoinConditions(GetContext(), comp_join); } diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp index f2cd004da..32dc2737d 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp @@ -193,8 +193,8 @@ unique_ptr FilterPushdown::PushdownOuterJoin(unique_ptrchildren[0] = left_pushdown.Rewrite(std::move(op->children[0])); - op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); + left_pushdown.RewriteChild(*op, 0); + right_pushdown.RewriteChild(*op, 1); return PushFinalFilters(std::move(op)); } diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp index d09711663..5b5bb6fb6 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp @@ -25,8 +25,8 @@ unique_ptr FilterPushdown::PushdownSemiAntiJoin(unique_ptrchildren[0] = Rewrite(std::move(op->children[0])); - op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); + RewriteChild(*op, 0); + right_pushdown.RewriteChild(*op, 1); bool left_empty = op->children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT; bool right_empty = op->children[1]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp index 137f9b962..13d38ab70 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp @@ -22,8 +22,8 @@ unique_ptr FilterPushdown::PushdownSingleJoin(unique_ptrchildren[0] = left_pushdown.Rewrite(std::move(op->children[0])); - op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); + left_pushdown.RewriteChild(*op, 0); + right_pushdown.RewriteChild(*op, 1); return PushFinalFilters(std::move(op)); } diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp index 2cfc06c0a..a36f3e54d 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -520,79 +520,6 @@ optional RelationStatisticsHelper::ExtractWindowStats(LogicalWind return result; } -static optional GetDistinctTargetCount(Expression &target, const RelationStats &child_stats, - const RelationColumnStatsLookup &child_columns) { - switch (target.GetExpressionClass()) { - case ExpressionClass::BOUND_COLUMN_REF: { - auto column = child_columns.Find(target.Cast().Binding()); - return column ? optional(column->current_domain) : optional(); - } - case ExpressionClass::BOUND_REF: { - auto index = target.Cast().Index(); - return index < child_stats.columns.size() ? optional(child_stats.columns[index].current_domain) - : optional(); - } - case ExpressionClass::BOUND_CONSTANT: - return DistinctCount(MinValue(child_stats.cardinality, 1), DistinctCountSource::EXACT); - default: - return {}; - } -} - -static optional GetDistinctTargetBinding(Expression &target, const RelationStats &child_stats) { - switch (target.GetExpressionClass()) { - case ExpressionClass::BOUND_COLUMN_REF: - return target.Cast().Binding(); - case ExpressionClass::BOUND_REF: { - auto index = target.Cast().Index(); - return index < child_stats.columns.size() ? optional(child_stats.columns[index].binding) - : optional(); - } - default: - return {}; - } -} - -optional RelationStatisticsHelper::ExtractDistinctStats(LogicalDistinct &distinct, - const RelationStats &child_stats) { - auto result = ProjectOutputStats(child_stats, distinct); - if (!result) { - return {}; - } - result->row_retention = 1; - vector distinct_counts; - if (distinct.distinct_targets.empty()) { - for (auto &column : child_stats.columns) { - distinct_counts.push_back(column.current_domain); - } - } else { - RelationColumnStatsLookup child_columns(child_stats); - for (auto &target : distinct.distinct_targets) { - auto count = GetDistinctTargetCount(*target, child_stats, child_columns); - if (!count) { - return result; - } - distinct_counts.push_back(*count); - } - } - result->cardinality = EstimateDistinctCardinality(distinct_counts, child_stats.cardinality); - result->CapCurrentDomainsToCardinality(); - if (result->columns.size() == 1 && distinct.distinct_targets.empty()) { - result->columns[0].semi_anti_join_domain_evidence.MarkUnique(); - } else if (distinct.distinct_targets.size() == 1) { - auto target_binding = GetDistinctTargetBinding(*distinct.distinct_targets[0], child_stats); - if (target_binding) { - for (auto &column : result->columns) { - if (column.binding == *target_binding) { - column.semi_anti_join_domain_evidence.MarkUnique(); - break; - } - } - } - } - return result; -} - optional RelationStatisticsHelper::ExtractLimitStats(LogicalLimit &limit, const RelationStats &child_stats) { auto result = ProjectOutputStats(child_stats, limit); diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp index 3d601a7e3..cbf6e4239 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp @@ -370,8 +370,6 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex return ExtractAggregationStats(op.Cast(), child_stats[0].get(), context); case LogicalOperatorType::LOGICAL_WINDOW: return ExtractWindowStats(op.Cast(), child_stats[0].get()); - case LogicalOperatorType::LOGICAL_DISTINCT: - return ExtractDistinctStats(op.Cast(), child_stats[0].get()); case LogicalOperatorType::LOGICAL_FILTER: { if (child_stats.size() != 1) { return {}; diff --git a/src/duckdb/src/optimizer/remove_redundant_order.cpp b/src/duckdb/src/optimizer/remove_redundant_order.cpp index 3911727f1..05798b059 100644 --- a/src/duckdb/src/optimizer/remove_redundant_order.cpp +++ b/src/duckdb/src/optimizer/remove_redundant_order.cpp @@ -2,7 +2,6 @@ #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_order.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" @@ -13,6 +12,10 @@ namespace { //! A hash aggregate sinks in parallel, so the input order never reaches its aggregates; an ungrouped aggregate sinks in //! order when one of its aggregates reads the rows in order bool AggregateDiscardsOrder(const LogicalAggregate &aggr) { + if (aggr.preserve_input_order) { + // DISTINCT ON keeps the first row of every group in input order + return false; + } if (!aggr.groups.empty()) { return true; } @@ -29,11 +32,6 @@ bool AggregateDiscardsOrder(const LogicalAggregate &aggr) { return true; } -//! DISTINCT ON keeps the first row of every group, so it reads its input in order; plain DISTINCT does not -bool DistinctDiscardsOrder(const LogicalDistinct &distinct) { - return distinct.distinct_type == DistinctType::DISTINCT; -} - //! UNION ALL concatenates its inputs in order; the hash-based set operations do not bool SetOperationDiscardsOrder(const LogicalSetOperation &setop) { return setop.type != LogicalOperatorType::LOGICAL_UNION || !setop.setop_all; @@ -66,9 +64,6 @@ void RemoveRedundantOrder::Optimize(unique_ptr &op, bool order_ case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: Optimize(op->children[0], AggregateDiscardsOrder(op->Cast())); return; - case LogicalOperatorType::LOGICAL_DISTINCT: - Optimize(op->children[0], DistinctDiscardsOrder(op->Cast())); - return; case LogicalOperatorType::LOGICAL_UNION: case LogicalOperatorType::LOGICAL_EXCEPT: case LogicalOperatorType::LOGICAL_INTERSECT: { diff --git a/src/duckdb/src/optimizer/remove_unused_columns.cpp b/src/duckdb/src/optimizer/remove_unused_columns.cpp index e55dbbb59..468fa39e0 100644 --- a/src/duckdb/src/optimizer/remove_unused_columns.cpp +++ b/src/duckdb/src/optimizer/remove_unused_columns.cpp @@ -19,7 +19,6 @@ #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_column_data_get.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_order.hpp" @@ -492,6 +491,27 @@ void RemoveUnusedColumns::VisitSecureView(LogicalSecureView &view) { view.output_expressions = std::move(new_expressions); } +static bool IsDuplicateCondition(const vector &conditions, const JoinCondition &cond) { + // two equal volatile conditions are two evaluations, so neither is a duplicate of the other + if (cond.IsComparison() ? (cond.GetLHS().IsVolatile() || cond.GetRHS().IsVolatile()) + : cond.GetJoinExpression().IsVolatile()) { + return false; + } + for (auto &other : conditions) { + if (cond.IsComparison() && other.IsComparison()) { + if (cond.GetComparisonType() == other.GetComparisonType() && cond.GetLHS().Equals(other.GetLHS()) && + cond.GetRHS().Equals(other.GetRHS())) { + return true; + } + } else if (!cond.IsComparison() && !other.IsComparison()) { + if (cond.GetJoinExpression().Equals(other.GetJoinExpression())) { + return true; + } + } + } + return false; +} + void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { const bool analyze = mode == RemoveUnusedColumnsMode::ANALYZE; auto &op = *op_ref; @@ -810,21 +830,6 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { } return; } - case LogicalOperatorType::LOGICAL_DISTINCT: { - auto &distinct = op.Cast(); - if (distinct.distinct_type == DistinctType::DISTINCT_ON) { - // distinct type references columns that need to be distinct on, so no - // need to implicitly reference everything. - break; - } - // Preserve all DISTINCT inputs without affecting sibling branches. - const auto previous_everything_referenced = everything_referenced; - everything_referenced = true; - LogicalOperatorVisitor::VisitOperatorExpressions(op); - VisitPrunableChildren(op); - everything_referenced = previous_everything_referenced; - return; - } case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: { if (analyze) { LogicalOperatorVisitor::VisitOperatorExpressions(op); @@ -1010,22 +1015,7 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { // after removing duplicate columns we may have duplicate join conditions (if the join graph is cyclical) vector unique_conditions; for (auto &cond : comp_join.conditions) { - bool found = false; - for (auto &unique_cond : unique_conditions) { - if (cond.IsComparison() && unique_cond.IsComparison()) { - if (cond.GetComparisonType() == unique_cond.GetComparisonType() && - cond.GetLHS().Equals(unique_cond.GetLHS()) && cond.GetRHS().Equals(unique_cond.GetRHS())) { - found = true; - break; - } - } else if (!cond.IsComparison() && !unique_cond.IsComparison()) { - if (cond.GetJoinExpression().Equals(unique_cond.GetJoinExpression())) { - found = true; - break; - } - } - } - if (!found) { + if (!IsDuplicateCondition(unique_conditions, cond)) { unique_conditions.push_back(std::move(cond)); } } diff --git a/src/duckdb/src/optimizer/row_group_pruner.cpp b/src/duckdb/src/optimizer/row_group_pruner.cpp index f97568940..3b76f64e2 100644 --- a/src/duckdb/src/optimizer/row_group_pruner.cpp +++ b/src/duckdb/src/optimizer/row_group_pruner.cpp @@ -53,7 +53,7 @@ bool RowGroupPruner::TryOptimize(LogicalOperator &op) const { } if (op_type == LogicalOperatorType::LOGICAL_FILTER || op_type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY || - op_type == LogicalOperatorType::LOGICAL_WINDOW || op_type == LogicalOperatorType::LOGICAL_DISTINCT) { + op_type == LogicalOperatorType::LOGICAL_WINDOW) { row_limit.SetInvalid(); row_offset.SetInvalid(); } diff --git a/src/duckdb/src/optimizer/rule/case_simplification.cpp b/src/duckdb/src/optimizer/rule/case_simplification.cpp index 2d8753d62..5bfc5ccd4 100644 --- a/src/duckdb/src/optimizer/rule/case_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/case_simplification.cpp @@ -21,7 +21,7 @@ unique_ptr CaseSimplificationRule::Apply(LogicalOperator &op, vector // use an ExpressionExecutor to execute the expression Value condition; if (!ExpressionExecutor::TryEvaluateScalar(GetContext(), *case_check.when_expr, condition) || - !condition.DefaultTryCastAs(LogicalType::BOOLEAN)) { + !condition.TryCastAs(GetContext(), LogicalType::BOOLEAN)) { // the condition cannot be evaluated: leave it to execution continue; } diff --git a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp index 53de7616b..042b900d9 100644 --- a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp @@ -77,63 +77,88 @@ static bool DateTimestampComparisonIsInvertible(ClientContext &context, BoundFun return true; } -static bool IsLosslessIntegralToFloatingCast(const LogicalType &source_type, const LogicalType &target_type) { - if (target_type.id() == LogicalTypeId::DOUBLE) { - switch (source_type.id()) { - case LogicalTypeId::TINYINT: - case LogicalTypeId::SMALLINT: - case LogicalTypeId::INTEGER: - case LogicalTypeId::UTINYINT: - case LogicalTypeId::USMALLINT: - case LogicalTypeId::UINTEGER: - return true; - default: - return false; - } - } - if (target_type.id() == LogicalTypeId::FLOAT) { - switch (source_type.id()) { - case LogicalTypeId::TINYINT: - case LogicalTypeId::SMALLINT: - case LogicalTypeId::UTINYINT: - case LogicalTypeId::USMALLINT: - return true; - default: - return false; - } - } - return false; -} - static bool ConstantCastIsInvertible(ClientContext &context, BoundFunctionExpression &expr, BoundFunctionExpression &cast_expression, const Value &constant_value, Value &cast_constant, const LogicalType &target_type, bool column_ref_left, unique_ptr &replacement) { - if (cast_constant.IsNull() || BoundCastExpression::CastIsInvertible(cast_expression.GetReturnType(), target_type)) { + auto &cast_type = cast_expression.GetReturnType(); + if (cast_constant.IsNull() || BoundCastExpression::CastIsInvertible(cast_type, target_type)) { return true; } - if (cast_expression.GetReturnType().IsIntegral() && target_type.IsIntegral()) { + if (cast_type.IsIntegral() && target_type.IsIntegral()) { return true; } - // The constant must survive the integral round-trip exactly; the column side is checked by the caller. - if (IsLosslessIntegralToFloatingCast(target_type, cast_expression.GetReturnType())) { - string error_message; - auto roundtrip = cast_constant.TryCastAs(context, cast_expression.GetReturnType(), &error_message, true); - return roundtrip && *roundtrip == constant_value; - } - if (target_type.id() == LogicalTypeId::DECIMAL && cast_expression.GetReturnType().id() == LogicalTypeId::DECIMAL) { - // a narrowing decimal cast of the constant is fine if the constant round-trips exactly - string error_message; - auto roundtrip = cast_constant.TryCastAs(context, cast_expression.GetReturnType(), &error_message, true); + // The constant must round-trip exactly; the column side is checked by the caller. + if (BoundCastExpression::IsLosslessIntegralToFloatingCast(target_type, cast_type) || + (target_type.id() == LogicalTypeId::DECIMAL && cast_type.id() == LogicalTypeId::DECIMAL)) { + auto roundtrip = cast_constant.TryCastAs(context, cast_type, nullptr, true); return roundtrip && *roundtrip == constant_value; } - if (target_type.id() != LogicalTypeId::DATE || cast_expression.GetReturnType().id() != LogicalTypeId::TIMESTAMP) { + if (target_type.id() != LogicalTypeId::DATE || cast_type.id() != LogicalTypeId::TIMESTAMP) { return false; } return DateTimestampComparisonIsInvertible(context, expr, cast_expression, constant_value, cast_constant, column_ref_left, replacement); } +//! Replaces CAST(x) c with x source_constant, keeping the side the cast was on +static void ReplaceCastWithChild(BoundFunctionExpression &expr, BoundFunctionExpression &cast_expression, + Value source_constant, bool column_ref_left) { + auto child_expression = std::move(BoundCastExpression::ChildMutable(cast_expression)); + auto new_constant_expr = make_uniq(std::move(source_constant)); + auto &left = BoundComparisonExpression::LeftMutable(expr); + auto &right = BoundComparisonExpression::RightMutable(expr); + if (column_ref_left) { + left = std::move(child_expression); + right = std::move(new_constant_expr); + } else { + left = std::move(new_constant_expr); + right = std::move(child_expression); + } +} + +static bool IsEqualityComparisonType(ExpressionType type) { + switch (type) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOTEQUAL: + case ExpressionType::COMPARE_NOT_DISTINCT_FROM: + case ExpressionType::COMPARE_DISTINCT_FROM: + return true; + default: + return false; + } +} + +//! Rewrites an (in)equality comparison of CAST(x) with a constant c, for a cast that is invertible for equality: +//! CAST(x) = c holds for exactly the source value CAST(c), if that value casts back to c, and for no value otherwise +static unique_ptr SimplifyEqualityCastComparison(ClientContext &context, BoundFunctionExpression &expr, + BoundFunctionExpression &cast_expression, + const Value &constant_value, bool column_ref_left, + bool &changes_made) { + D_ASSERT(!constant_value.IsNull()); + auto source_constant = BoundCastExpression::TryInvertConstant(context, cast_expression, constant_value); + if (!source_constant) { + auto &child = BoundCastExpression::ChildMutable(cast_expression); + auto comparison_type = expr.GetExpressionType(); + switch (comparison_type) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOTEQUAL: + return ExpressionRewriter::ConstantOrNull( + context, std::move(child), Value::BOOLEAN(comparison_type == ExpressionType::COMPARE_NOTEQUAL)); + default: + // folding to a constant drops the child, which could throw or have side effects + if (child->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return nullptr; + } + return make_uniq( + Value::BOOLEAN(comparison_type == ExpressionType::COMPARE_DISTINCT_FROM)); + } + } + ReplaceCastWithChild(expr, cast_expression, std::move(*source_constant), column_ref_left); + changes_made = true; + return nullptr; +} + static unique_ptr CreateNullCheckExpression(ExpressionType expression_type, unique_ptr child) { D_ASSERT(expression_type == ExpressionType::OPERATOR_IS_NULL || expression_type == ExpressionType::OPERATOR_IS_NOT_NULL); @@ -242,8 +267,13 @@ unique_ptr ComparisonSimplificationRule::Apply(LogicalOperator &op, //! invertible in practice. auto &cast_expression = column_ref_expr.Cast(); auto target_type = BoundCastExpression::SourceType(cast_expression); + if (!constant_value.IsNull() && IsEqualityComparisonType(expr.GetExpressionType()) && + BoundCastExpression::CastIsInvertibleForEquality(target_type, cast_expression.GetReturnType())) { + return SimplifyEqualityCastComparison(GetContext(), expr, cast_expression, constant_value, column_ref_left, + changes_made); + } if (!BoundCastExpression::CastIsInvertible(target_type, cast_expression.GetReturnType()) && - !IsLosslessIntegralToFloatingCast(target_type, cast_expression.GetReturnType())) { + !BoundCastExpression::IsLosslessIntegralToFloatingCast(target_type, cast_expression.GetReturnType())) { return nullptr; } @@ -266,15 +296,7 @@ unique_ptr ComparisonSimplificationRule::Apply(LogicalOperator &op, } //! We can cast, now we change our column_ref_expression from an operator cast to a column reference - auto child_expression = std::move(BoundCastExpression::ChildMutable(cast_expression)); - auto new_constant_expr = make_uniq(cast_constant); - if (column_ref_left) { - left = std::move(child_expression); - right = std::move(new_constant_expr); - } else { - left = std::move(new_constant_expr); - right = std::move(child_expression); - } + ReplaceCastWithChild(expr, cast_expression, std::move(cast_constant), column_ref_left); changes_made = true; } return nullptr; diff --git a/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp b/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp index 53aafe300..b7300921d 100644 --- a/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/conjunction_simplification.cpp @@ -43,7 +43,7 @@ unique_ptr ConjunctionSimplificationRule::Apply(LogicalOperator &op, if (!ExpressionExecutor::TryEvaluateScalar(GetContext(), constant_expr, constant_value)) { return nullptr; } - constant_value = constant_value.DefaultCastAs(LogicalType::BOOLEAN); + constant_value = constant_value.CastAs(GetContext(), LogicalType::BOOLEAN); if (constant_value.IsNull()) { // FALSE and NULL have the same effect in filters and joins if (conjunction.GetExpressionType() != ExpressionType::CONJUNCTION_OR || !is_root || diff --git a/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp b/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp index 8b91ea949..d94a72573 100644 --- a/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp +++ b/src/duckdb/src/optimizer/rule/contains_to_in_clause.cpp @@ -44,7 +44,7 @@ unique_ptr ContainsToInClauseRule::Apply(LogicalOperator &op, vector vector non_null_elements; for (const auto &elem : ListValue::GetChildren(list_val)) { if (!elem.IsNull()) { - non_null_elements.emplace_back(elem.DefaultCastAs(child_type)); + non_null_elements.emplace_back(elem.CastAs(GetContext(), child_type)); } } diff --git a/src/duckdb/src/optimizer/rule/distributivity.cpp b/src/duckdb/src/optimizer/rule/distributivity.cpp index 285e65f73..2763c9c63 100644 --- a/src/duckdb/src/optimizer/rule/distributivity.cpp +++ b/src/duckdb/src/optimizer/rule/distributivity.cpp @@ -15,12 +15,15 @@ DistributivityRule::DistributivityRule(ExpressionRewriter &rewriter) : Rule(rewr } void DistributivityRule::AddExpressionSet(Expression &expr, expression_set_t &set) { + // a volatile conjunct in two branches is two evaluations, so it is never common to the branches if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { auto &and_expr = expr.Cast(); for (auto &child : and_expr.GetChildrenMutable()) { - set.insert(*child); + if (!child->IsVolatile()) { + set.insert(*child); + } } - } else { + } else if (!expr.IsVolatile()) { set.insert(expr); } } diff --git a/src/duckdb/src/optimizer/rule/equal_or_null_simplification.cpp b/src/duckdb/src/optimizer/rule/equal_or_null_simplification.cpp index 6be67850b..635a256d0 100644 --- a/src/duckdb/src/optimizer/rule/equal_or_null_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/equal_or_null_simplification.cpp @@ -59,6 +59,10 @@ static unique_ptr TryRewriteEqualOrIsNull(Expression &equal_expr, Ex auto &equal_cast = equal_expr.Cast(); auto &and_cast = and_expr.Cast(); + // the IS NULL tests evaluate a volatile operand again, so the rewrite would merge two evaluations into one + if (equal_cast.IsVolatile()) { + return nullptr; + } if (and_cast.GetChildren().size() != 2) { return nullptr; diff --git a/src/duckdb/src/optimizer/rule/in_clause_simplification_rule.cpp b/src/duckdb/src/optimizer/rule/in_clause_simplification_rule.cpp index 0b9b5974b..c06c276c1 100644 --- a/src/duckdb/src/optimizer/rule/in_clause_simplification_rule.cpp +++ b/src/duckdb/src/optimizer/rule/in_clause_simplification_rule.cpp @@ -17,6 +17,39 @@ InClauseSimplificationRule::InClauseSimplificationRule(ExpressionRewriter &rewri root = std::move(op); } +//! Rewrites CAST(x) IN (constants) for a cast that is invertible for equality: each constant c is replaced by the +//! source value CAST(c) if that value casts back to c, and dropped otherwise, as no source value can match it +static unique_ptr SimplifyEqualityCast(ClientContext &context, BoundOperatorExpression &expr, + BoundFunctionExpression &cast_expression, bool &changes_made) { + auto source_type = BoundCastExpression::SourceType(cast_expression); + auto &children = expr.GetChildrenMutable(); + vector> new_children; + new_children.push_back(nullptr); + for (idx_t i = 1; i < children.size(); i++) { + if (children[i]->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + return nullptr; + } + auto &constant_value = children[i]->Cast().GetValue(); + if (constant_value.IsNull()) { + new_children.push_back(make_uniq(Value(source_type))); + continue; + } + auto source_constant = BoundCastExpression::TryInvertConstant(context, cast_expression, constant_value); + if (source_constant) { + new_children.push_back(make_uniq(std::move(*source_constant))); + } + } + auto child = std::move(BoundCastExpression::ChildMutable(cast_expression)); + if (new_children.size() == 1) { + D_ASSERT(expr.GetExpressionType() == ExpressionType::COMPARE_IN); + return ExpressionRewriter::ConstantOrNull(context, std::move(child), Value::BOOLEAN(false)); + } + new_children[0] = std::move(child); + children.swap(new_children); + changes_made = true; + return nullptr; +} + unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, bool is_root) { auto &expr = bindings[0].get().Cast(); @@ -28,6 +61,10 @@ unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, ve // a TRY_CAST turns failing values into NULL, which is lost when the cast is removed return nullptr; } + auto target_type = BoundCastExpression::SourceType(cast_expression); + if (BoundCastExpression::CastIsInvertibleForEquality(target_type, cast_expression.GetReturnType())) { + return SimplifyEqualityCast(GetContext(), expr, cast_expression, changes_made); + } if (BoundCastExpression::Child(cast_expression).GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { return nullptr; } @@ -35,7 +72,6 @@ unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, ve //! and apply a cast to the constant expressions. We can only do this //! if the semantics do not change, which only happens when BOTH casts //! are invertible. - auto target_type = BoundCastExpression::SourceType(cast_expression); if (!BoundCastExpression::CastIsInvertible(target_type, cast_expression.GetReturnType())) { return nullptr; } @@ -50,7 +86,7 @@ unique_ptr InClauseSimplificationRule::Apply(LogicalOperator &op, ve if (!BoundCastExpression::CastIsInvertible(constant_value.type(), target_type)) { return nullptr; } - auto new_constant = constant_value.DefaultTryCastAs(target_type); + auto new_constant = constant_value.TryCastAs(GetContext(), target_type); if (!new_constant) { return nullptr; } else { diff --git a/src/duckdb/src/optimizer/rule/monotone_preimage.cpp b/src/duckdb/src/optimizer/rule/monotone_preimage.cpp index 92eb239df..a29d86d6d 100644 --- a/src/duckdb/src/optimizer/rule/monotone_preimage.cpp +++ b/src/duckdb/src/optimizer/rule/monotone_preimage.cpp @@ -199,7 +199,7 @@ unique_ptr MonotonePreimageRule::Apply(LogicalOperator &op, vector().distinct_type == DistinctType::DISTINCT_ON) { - // the columns it does not deduplicate on pass through by position - for (auto &binding : op.children[0]->GetColumnBindings()) { - read.insert(binding); - } - } VisitOperatorChildren(op); } @@ -344,11 +336,6 @@ class SelfJoinAggregateRewriter { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: Walk(op.children[0], AggregateIgnoresDuplicates(op.Cast())); return; - case LogicalOperatorType::LOGICAL_DISTINCT: - // its targets are expressions, so what it deduplicates on counts as read, and so does every column a - // DISTINCT ON passes through - Walk(op.children[0], true); - return; case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { // its references are all below its second child, so they are all seen before its definition is auto &cte = op.Cast(); diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp index 5769ffb0d..41efa1d5e 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/client_context.hpp" #include "duckdb/common/assert.hpp" #include "duckdb/common/column_index.hpp" #include "duckdb/common/enums/expression_type.hpp" @@ -121,7 +122,7 @@ bool TryGetMinMaxColumnInfo(const Expression &expr, MinMaxColumnInfo &info) { return true; } -bool TryGetValueFromStats(const PartitionStatistics &stats, const StorageIndex &storage_index, +bool TryGetValueFromStats(Context &context, const PartitionStatistics &stats, const StorageIndex &storage_index, const ValueComparator &comparator, const LogicalType &result_type, Value &result) { if (!stats.partition_row_group) { return false; @@ -153,7 +154,7 @@ bool TryGetValueFromStats(const PartitionStatistics &stats, const StorageIndex & if (result.type() == result_type) { return true; } - auto cast = result.DefaultTryCastAs(result_type); + auto cast = result.TryCastAs(context, result_type); if (!cast) { return false; } @@ -499,13 +500,14 @@ void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_p auto &comparator = comparators[agg_idx]; Value agg_result; - if (!TryGetValueFromStats(partition_stats[0], storage_index, *comparator, result_type, agg_result)) { + if (!TryGetValueFromStats(context.GetContext(), partition_stats[0], storage_index, *comparator, result_type, + agg_result)) { return; } for (idx_t partition_idx = 1; partition_idx < partition_stats.size(); partition_idx++) { Value rhs; - if (!TryGetValueFromStats(partition_stats[partition_idx], storage_index, *comparator, result_type, - rhs)) { + if (!TryGetValueFromStats(context.GetContext(), partition_stats[partition_idx], storage_index, + *comparator, result_type, rhs)) { return; } if (!comparator->Compare(agg_result, rhs)) { diff --git a/src/duckdb/src/optimizer/window_self_join.cpp b/src/duckdb/src/optimizer/window_self_join.cpp index 54e181e09..a60428813 100644 --- a/src/duckdb/src/optimizer/window_self_join.cpp +++ b/src/duckdb/src/optimizer/window_self_join.cpp @@ -105,6 +105,7 @@ static unique_ptr TranslateAggregate(ClientContext &client, const Bo const auto aggr_ordered = (agg_func.GetOrderDependent() == AggregateOrderDependent::ORDER_DEPENDENT); auto result = make_uniq(std::move(agg_func), std::move(children), std::move(filter), std::move(bind_info), aggr_type); + result->SetReturnType(w_expr.GetReturnType()); if (!aggr_ordered) { // ORDER BY is a NOP, so drop it. diff --git a/src/duckdb/src/parser/expression/window_expression.cpp b/src/duckdb/src/parser/expression/window_expression.cpp index 086e6d5c9..54219d59a 100644 --- a/src/duckdb/src/parser/expression/window_expression.cpp +++ b/src/duckdb/src/parser/expression/window_expression.cpp @@ -13,11 +13,13 @@ vector> WindowExpression::SerializedChildren(Serial idx_t nargs = arguments.size(); if (!serializer.ShouldSerialize(StorageVersion::V2_0_0) && (qualified_name.Name() == "lead" || qualified_name.Name() == "lag")) { - nargs = 1; + nargs = MinValue(nargs, 1); } for (idx_t i = 0; i < nargs; ++i) { - result.emplace_back(arguments[i].GetExpression().Copy()); + auto copy = arguments[i].GetExpression().Copy(); + copy->SetAlias(arguments[i].GetName()); + result.emplace_back(std::move(copy)); } return result; @@ -107,14 +109,9 @@ void WindowExpression::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault(202, "catalog", qualified_name.Catalog()); if (!serializer.ShouldSerialize(StorageVersion::V2_0_0)) { - // Legacy serialization. - vector> children; - for (auto &arg : arguments) { - auto copy = arg.GetExpression().Copy(); - copy->SetAlias(arg.GetName()); - children.push_back(std::move(copy)); - } - serializer.WritePropertyWithDefault>>(203, "children", children); + // Legacy serialization: the offset and default of lead and lag go into properties 210 and 211 instead + serializer.WritePropertyWithDefault>>(203, "children", + SerializedChildren(serializer)); } serializer.WritePropertyWithDefault>>(204, "partitions", partitions); @@ -176,8 +173,16 @@ unique_ptr WindowExpression::Deserialize(Deserializer &deseria deserializer.ReadProperty(207, "end", result->end); deserializer.ReadPropertyWithDefault>(208, "start_expr", result->start_expr); deserializer.ReadPropertyWithDefault>(209, "end_expr", result->end_expr); - deserializer.ReadDeletedProperty>(210, "offset_expr"); - deserializer.ReadDeletedProperty>(211, "default_expr"); + // v1.x stores the offset and default of lead and lag here, 2.0 stores them as arguments + unique_ptr legacy_expr; + deserializer.ReadPropertyWithDefault>(210, "offset_expr", legacy_expr); + if (legacy_expr) { + result->arguments.emplace_back(std::move(legacy_expr)); + } + deserializer.ReadPropertyWithDefault>(211, "default_expr", legacy_expr); + if (legacy_expr) { + result->arguments.emplace_back(std::move(legacy_expr)); + } deserializer.ReadPropertyWithDefault(212, "ignore_nulls", result->ignore_nulls); deserializer.ReadPropertyWithDefault>(213, "filter_expr", result->filter_expr); deserializer.ReadPropertyWithExplicitDefault(214, "exclude_clause", result->exclude_clause, diff --git a/src/duckdb/src/parser/peg/compiled_grammar.cpp b/src/duckdb/src/parser/peg/compiled_grammar.cpp index 391617b9a..65301052a 100644 --- a/src/duckdb/src/parser/peg/compiled_grammar.cpp +++ b/src/duckdb/src/parser/peg/compiled_grammar.cpp @@ -109,6 +109,9 @@ terminal_rule_overrides_t ParsedGrammar::BuildTerminalRuleOverrides(const PEGKey make_uniq(SuggestionState::SUGGEST_VARIABLE, keyword_helper)); AddTerminalRuleOverride(overrides, "TableFunctionName", make_uniq(SuggestionState::SUGGEST_TABLE_FUNCTION_NAME, keyword_helper)); + AddTerminalRuleOverride( + overrides, "ReservedTableFunctionName", + make_uniq(SuggestionState::SUGGEST_TABLE_FUNCTION_NAME, keyword_helper)); AddTerminalRuleOverride(overrides, "TypeName", make_uniq(SuggestionState::SUGGEST_TYPE_NAME, keyword_helper)); AddTerminalRuleOverride(overrides, "ReservedTypeName", diff --git a/src/duckdb/src/parser/peg/matcher_factory.cpp b/src/duckdb/src/parser/peg/matcher_factory.cpp index 8f36c9787..f4f4af052 100644 --- a/src/duckdb/src/parser/peg/matcher_factory.cpp +++ b/src/duckdb/src/parser/peg/matcher_factory.cpp @@ -247,7 +247,6 @@ Matcher &MatcherFactory::CreateRootMatcher(const string &root_rule) { // START GENERATED RULE LABELS //===--------------------------------------------------------------------===// LabelRule("Expression", "an expression"); - LabelRule("LambdaArrowExpression", "an expression"); LabelRule("LogicalOrExpression", "an expression"); LabelRule("LogicalAndExpression", "an expression"); LabelRule("LogicalNotExpression", "an expression"); diff --git a/src/duckdb/src/parser/peg/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index 137cb1f4d..f709da5cb 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -95,6 +95,7 @@ static const char *const PEG_RULE_NAMES[] = { "ReservedFunctionName", "ReservedTypeName", "TableFunctionName", + "ReservedTableFunctionName", "ConstraintName", "SequenceName", "CollationName", @@ -625,8 +626,6 @@ static const char *const PEG_RULE_NAMES[] = { "SingleExpression", "Expression", "ColumnDefaultExpr", - "LambdaArrowExpression", - "SingleArrowPair", "LogicalOrExpression", "LogicalOrExpressionTail", "ColDefOrExpr", @@ -698,6 +697,12 @@ static const char *const PEG_RULE_NAMES[] = { "OtherOperatorTail", "AnyAllSubqueryTail", "OtherOperatorExpressionTail", + "SingleArrowTail", + "SingleArrowBody", + "ArrowChainBody", + "ArrowChainTail", + "DoubleArrowTail", + "ArrowFullBody", "OtherOperator", "AnyAllParsedOperator", "NamedOtherOperator", @@ -1032,6 +1037,8 @@ static const char *const PEG_RULE_NAMES[] = { "TableFunctionAliasColon", "WithOrdinality", "QualifiedTableFunction", + "CatalogReservedSchemaTableFunctionName", + "TableFunctionNameAsQualifiedName", "TableFunctionArguments", "FunctionArgument", "NamedFunctionArgument", diff --git a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp index 61c5ce828..214fb8cc4 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp @@ -108,7 +108,6 @@ PEGTransformerFactory::PEGTransformerFactory(ParsedGrammar &grammar_p) : grammar //===--------------------------------------------------------------------===// collapsible_rules.insert("Expression"); collapsible_rules.insert("ColumnDefaultExpr"); - collapsible_rules.insert("LambdaArrowExpression"); collapsible_rules.insert("LogicalOrExpression"); collapsible_rules.insert("ColDefOrExpr"); collapsible_rules.insert("LogicalAndExpression"); @@ -154,13 +153,13 @@ PEGTransformerFactory::PEGTransformerFactory(ParsedGrammar &grammar_p) : grammar grammar.SetExpressionDepth("NestedType", ExpressionDepthKind::NESTING); grammar.SetExpressionDepth("SubqueryReference", ExpressionDepthKind::NESTING); grammar.SetExpressionDepth("CustomPrefixExpression", ExpressionDepthKind::NESTING); - grammar.SetExpressionDepth("LambdaArrowExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("NotExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("IsExpressionContinuation", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("IsDistinctFromExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("ComparisonExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("BetweenInLikeExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("InfixOtherOperatorExpression", ExpressionDepthKind::CHAIN); + grammar.SetExpressionDepth("ArrowChainBody", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("BitwiseExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("TildeExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("AdditiveExpression", ExpressionDepthKind::CHAIN); diff --git a/src/duckdb/src/parser/peg/transformer/transform_expression.cpp b/src/duckdb/src/parser/peg/transformer/transform_expression.cpp index 444640ba5..4a3bb0a03 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_expression.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_expression.cpp @@ -625,25 +625,6 @@ PEGTransformerFactory::TransformColumnDefaultExpr(PEGTransformer &transformer, return col_def_or_expr; } -unique_ptr PEGTransformerFactory::TransformLambdaArrowExpression( - PEGTransformer &transformer, unique_ptr logical_or_expression, - optional>> single_arrow_pair) { - auto expr = std::move(logical_or_expression); - if (!single_arrow_pair) { - return expr; - } - for (auto &right_expr : *single_arrow_pair) { - expr = make_uniq(std::move(expr), std::move(right_expr)); - } - return expr; -} - -unique_ptr -PEGTransformerFactory::TransformSingleArrowPair(PEGTransformer &transformer, - unique_ptr logical_or_expression) { - return logical_or_expression; -} - static unique_ptr FoldConjunctionExpression(PEGTransformer &transformer, unique_ptr expression, optional>> tails, @@ -1391,6 +1372,16 @@ static unique_ptr TransformOperatorFunction(const string &oper return std::move(result); } +static unique_ptr TransformArrowChainLink(unique_ptr expr, ArrowChainLink link) { + if (!link.is_double_arrow) { + return make_uniq(std::move(expr), std::move(link.expression)); + } + vector> children; + children.push_back(std::move(expr)); + children.push_back(std::move(link.expression)); + return TransformOperatorFunction("->>", std::move(children)); +} + unique_ptr PEGTransformerFactory::TransformInfixOtherOperatorExpression(PEGTransformer &transformer, unique_ptr bitwise_expression, @@ -1401,6 +1392,13 @@ PEGTransformerFactory::TransformInfixOtherOperatorExpression(PEGTransformer &tra } for (auto &other_operator_expr : *other_operator_tail) { auto right_expr = std::move(other_operator_expr.expression); + if (other_operator_expr.is_arrow) { + expr = make_uniq(std::move(expr), std::move(right_expr)); + for (auto &link : other_operator_expr.arrow_chain) { + expr = TransformArrowChainLink(std::move(expr), std::move(link)); + } + continue; + } if (other_operator_expr.op.is_any_all) { auto op_string = other_operator_expr.op.name; auto is_any = other_operator_expr.op.is_any; @@ -1505,6 +1503,49 @@ PEGTransformerFactory::TransformOtherOperatorExpressionTail(PEGTransformer &tran return result; } +OtherOperatorTail PEGTransformerFactory::TransformSingleArrowTail(PEGTransformer &transformer, + ArrowBody single_arrow_body) { + OtherOperatorTail result; + result.op.name = "->"; + result.is_arrow = true; + result.expression = std::move(single_arrow_body.expression); + result.arrow_chain = std::move(single_arrow_body.arrow_chain); + return result; +} + +OtherOperatorTail PEGTransformerFactory::TransformDoubleArrowTail(PEGTransformer &transformer, + unique_ptr bitwise_expression) { + OtherOperatorTail result; + result.op.name = "->>"; + result.expression = std::move(bitwise_expression); + return result; +} + +ArrowBody PEGTransformerFactory::TransformArrowChainBody(PEGTransformer &transformer, + unique_ptr bitwise_expression, + vector arrow_chain_tail) { + ArrowBody result; + result.expression = std::move(bitwise_expression); + // flatten the chain: a nested '->' carries the arrows that follow its own operand + for (auto &tail : arrow_chain_tail) { + ArrowChainLink link; + link.is_double_arrow = !tail.is_arrow; + link.expression = std::move(tail.expression); + result.arrow_chain.push_back(std::move(link)); + for (auto &nested_link : tail.arrow_chain) { + result.arrow_chain.push_back(std::move(nested_link)); + } + } + return result; +} + +ArrowBody PEGTransformerFactory::TransformArrowFullBody(PEGTransformer &transformer, + unique_ptr logical_or_expression) { + ArrowBody result; + result.expression = std::move(logical_or_expression); + return result; +} + ParsedOperator PEGTransformerFactory::TransformAnyAllParsedOperator(PEGTransformer &transformer, const pair &any_all_operator) { ParsedOperator result; 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 6ebd8b728..0f4e3fadb 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -3479,7 +3479,7 @@ static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::FunctionExpr {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::LambdaArrowExpression, +static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::LogicalOrExpression, TransformChildKind::REQUIRED, 0, 0, @@ -3495,14 +3495,14 @@ static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::ColDefOrExpr {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::SingleArrowPair, +static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::LogicalOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LogicalOrExpression, + {PEGRuleId::LogicalAndExpression, TransformChildKind::REQUIRED, 0, 0, @@ -3510,7 +3510,7 @@ static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::SingleArrowP {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::LogicalOrExpression, +static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::LogicalAndExpression, TransformChildKind::REQUIRED, 1, 0, @@ -3518,14 +3518,14 @@ static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::LogicalOrExp {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::LogicalOrExpressionTail, +static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::ColDefOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LogicalAndExpression, + {PEGRuleId::ColDefAndExpr, TransformChildKind::REQUIRED, 0, 0, @@ -3533,7 +3533,7 @@ static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::LogicalOrExp {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalAndExpression, +static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::ColDefAndExpr, TransformChildKind::REQUIRED, 1, 0, @@ -3541,14 +3541,14 @@ static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalAndEx {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::ColDefOrExpressionTail, +static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColDefAndExpr, + {PEGRuleId::LogicalNotExpression, TransformChildKind::REQUIRED, 0, 0, @@ -3556,7 +3556,7 @@ static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::ColDefOrExpr {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::ColDefAndExpr, +static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::LogicalNotExpression, TransformChildKind::REQUIRED, 1, 0, @@ -3564,14 +3564,14 @@ static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::ColDefAndExp {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::LogicalAndExpressionTail, +static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LogicalNotExpression, + {PEGRuleId::IsDistinctFromExpression, TransformChildKind::REQUIRED, 0, 0, @@ -3579,7 +3579,7 @@ static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::LogicalAndEx {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::LogicalNotExpression, +static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::IsDistinctFromExpression, TransformChildKind::REQUIRED, 1, 0, @@ -3587,30 +3587,7 @@ static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::LogicalNotEx {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::ColDefAndExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IsDistinctFromExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::IsDistinctFromExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsExpression, +static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3624,16 +3601,16 @@ static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::NotKeyword, +static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::NotKeyword, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsExpressionContinuation, +static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsExpressionContinuation, TransformChildKind::OPTIONAL, 1, 1, @@ -3647,8 +3624,8 @@ 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::IsExpressionTail, +static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3662,64 +3639,64 @@ static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsTest, +static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsTest, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::CastOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::IsLiteralValue, +static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::IsLiteralValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::IsNullOperator, +static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::IsNullOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3733,8 +3710,8 @@ static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::IsDistinctFr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::ComparisonExpression, +static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::ComparisonExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3748,8 +3725,8 @@ static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3763,8 +3740,8 @@ static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonOperand, +static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::ComparisonOperand, TransformChildKind::REQUIRED, 1, 1, @@ -3778,8 +3755,8 @@ static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonOp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3793,8 +3770,8 @@ static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::BetweenLikeOp, +static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::BetweenLikeOp, TransformChildKind::OPTIONAL, 2, 2, @@ -3815,8 +3792,8 @@ static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::BetweenLikeO false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::CastOperator, TransformChildKind::OPTIONAL_REPEAT, 2, 1, @@ -3830,16 +3807,16 @@ static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::CastOperator false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::BetweenLikeOpExpression, +static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::BetweenLikeOpExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::EscapeClause, +static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::EscapeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3860,48 +3837,48 @@ static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::EscapeClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::InExpression, +static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::InExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 4, 1, @@ -3915,16 +3892,16 @@ static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::InfixOtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::InfixOtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3938,8 +3915,8 @@ 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, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -3953,8 +3930,8 @@ static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3968,40 +3945,71 @@ static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::AnyAllOperator, +static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::SingleArrowBody, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::ArrowChainTail, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::AnyOrAll, +static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::AnyAllOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::QualifiedOperatorContents, +static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::AnyOrAll, TransformChildKind::REQUIRED, 1, 0, false, - {1, TRANSFORM_PATH_END, 0}, + {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::ColIdDot, +static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::QualifiedOperatorContents, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::ColIdDot, TransformChildKind::OPTIONAL_REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::BitwiseExpressionTail, +static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::BitwiseExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4015,8 +4023,8 @@ static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4030,8 +4038,8 @@ static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::TildeExpress false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AdditiveExpression, +static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AdditiveExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4045,8 +4053,8 @@ static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AdditiveExpressionTail, +static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::AdditiveExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4060,8 +4068,8 @@ static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::MultiplicativeExpression, +static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::MultiplicativeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4075,8 +4083,8 @@ static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::Multiplicati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::MultiplicativeExpressionTail, +static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::MultiplicativeExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4090,8 +4098,8 @@ static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::Multiplicati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::ExponentiationExpression, +static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::ExponentiationExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4105,8 +4113,8 @@ static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::ExponentiationExpressionTail, +static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::ExponentiationExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4120,8 +4128,8 @@ static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::CollateExpression, +static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::CollateExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4135,8 +4143,8 @@ static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::CollateExpressionTail, +static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::CollateExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4150,16 +4158,16 @@ static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::AtTimeZoneExpression, +static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::AtTimeZoneExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::AtTimeZoneExpressionTail, +static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::AtTimeZoneExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4173,24 +4181,24 @@ static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::AtTimeZoneEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::UnaryExpression, +static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::UnaryExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::IndirectionList, +static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::IndirectionList, TransformChildKind::OPTIONAL, 1, 1, @@ -4204,24 +4212,24 @@ static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::IndirectionL false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::Indirection, +static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::Indirection, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::MethodExpression, +static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::MethodExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::MethodExpressionArguments, +static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::MethodExpressionArguments, TransformChildKind::REQUIRED, 1, 1, @@ -4235,16 +4243,16 @@ static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::MethodExpres false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::MethodExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::MethodExpressionArgumentList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -4272,16 +4280,16 @@ static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::SliceBound, +static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::SliceBound, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::SliceUpperBound, +static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::SliceUpperBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4295,16 +4303,16 @@ static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::SliceUpperBo false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::StepSliceBound, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::StepSliceBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4318,32 +4326,32 @@ static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::StepSliceBou false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::ExtractArguments, +static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::ExtractArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4357,8 +4365,8 @@ static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -4372,24 +4380,24 @@ static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::NullIfArguments, +static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::NullIfArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::PositionArguments, +static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::PositionArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4403,32 +4411,32 @@ static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::SubstringArguments, +static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::SubstringArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::SubstringFromFor, +static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::SubstringFromFor, TransformChildKind::REQUIRED, 1, 1, @@ -4442,8 +4450,8 @@ static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::SubstringFro false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 1, 1, @@ -4457,24 +4465,24 @@ static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::ForExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::TrimArguments, +static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::TrimArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 2, @@ -4495,24 +4503,24 @@ static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::OverlayArguments, +static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::OverlayArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 4, 3, @@ -4540,16 +4548,16 @@ static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::ExtractDatePart, +static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::ExtractDatePart, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, 1, @@ -4563,8 +4571,8 @@ static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::ExternalReso false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 5, 1, @@ -4578,16 +4586,16 @@ static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::ColId, +static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::ColId, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::AttachOptions, +static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 4, 2, @@ -4608,8 +4616,8 @@ static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::AttachOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::AttachOptions, +static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 3, 1, @@ -4623,16 +4631,16 @@ static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::AttachOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 10, 7, @@ -4688,24 +4696,24 @@ static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 8, 8, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::InsertByName, +static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::InsertByName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::InsertByPosition, +static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::InsertByPosition, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::InsertAlias, +static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::InsertAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -4719,8 +4727,8 @@ static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::InsertAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::OnConflictAction, +static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::OnConflictAction, TransformChildKind::REQUIRED, 3, 1, @@ -4734,8 +4742,8 @@ static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::OnConflictAc false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 1, 1, @@ -4749,16 +4757,16 @@ static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::ConstraintName, +static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::ConstraintName, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 4, 1, @@ -4772,16 +4780,16 @@ static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::ExtensionAlias, +static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::ExtensionAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -4802,8 +4810,8 @@ static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::ExtensionAli false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::VersionNumber, +static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::VersionNumber, TransformChildKind::OPTIONAL, 5, 3, @@ -4831,16 +4839,16 @@ static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::VersionNumbe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::IdentifierOrStringLiteral, +static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::IdentifierOrStringLiteral, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::RepositoryPublicKey, +static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::RepositoryPublicKey, TransformChildKind::OPTIONAL, 7, 4, @@ -4875,8 +4883,8 @@ static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::RepositoryPu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::ColIdOrString, TransformChildKind::REQUIRED, 4, 1, @@ -4890,8 +4898,8 @@ static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ColIdOrStrin false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -4905,24 +4913,16 @@ static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::MatchRecognizeClause, +static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::MatchRecognizeClause, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::WindowPartition, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::OrderByClause, +static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::WindowPartition, TransformChildKind::REQUIRED, 0, 0, @@ -4930,7 +4930,7 @@ static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::OrderByClaus {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_372 = {FRAME_CHILDREN_357, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::MeasuresClause, +static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 0, 0, @@ -4938,7 +4938,7 @@ static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::MeasuresClau {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_358, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::RowsPerMatch, +static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::MeasuresClause, TransformChildKind::REQUIRED, 0, 0, @@ -4946,7 +4946,7 @@ static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::RowsPerMatch {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_374 = {FRAME_CHILDREN_359, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::AfterMatchSkip, +static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::RowsPerMatch, TransformChildKind::REQUIRED, 0, 0, @@ -4954,7 +4954,7 @@ static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::AfterMatchSk {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_360, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::PatternClause, +static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::AfterMatchSkip, TransformChildKind::REQUIRED, 0, 0, @@ -4962,7 +4962,7 @@ static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::PatternClaus {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_361, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::SubsetClause, +static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::PatternClause, TransformChildKind::REQUIRED, 0, 0, @@ -4970,7 +4970,7 @@ static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::SubsetClause {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_362, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::DefineClause, +static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::SubsetClause, TransformChildKind::REQUIRED, 0, 0, @@ -4978,15 +4978,23 @@ static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::DefineClause {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_363, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::MeasuresElement, +static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::DefineClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_364, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::MeasuresElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_364, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_365, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 1, @@ -5000,48 +5008,48 @@ static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_365, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::AllRowsEmptyMatches, +static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_366, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::AllRowsEmptyMatches, TransformChildKind::OPTIONAL, 4, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::AfterMatchSkipTarget, +static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::AfterMatchSkipTarget, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::RowPatternAlternative, +static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_371, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::RowPatternAlternative, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5055,24 +5063,24 @@ static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::RowPatternAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_371, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::RowPatternTerm, +static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_372, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::RowPatternTerm, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_372, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::RowPatternFactor, +static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_373, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::RowPatternFactor, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_373, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::RowPatternQuantifier, +static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_374, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::RowPatternQuantifier, TransformChildKind::OPTIONAL, 1, 1, @@ -5086,40 +5094,40 @@ static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::RowPatternQu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_374, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_375, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::RowPattern, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_375, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_376, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::QuantifierReluctant, +static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_379, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::QuantifierReluctant, TransformChildKind::OPTIONAL, 1, 1, @@ -5133,24 +5141,24 @@ static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::QuantifierRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_379, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::QuantifierBounds, +static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_380, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::QuantifierBounds, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_380, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::SubsetElement, +static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_381, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::SubsetElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_381, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_382, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::LIST, 2, 1, @@ -5164,16 +5172,16 @@ static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_382, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::DefineElement, +static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_383, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::DefineElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_383, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_384, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -5187,8 +5195,8 @@ static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_384, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_385, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 7, 5, @@ -5230,16 +5238,16 @@ static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_385, 6, 6, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::TableRef, +static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_386, 6, 6, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::TableRef, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_386, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_387, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 4, 1, @@ -5253,48 +5261,48 @@ static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_387, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::UpdateMatchInfo, +static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_388, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::UpdateMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_388, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::UpdateMatchSetClause, +static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_389, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::UpdateMatchSetClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_389, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_390, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_390, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::InsertMatchInfo, +static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_391, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::InsertMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_391, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_392, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_392, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_393, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 1, @@ -5308,16 +5316,16 @@ static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_393, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::UpdateMatchSetInfo, +static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_394, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::UpdateMatchSetInfo, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_394, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_395, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 6, 2, @@ -5338,24 +5346,24 @@ static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_395, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::PivotColumnList, +static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_396, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::PivotColumnList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_396, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::PivotColumnEntry, +static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::PivotColumnEntry, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_397, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_398, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 2, 1, @@ -5369,8 +5377,8 @@ static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::SelectStatem false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_398, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_399, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 4, 1, @@ -5384,48 +5392,48 @@ static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::OptionalPare false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_399, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_400, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_400, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_401, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_401, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::PragmaAssignOrFunction, +static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_402, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::PragmaAssignOrFunction, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_402, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::PragmaParameters, +static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_404, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::PragmaParameters, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_404, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_405, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 4, 2, @@ -5446,11 +5454,11 @@ static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::Statement, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_405, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_406[] = { +static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_406, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_407[] = { {PEGRuleId::Type, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_406, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::SelectSetOpChainTail, +static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_407, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::SelectSetOpChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5464,8 +5472,8 @@ static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::SelectSetOpC false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_407, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::IntersectChain, +static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_408, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::IntersectChain, TransformChildKind::REQUIRED, 1, 1, @@ -5479,8 +5487,8 @@ static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_408, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::IntersectChainTail, +static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_409, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::IntersectChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5494,8 +5502,8 @@ static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_409, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::SelectAtom, +static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_410, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::SelectAtom, TransformChildKind::REQUIRED, 1, 1, @@ -5509,16 +5517,16 @@ static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::SelectAtom, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_410, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_411, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_412, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 1, @@ -5532,8 +5540,8 @@ static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::DistinctOrAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_412, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::LimitOffset, +static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_413, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::LimitOffset, TransformChildKind::OPTIONAL, 1, 1, @@ -5547,8 +5555,8 @@ static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::LimitOffset, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_413, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_414, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::OffsetClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5562,8 +5570,8 @@ static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_414, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::LimitClause, +static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_415, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::LimitClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5577,8 +5585,8 @@ static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::LimitClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_415, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_416, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 1, 1, @@ -5592,8 +5600,8 @@ static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::FetchClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_416, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::OffsetClause, TransformChildKind::REQUIRED, 1, 1, @@ -5607,32 +5615,32 @@ static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_418, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_418, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_419, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_419, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::SimpleSelect, +static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_420, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::SimpleSelect, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_420, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::FromClause, +static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_421, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::FromClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5646,8 +5654,8 @@ static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::FromClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::SelectClause, +static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::SelectClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5661,8 +5669,8 @@ static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::SelectClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::CTEBody, +static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::CTEBody, TransformChildKind::REQUIRED, 5, 4, @@ -5697,24 +5705,24 @@ static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::CTEBody, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_423, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_424, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_424, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_425, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_425, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_426, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::TargetList, TransformChildKind::OPTIONAL, 2, 1, @@ -5728,24 +5736,24 @@ static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::TargetList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_426, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::AliasedExpression, +static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_427, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::AliasedExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_427, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::DistinctOnTargets, +static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_428, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::DistinctOnTargets, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_428, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_429, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5780,8 +5788,8 @@ static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_429, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_430, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5816,8 +5824,8 @@ static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_430, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_431, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -5845,8 +5853,8 @@ static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_431, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_432, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -5874,8 +5882,8 @@ static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_432, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_433, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -5889,8 +5897,8 @@ static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_433, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::PivotGroupByList, +static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_434, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::PivotGroupByList, TransformChildKind::OPTIONAL, 3, 2, @@ -5911,16 +5919,16 @@ static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::PivotGroupBy false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_434, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_435, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_435, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_436, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -5941,8 +5949,8 @@ static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::TableAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_436, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::UnpivotValueList, +static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_437, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::UnpivotValueList, TransformChildKind::REPEAT, 2, 1, @@ -5956,16 +5964,16 @@ static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::UnpivotValue false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_437, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::BaseExpression, +static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_438, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::BaseExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_438, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::PivotValueTarget, +static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_439, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::PivotValueTarget, TransformChildKind::REQUIRED, 2, 1, @@ -5979,16 +5987,16 @@ static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::PivotValueTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_439, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::PivotTargetList, +static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_440, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::PivotTargetList, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_440, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::UnpivotTargetList, +static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_441, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::UnpivotTargetList, TransformChildKind::REQUIRED, 2, 1, @@ -6002,16 +6010,16 @@ static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::UnpivotTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_441, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_442, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_442, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_443, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 5, 5, @@ -6053,8 +6061,8 @@ static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_443, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_444, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -6089,8 +6097,8 @@ static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_444, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::SchemaQualification, +static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_445, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::SchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -6098,22 +6106,22 @@ static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::SchemaQualif {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, {PEGRuleId::CatalogQualification, - TransformChildKind::OPTIONAL, + TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_445, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_446, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::FunctionArgument, TransformChildKind::OPTIONAL_LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_446, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_447, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6127,8 +6135,8 @@ static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_447, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_448, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 2, @@ -6149,8 +6157,8 @@ static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_448, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_449, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 2, 1, @@ -6164,24 +6172,24 @@ static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::ColumnAliase false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_449, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_450, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_450, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::AtSpecifier, +static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_451, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::AtSpecifier, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_451, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_452, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6195,8 +6203,8 @@ static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_452, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_453, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6231,8 +6239,8 @@ static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_453, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_454, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6267,16 +6275,16 @@ static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_454, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::ValuesClause, +static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_455, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::ValuesClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_455, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::WithOrdinality, +static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_456, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::WithOrdinality, TransformChildKind::OPTIONAL, 3, 3, @@ -6304,8 +6312,8 @@ static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::WithOrdinali false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_456, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_457, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -6319,8 +6327,8 @@ static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_457, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_458, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 2, 2, @@ -6341,8 +6349,8 @@ static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_458, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_459, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 1, 1, @@ -6356,8 +6364,8 @@ static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::SampleClause false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_459, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::JoinQualifier, +static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_460, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, 3, @@ -6385,8 +6393,8 @@ static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::JoinQualifie false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_460, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_461[] = { +static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_461, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_462[] = { {PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, @@ -6402,8 +6410,8 @@ static const TransformChildPlan FRAME_CHILDREN_461[] = { {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, {PEGRuleId::ColLabel, TransformChildKind::REQUIRED, 2, 0, false, {1, 1, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_461, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::InnerTableRef, +static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_462, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::InnerTableRef, TransformChildKind::REQUIRED, 2, 1, @@ -6417,48 +6425,48 @@ static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::InnerTableRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_462, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::UsingColumnName, +static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_463, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::UsingColumnName, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_463, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::JoinType, +static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_464, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::JoinType, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_464, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::GroupByExpressions, +static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_465, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::GroupByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_465, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SampleEntry, +static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_466, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleEntry, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_466, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::WindowDefinition, +static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_467, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::WindowDefinition, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_467, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleProperties, +static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_468, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::SampleProperties, TransformChildKind::OPTIONAL, 1, 1, @@ -6472,8 +6480,8 @@ static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleProper false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_468, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::RepeatableSample, +static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_469, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::RepeatableSample, TransformChildKind::OPTIONAL, 2, 2, @@ -6494,8 +6502,8 @@ static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::RepeatableSa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_469, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_470[] = { +static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_470, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_471[] = { {PEGRuleId::SampleSeed, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, 1, 0}}, {PEGRuleId::ColId, TransformChildKind::REQUIRED, @@ -6504,16 +6512,16 @@ static const TransformChildPlan FRAME_CHILDREN_470[] = { false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_470, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::SampleSeed, +static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_471, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::SampleSeed, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_471, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::SampleUnit, +static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_472, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::SampleUnit, TransformChildKind::OPTIONAL, 1, 1, @@ -6527,16 +6535,16 @@ static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::SampleUnit, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_472, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_473, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_473, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_474, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -6550,32 +6558,32 @@ static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_474, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_475, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_475, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::OrderByExpressions, +static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_476, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::OrderByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_476, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::OrderByExpression, +static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_477, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::OrderByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_477, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::NullsFirstOrLast, +static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_478, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::NullsFirstOrLast, TransformChildKind::OPTIONAL, 2, 1, @@ -6589,32 +6597,32 @@ static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::NullsFirstOr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_478, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::LimitValue, +static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_479, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::LimitValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_479, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::OffsetValue, +static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_480, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::OffsetValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_480, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::FetchValue, +static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_481, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::FetchValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_481, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_482, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6628,56 +6636,56 @@ static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_482, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::ValuesExpressions, +static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_483, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::ValuesExpressions, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_483, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::SetAssignmentOrTimeZone, +static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_484, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::SetAssignmentOrTimeZone, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_484, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_485, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_485, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::ResetTarget, +static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_486, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::ResetTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_486, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::SettingScope, +static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_487, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::SettingScope, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_487, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::SetVariableOrSetting, +static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::SetVariableOrSetting, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::SetAssignment, +static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::SetAssignment, TransformChildKind::REQUIRED, 1, 1, @@ -6691,8 +6699,8 @@ static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::SetAssignmen false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_489, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::ZoneValue, +static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_490, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::ZoneValue, TransformChildKind::REQUIRED, 3, 1, @@ -6706,48 +6714,48 @@ static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::ZoneValue, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_490, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::Interval, +static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_491, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_491, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::VariableScope, +static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_492, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::VariableScope, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_492, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::ReadOrWrite, +static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::ReadOrWrite, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::ReadOnlyOrReadWrite, +static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::ReadOnlyOrReadWrite, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 6, 5, @@ -6789,8 +6797,8 @@ static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_496, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::UpdateAlias, +static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_497, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::UpdateAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -6804,16 +6812,16 @@ static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::UpdateAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_497, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::UpdateSetClause, +static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_498, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::UpdateSetClause, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_498, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_499, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6827,32 +6835,32 @@ static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_499, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_500, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_500, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::UseTarget, +static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_501, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::UseTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_502, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::AnalyzeTarget, +static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_503, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::AnalyzeTarget, TransformChildKind::OPTIONAL, 2, 1, @@ -6866,16 +6874,16 @@ static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::AnalyzeTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_503, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::VacuumOption, +static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_504, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::VacuumOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_504, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::OptAnalyze, +static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_505, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::OptAnalyze, TransformChildKind::OPTIONAL, 3, 3, @@ -6903,15 +6911,15 @@ static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::OptAnalyze, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_505, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::AnalyzeKeyword, +static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_506, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::AnalyzeKeyword, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_506, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_507, 1, 1, false, 0, {}}; static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, @@ -8102,52 +8110,48 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_259}, {"ColumnDefaultExpr", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_260}, - {"LambdaArrowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline, &FRAME_PLAN_261}, - {"SingleArrowPair", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowPairTrampoline, &FRAME_PLAN_262}, {"LogicalOrExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_263}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_261}, {"LogicalOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_264}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_262}, {"ColDefOrExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_265}, + &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_263}, {"ColDefOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_266}, + &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_264}, {"LogicalAndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_267}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_265}, {"LogicalAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_268}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_266}, {"ColDefAndExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_269}, + &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_267}, {"ColDefAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_270}, + &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_268}, {"LogicalNotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_271}, + &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_269}, {"NotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_272}, + &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_270}, {"NotKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_12}, {"IsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_273}, + &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_271}, {"IsExpressionContinuation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_274}, + &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_272}, {"IsExpressionTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsTestTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_275}, + &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_273}, {"IsDistinctTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_276}, + &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_274}, {"IsComparisonTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_277}, + &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_275}, {"IsOtherOperatorTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_278}, + &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_276}, {"IsCastTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_279}, + &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_277}, {"IsTest", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_280}, + &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_278}, {"IsLiteralValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UnknownLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8159,23 +8163,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsNull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullTrampoline, - &FRAME_PLAN_281}, + &FRAME_PLAN_279}, {"IsNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsDistinctFromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_282}, + &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_280}, {"IsDistinctFromTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_283}, + &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_281}, {"IsDistinctFromOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_12}, {"ComparisonExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_284}, + &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_282}, {"ComparisonExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_285}, + &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_283}, {"ComparisonOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NotComparisonOperand", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_286}, + &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_284}, {"ComparisonOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OperatorEqual", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8191,17 +8195,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OperatorGreaterThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_12}, {"BetweenInLikeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_287}, + &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_285}, {"InPredicate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_288}, + &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_286}, {"BetweenLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_289}, + &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_287}, {"BetweenLikeOpExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LikeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_290}, + &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_288}, {"EscapeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_291}, + &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_289}, {"LikeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, &FRAME_PLAN_19}, {"LikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8225,31 +8229,43 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotSimilarToOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_12}, {"InClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_290}, {"InExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InContainsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_291}, {"InExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_292}, {"InSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_293}, {"BetweenClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_294}, {"OtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_295}, {"InfixOtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_296}, {"OtherOperatorTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllSubqueryTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_299}, + &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_297}, {"OtherOperatorExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_300}, + &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_298}, + {"SingleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_299}, + {"SingleArrowBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"ArrowChainBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_300}, + {"ArrowChainTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"DoubleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_301}, + {"ArrowFullBody", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_259}, {"OtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllParsedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_301}, + &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_302}, {"NamedOtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, &FRAME_PLAN_54}, {"OperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8257,7 +8273,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AnyOperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_12}, {"AnyAllOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_302}, + &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_303}, {"AnyOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubqueryAny", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8265,49 +8281,49 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SubqueryAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_12}, {"QualifiedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_303}, + &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_304}, {"QualifiedOperatorContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_304}, + &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_305}, {"BitwiseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_305}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_306}, {"BitwiseExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_306}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_307}, {"BitOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_12}, {"TildeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_307}, + &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_308}, {"AdditiveExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_308}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_309}, {"AdditiveExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_309}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_310}, {"Term", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTermTrampoline, &FRAME_PLAN_12}, {"MultiplicativeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_310}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_311}, {"MultiplicativeExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_311}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_312}, {"Factor", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFactorTrampoline, &FRAME_PLAN_12}, {"ExponentiationExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_312}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_313}, {"ExponentiationExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_313}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_314}, {"ExponentOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_12}, {"CollateExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_314}, + &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_315}, {"CollateExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_315}, + &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_316}, {"AtTimeZoneExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_316}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_317}, {"AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_317}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_318}, {"UnaryExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_318}, + &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_319}, {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_19}, {"MinusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8317,9 +8333,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TildePrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_12}, {"BaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_319}, + &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_320}, {"IndirectionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_320}, + &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_321}, {"Indirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8327,27 +8343,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DotOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DotMethodOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_321}, + &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_322}, {"DotColumnOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_147}, {"MethodExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_322}, + &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_323}, {"MethodExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_323}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_324}, {"MethodExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_324}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_325}, {"MethodFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_211}, {"SliceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_325}, + &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_326}, {"SliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_326}, + &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_327}, {"SliceUpperBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MinusStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_327}, + &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_328}, {"EndStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_328}, + &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_329}, {"EndSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_66}, {"StepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8357,47 +8373,47 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SpecialFunctionExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CoalesceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_329}, + &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_330}, {"UnpackExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_134}, {"TryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_134}, {"ColumnsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_330}, + &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_331}, {"ExtractExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_331}, + &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_332}, {"ExtractArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_332}, + &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_333}, {"LambdaExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_333}, + &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_334}, {"NullIfExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_334}, + &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_335}, {"NullIfArguments", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_254}, {"PositionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_335}, + &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_336}, {"PositionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_336}, + &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_337}, {"RowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_337}, + &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_338}, {"SubstringExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_338}, + &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_339}, {"SubstringArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_340}, {"SubstringParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_341}, {"SubstringFromFor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringFromOptionalFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_341}, + &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_342}, {"SubstringFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_342}, + &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_343}, {"TrimExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_344}, {"TrimArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_345}, {"TrimDirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, &FRAME_PLAN_19}, {"TrimBoth", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8407,23 +8423,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TrimTrailing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_12}, {"TrimSource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_346}, {"OverlayExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_346}, + &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_347}, {"OverlayArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OverlayParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_347}, + &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_348}, {"FromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_21}, {"ForExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_21}, {"OverlayExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_340}, {"ExtractArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExtractDatePartArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_348}, + &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_349}, {"ExtractIdentifierArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_12}, {"ExtractStringArgument", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8433,25 +8449,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ExternalResourceStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_349}, + &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_350}, {"RegisterExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_350}, + &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_351}, {"DestroyExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_351}, + &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_352}, {"ExternalResourceCreationOptions", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_33}, {"AttachToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_352}, + &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_353}, {"ConnectToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_353}, + &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_354}, {"ExternalResourceSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExternalResourceCreateClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_354}, + &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_355}, {"ExternalResourceReferenceClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_32}, {"InsertStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_355}, + &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_356}, {"OrAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertOrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8461,15 +8477,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ByNameOrPosition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertByNameOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_356}, - {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_357}, + {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_358}, {"InsertByName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_12}, {"InsertByPosition", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_12}, {"InsertTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_358}, + &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_359}, {"InsertAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_12}, {"ColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8483,27 +8499,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_12}, {"OnConflictClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_359}, + &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_360}, {"OnConflictTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictExpressionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_360}, + &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_361}, {"OnConflictIndexTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_361}, + &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_362}, {"OnConflictAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_362}, + &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_363}, {"OnConflictNothing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_12}, {"ReturningClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_363}, + &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_364}, {"LoadStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_364}, + &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_365}, {"ExtensionAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_12}, {"InstallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_365}, + &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_366}, {"InstallAndLoad", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_12}, {"UpdateExtensionsStatement", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8515,45 +8531,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FromSourceString", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_12}, {"VersionNumber", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_366}, + &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_367}, {"ExtensionRepositoryStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_367}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_368}, {"RepositoryPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_12}, {"RepositoryPublicKey", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_12}, {"DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_368}, + &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_369}, {"TableMatchRecognizeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_369}, + &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_370}, {"MatchRecognizeBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_370}, + &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_371}, {"MatchRecognizeClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MRPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_371}, + &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_372}, {"MROrderBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_372}, + &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_373}, {"MRMeasures", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_373}, + &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_374}, {"MRRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRRowsTrampoline, - &FRAME_PLAN_374}, - {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, &FRAME_PLAN_375}, + {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, + &FRAME_PLAN_376}, {"MRPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_376}, + &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_377}, {"MRSubset", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_377}, + &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_378}, {"MRDefineAuto", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_12}, {"MRDefine", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_378}, + &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_379}, {"MeasuresClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_379}, + &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_380}, {"MeasuresElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_380}, + &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_381}, {"MeasureSemantics", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RunningSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8565,7 +8581,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OneRowPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_12}, {"AllRowsPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_381}, + &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_382}, {"AllRowsEmptyMatches", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ShowEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8575,7 +8591,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WithUnmatchedRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_12}, {"AfterMatchSkip", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_382}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_383}, {"AfterMatchSkipTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SkipToNextRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8583,25 +8599,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SkipPastLastRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_12}, {"SkipToFirstVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_383}, + &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_384}, {"SkipToLastVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_383}, + &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_384}, {"SkipToVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_384}, + &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_385}, {"PatternClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_385}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_386}, {"RowPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_386}, + &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_387}, {"RowPatternAlternative", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_387}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_388}, {"RowPatternTerm", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_388}, + &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_389}, {"RowPatternFactor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_389}, + &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_390}, {"RowPatternPrimary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RowPatternPermute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_390}, + &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_391}, {"RowPatternAnchor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PatternStart", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8609,15 +8625,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PatternEnd", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_12}, {"RowPatternGroup", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_391}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_392}, {"RowPatternEmpty", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_12}, {"RowPatternExclusion", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_392}, + &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_393}, {"RowPatternLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_393}, + &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_394}, {"RowPatternQuantifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_394}, + &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_395}, {"RowPatternQuantifierKind", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierReluctant", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8629,7 +8645,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierOptional", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_12}, {"QuantifierRange", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_395}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_396}, {"QuantifierBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8641,55 +8657,55 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierExact", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_12}, {"SubsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_396}, + &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_397}, {"SubsetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_397}, + &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_398}, {"DefineClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_398}, + &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_399}, {"DefineElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_399}, + &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_400}, {"MergeIntoStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_400}, + &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_401}, {"MergeIntoUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_401}, + &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_402}, {"MergeMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_402}, + &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_403}, {"MatchedClauseAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_403}, + &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_404}, {"UpdateMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchSetAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_404}, + &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_405}, {"UpdateByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_405}, + &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_406}, {"DeleteMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_12}, {"InsertMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_406}, + &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_407}, {"InsertMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertDefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_12}, {"InsertByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_407}, + &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_408}, {"InsertValuesList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_408}, + &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_409}, {"DoNothingMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_12}, {"ErrorMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_66}, {"UpdateMatchSetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_409}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_410}, {"UpdateMatchSetInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_80}, {"AndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_21}, {"NotMatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_410}, + &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_411}, {"BySourceOrTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BySource", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8699,27 +8715,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PivotStatement", &PEGTransformerFactory::InitializePivotStatementTrampoline, &PEGTransformerFactory::FinalizePivotStatementTrampoline, nullptr}, {"PivotOn", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotOnTrampoline, - &FRAME_PLAN_411}, + &FRAME_PLAN_412}, {"PivotUsing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_363}, + &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_364}, {"PivotColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_412}, + &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_413}, {"PivotColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotColumnExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_31}, {"PivotColumnSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_413}, + &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_414}, {"UnpivotStatement", &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline, nullptr}, {"IntoNameValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_414}, + &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_415}, {"OptionalParensNameList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ParenthesizedNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_416}, {"BareNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_417}, {"IncludeOrExcludeNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IncludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8731,41 +8747,41 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"UnpivotHeaderSingle", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_38}, {"UnpivotHeaderList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_416}, {"PragmaStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_417}, + &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_418}, {"PragmaAssignOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PragmaAssign", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_418}, + &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_419}, {"PragmaFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_419}, + &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_420}, {"PragmaParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_292}, {"PrepareStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_420}, + &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_421}, {"TypeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_421}, + &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_422}, {"SelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_202}, {"SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline, nullptr}, {"SelectSetOpChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_422}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_423}, {"SelectSetOpChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_424}, {"IntersectChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_425}, {"IntersectChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_426}, {"SetIntersectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_426}, + &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_427}, {"SelectAtom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_293}, {"SetopClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_427}, + &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_428}, {"SetopType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetopUnion", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8775,103 +8791,103 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SelectStatementType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResultModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_428}, + &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_429}, {"LimitOffset", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LimitOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_429}, + &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_430}, {"OffsetLimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_430}, + &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_431}, {"OffsetFetchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_431}, + &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_432}, {"FetchOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_432}, + &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_433}, {"FetchOnlyClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_433}, + &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_434}, {"TableStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_434}, + &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_435}, {"OptionalParensSimpleSelect", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleSelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_435}, + &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_436}, {"SimpleSelect", &PEGTransformerFactory::InitializeSimpleSelectTrampoline, &PEGTransformerFactory::FinalizeSimpleSelectTrampoline, nullptr}, {"SelectFrom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectFromClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_436}, + &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_437}, {"FromSelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_437}, + &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_438}, {"WithStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_438}, + &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_439}, {"CTEBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CTESelectBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_293}, {"CTEDMLBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_439}, + &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_440}, {"UsingKey", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_440}, + &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_441}, {"Materialized", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_12}, {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, &PEGTransformerFactory::FinalizeWithClauseTrampoline, nullptr}, {"SelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_441}, + &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_442}, {"TargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_442}, + &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_443}, {"ColumnAliases", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_416}, {"DistinctClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DistinctAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_12}, {"DistinctOn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_443}, + &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_444}, {"DistinctOnTargets", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_329}, + &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_330}, {"InnerTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, &PEGTransformerFactory::FinalizeTableRefTrampoline, nullptr}, {"TableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_444}, + &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_445}, {"BaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_445}, + &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_446}, {"TableAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_38}, {"ValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_446}, + &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_447}, {"ParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_447}, + &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_448}, {"JoinOrPivot", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TablePivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_448}, + &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_449}, {"TablePivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_449}, + &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_450}, {"PivotGroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_450}, + &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_451}, {"TableUnpivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_451}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_452}, {"TableUnpivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_452}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_453}, {"PivotHeader", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_453}, + &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_454}, {"PivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_454}, + &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_455}, {"PivotValueTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotEnumTarget", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_12}, {"PivotListTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_455}, + &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_456}, {"UnpivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_456}, + &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_457}, {"PivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_457}, + &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_458}, {"UnpivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_457}, + &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_458}, {"Lateral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeLateralTrampoline, &FRAME_PLAN_12}, {"BaseTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8887,33 +8903,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableFunctionLateralOpt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_458}, + &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_459}, {"TableFunctionAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_459}, + &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_460}, {"WithOrdinality", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_12}, - {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline, &FRAME_PLAN_460}, + {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + {"CatalogReservedSchemaTableFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_461}, + {"TableFunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"TableFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_461}, + &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_462}, {"FunctionArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NamedFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_462}, + &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_463}, {"PositionalFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_31}, {"NamedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_463}, + &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_464}, {"TableAlias", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableAliasAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_464}, + &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_465}, {"TableAliasWithoutAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_465}, + &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_466}, {"AtClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_466}, + &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_467}, {"AtSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_467}, + &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_468}, {"AtUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_19}, {"VersionAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8925,21 +8945,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestJoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestJoinAliased", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_468}, + &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_469}, {"NearestJoinBare", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_469}, + &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_470}, {"NearestBareTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_470}, + &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_471}, {"NearestTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_471}, + &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_472}, {"NearestTableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_472}, + &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_473}, {"NearestBaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_473}, + &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_474}, {"NearestParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_474}, + &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_475}, {"ApproxOrExact", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestApprox", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8953,19 +8973,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestSimilarity", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_12}, {"RegularJoinClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_475}, + &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_476}, {"JoinByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_476}, + &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_477}, {"Asof", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAsofTrampoline, &FRAME_PLAN_12}, {"JoinWithoutOnClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_477}, + &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_478}, {"JoinQualifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_21}, {"UsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_478}, + &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_479}, {"UsingColumnName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, &FRAME_PLAN_149}, {"JoinType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8975,7 +8995,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CrossJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_12}, {"NaturalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_479}, + &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_480}, {"PositionalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_12}, {"FullJoin", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8995,35 +9015,35 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WhereClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_21}, {"GroupByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_480}, + &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_481}, {"HavingClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_21}, {"QualifyClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_21}, {"SampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_481}, + &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_482}, {"SelectSampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_481}, + &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_482}, {"WindowClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_482}, + &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_483}, {"WindowDefinition", &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline, nullptr}, {"SampleEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleEntryCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_483}, + &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_484}, {"SampleEntryFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_484}, + &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_485}, {"SampleFunction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_83}, {"SampleProperties", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_485}, + &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_486}, {"RepeatableSample", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_486}, + &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_487}, {"SampleSeed", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_12}, {"SampleCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_487}, + &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_488}, {"SampleValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9037,7 +9057,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GroupByAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_12}, {"GroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_488}, + &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_489}, {"GroupByExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupByBaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9045,7 +9065,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"EmptyGroupingItem", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_12}, {"CubeOrRollupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_489}, + &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_490}, {"CubeOrRollup", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, &FRAME_PLAN_19}, {"CubeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9053,9 +9073,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"RollupKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_12}, {"GroupingSetsClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_490}, + &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_491}, {"SubqueryReference", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_293}, {"OrderByExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_98}, {"DescOrAsc", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9071,17 +9091,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NullsLast", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_12}, {"OrderByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_491}, + &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_492}, {"OrderByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OrderByExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_492}, + &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_493}, {"OrderByAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_493}, + &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_494}, {"LimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_494}, + &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_495}, {"OffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_495}, + &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_496}, {"OffsetValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_31}, {"LimitValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9097,45 +9117,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FetchClauseWithoutValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_12}, {"FetchClauseWithValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_496}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_497}, {"FetchValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_31}, {"AliasedExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ColIdExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_497}, + &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_498}, {"ExpressionAsCollabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_380}, + &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_381}, {"ExpressionOptIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_31}, {"ValuesClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_498}, + &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_499}, {"ValuesExpressions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_292}, {"SetStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetKeywordStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_499}, + &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_500}, {"VariableAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_500}, + &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_501}, {"SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_501}, + &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_502}, {"ResetTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_503}, {"ResetVariableOrSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_504}, {"SetSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_503}, {"StandardAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_504}, + &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_505}, {"SetVariableOrSetting", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_505}, + &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_506}, {"ZoneValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ZoneLocal", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9147,13 +9167,13 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ZoneIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_12}, {"ZoneIntervalWithInterval", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_506}, + &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_507}, {"ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_12}, {"SetSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_503}, {"SetVariable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_507}, + &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_508}, {"VariableScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_12}, {"SettingScope", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9165,19 +9185,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GlobalScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_12}, {"SetAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_508}, + &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_509}, {"VariableList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_340}, {"TransactionStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BeginTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_509}, + &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_510}, {"RollbackTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_12}, {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_12}, {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_510}, + &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_511}, {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReadOnly", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9185,27 +9205,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ReadWrite", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_12}, {"UpdateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_512}, {"UpdateTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BaseTableSet", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_182}, {"BaseTableAliasSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_513}, {"UpdateAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_32}, {"UpdateSetClauseList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_514}, {"UpdateSetClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateSetTuple", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_17}, {"UpdateSetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_514}, + &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_515}, {"UpdateSetColumnTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_515}, + &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_516}, {"UseStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_516}, + &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_517}, {"UseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SchemaNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9213,21 +9233,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CatalogNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, &FRAME_PLAN_54}, {"UseTargetCatalogSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_517}, + &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_518}, {"DotIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_12}, {"VacuumStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_518}, + &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_519}, {"VacuumOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"VacuumParensOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_519}, + &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_520}, {"VacuumLegacyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_520}, + &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_521}, {"VacuumOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, &FRAME_PLAN_19}, {"OptAnalyze", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_521}, + &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_522}, {"OptFull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptFullTrampoline, &FRAME_PLAN_12}, {"OptFreeze", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9235,7 +9255,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OptVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_12}, {"NameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_416}, }; static case_insensitive_map_t BuildGeneratedTransformFrameOps() { @@ -14518,40 +14538,6 @@ PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -arena_ptr -PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline(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(); - } - auto logical_or_expression = process.TakeResult>(0); - optional>> single_arrow_pair {}; - if (dynamic_child_count > 0) { - vector> single_arrow_pair_value; - single_arrow_pair_value.reserve(dynamic_child_count); - for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { - single_arrow_pair_value.push_back(process.TakeResult>(i)); - } - single_arrow_pair = std::move(single_arrow_pair_value); - } - auto result = - TransformLambdaArrowExpression(transformer, std::move(logical_or_expression), std::move(single_arrow_pair)); - return transformer.MakeResult>(std::move(result)); -} - -arena_ptr -PEGTransformerFactory::FinalizeSingleArrowPairTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto logical_or_expression = process.TakeResult>(0); - auto result = TransformSingleArrowPair(transformer, std::move(logical_or_expression)); - return transformer.MakeResult>(std::move(result)); -} - arena_ptr PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -15249,6 +15235,47 @@ PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline(PEGTransfor return transformer.MakeResult(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeSingleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto single_arrow_body = process.TakeResult(0); + auto result = TransformSingleArrowTail(transformer, std::move(single_arrow_body)); + return transformer.MakeResult(std::move(result)); +} + +arena_ptr +PEGTransformerFactory::FinalizeArrowChainBodyTrampoline(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 bitwise_expression = process.TakeResult>(0); + vector arrow_chain_tail; + arrow_chain_tail.reserve(dynamic_child_count); + for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { + arrow_chain_tail.push_back(process.TakeResult(i)); + } + auto result = TransformArrowChainBody(transformer, std::move(bitwise_expression), std::move(arrow_chain_tail)); + return transformer.MakeResult(std::move(result)); +} + +arena_ptr +PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto bitwise_expression = process.TakeResult>(0); + auto result = TransformDoubleArrowTail(transformer, std::move(bitwise_expression)); + return transformer.MakeResult(std::move(result)); +} + +arena_ptr +PEGTransformerFactory::FinalizeArrowFullBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto logical_or_expression = process.TakeResult>(0); + auto result = TransformArrowFullBody(transformer, std::move(logical_or_expression)); + return transformer.MakeResult(std::move(result)); +} + arena_ptr PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -18131,8 +18158,8 @@ PEGTransformerFactory::FinalizeWithOrdinalityTrampoline(PEGTransformer &transfor } arena_ptr -PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline(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(); @@ -18141,10 +18168,7 @@ PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline(PEGTransformer & 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); - } + auto catalog_qualification = process.TakeResult(0); optional> schema_qualification {}; if (dynamic_child_count > 0) { vector schema_qualification_value; @@ -18154,9 +18178,18 @@ PEGTransformerFactory::FinalizeQualifiedTableFunctionTrampoline(PEGTransformer & } schema_qualification = std::move(schema_qualification_value); } - auto table_function_name = list_pr.GetChild(2).Cast().identifier; - auto result = - TransformQualifiedTableFunction(transformer, catalog_qualification, schema_qualification, table_function_name); + auto reserved_table_function_name = list_pr.GetChild(2).Cast().identifier; + auto result = TransformCatalogReservedSchemaTableFunctionName(transformer, catalog_qualification, + schema_qualification, reserved_table_function_name); + return transformer.MakeResult(result); +} + +arena_ptr +PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + auto table_function_name = list_pr.GetChild(0).Cast().identifier; + auto result = TransformTableFunctionNameAsQualifiedName(transformer, table_function_name); return transformer.MakeResult(result); } diff --git a/src/duckdb/src/parser/peg/transformer/transform_select.cpp b/src/duckdb/src/parser/peg/transformer/transform_select.cpp index 0fba4e745..2148d0865 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_select.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_select.cpp @@ -1546,19 +1546,22 @@ unique_ptr PEGTransformerFactory::TransformCatalogReservedSchemaTa return make_uniq(description); } -QualifiedName PEGTransformerFactory::TransformQualifiedTableFunction( - PEGTransformer &transformer, const optional &catalog_qualification, - const optional> &schema_qualification, const Identifier &table_function_name) { +QualifiedName PEGTransformerFactory::TransformCatalogReservedSchemaTableFunctionName( + PEGTransformer &transformer, const Identifier &catalog_qualification, + const optional> &schema_qualification, const Identifier &reserved_table_function_name) { vector qualification; - if (catalog_qualification) { - qualification.push_back(*catalog_qualification); - } + qualification.push_back(catalog_qualification); if (schema_qualification) { for (auto &schema : *schema_qualification) { qualification.push_back(schema); } } - return QualifiedName(std::move(qualification), table_function_name); + return QualifiedName(std::move(qualification), reserved_table_function_name); +} + +QualifiedName PEGTransformerFactory::TransformTableFunctionNameAsQualifiedName(PEGTransformer &transformer, + const Identifier &table_function_name) { + return QualifiedName(table_function_name); } vector 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 d9da51866..7cbade868 100644 --- a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp @@ -263,7 +263,7 @@ BindResult ExpressionBinder::TryBindLambdaOrJson(FunctionExpression &function, i CatalogEntry &ExpressionBinder::BindFunction(FunctionExpression &function) { QueryErrorContext error_context(function.GetQueryLocation()); - ColumnQualifier qualifier(binder); + ColumnQualifier qualifier(binder, lambda_bindings); auto func = qualifier.QualifyFunction(function); if (!func) { // function was not found - check if we this is a table function (to throw a more helpful error message) diff --git a/src/duckdb/src/planner/binder/expression/bind_lambda.cpp b/src/duckdb/src/planner/binder/expression/bind_lambda.cpp index dad684ef1..8d1f991c4 100644 --- a/src/duckdb/src/planner/binder/expression/bind_lambda.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_lambda.cpp @@ -62,27 +62,6 @@ static void ExtractParameters(LambdaExpression &expr, vector &column D_ASSERT(!column_names.empty()); } -static bool IsDoubleArrowRHS(const ParsedExpression &expr) { - if (expr.GetExpressionClass() != ExpressionClass::FUNCTION) { - return false; - } - auto &func = expr.Cast(); - return func.IsOperator() && func.FunctionName() == "->>" && func.GetArguments().size() == 2; -} - -static unique_ptr RestructureArrowChain(LambdaExpression &expr) { - auto &rhs_func = expr.RightMutable()->Cast(); - auto inner_lambda = make_uniq( - std::move(expr.LeftMutable()), std::move(rhs_func.GetArgumentsMutable()[0].GetExpressionMutable())); - inner_lambda->GetLambdaSyntaxTypeMutable() = expr.GetLambdaSyntaxType(); - vector> children; - children.push_back(std::move(inner_lambda)); - children.push_back(std::move(rhs_func.GetArgumentsMutable()[1].GetExpressionMutable())); - auto restructured = make_uniq("->>", std::move(children)); - restructured->IsOperatorMutable() = true; - return std::move(restructured); -} - BindResult ExpressionBinder::BindExpression(LambdaExpression &expr, idx_t depth, const vector &function_child_types, optional_ptr bind_lambda_function, @@ -92,13 +71,6 @@ BindResult ExpressionBinder::BindExpression(LambdaExpression &expr, idx_t depth, } if (!bind_lambda_function) { - // The PEG parser produces A -> (B ->> C) where the standard parser left-associates to (A -> B) ->> C. - // Restructure to match standard behavior before binding. - if (IsDoubleArrowRHS(expr.Right())) { - unique_ptr restructured = RestructureArrowChain(expr); - return BindExpression(restructured, depth); - } - // This is not a lambda expression, but the JSON arrow operator. // Remember the original expression in case of a binding error. if (!expr.CopiedExprMutable()) { 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 c940c010a..6e5748885 100644 --- a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp @@ -241,7 +241,7 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (i_exp.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { auto &const_exp = i_exp.Cast(); if (!const_exp.GetValue().IsNull() && const_exp.GetReturnType().IsIntegral()) { - const_exp.SetValue(const_exp.GetValue().DefaultCastAs(LogicalType::UINTEGER, true)); + const_exp.SetValue(const_exp.GetValue().CastAs(context, LogicalType::UINTEGER, true)); const_exp.SetReturnType(LogicalType::UINTEGER); } } diff --git a/src/duckdb/src/planner/binder/expression/bind_try_subquery.cpp b/src/duckdb/src/planner/binder/expression/bind_try_subquery.cpp index d59d914c1..a5e18c1b0 100644 --- a/src/duckdb/src/planner/binder/expression/bind_try_subquery.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_try_subquery.cpp @@ -195,7 +195,6 @@ optional ExpressionBinder::LowerTrySubquery(const ParsedExpression switch (current_op.type) { case LogicalOperatorType::LOGICAL_ORDER_BY: case LogicalOperatorType::LOGICAL_TOP_N: - case LogicalOperatorType::LOGICAL_DISTINCT: if (expose_error_flag) { // these modifiers reference or deduplicate the select list column; a struct transport // would leave their references scalar or change DISTINCT semantics (an error-masked @@ -235,6 +234,31 @@ optional ExpressionBinder::LowerTrySubquery(const ParsedExpression current = *projection.children[0]; continue; } + if (indexes.distinct_index.IsValid() && projection.table_index == indexes.distinct_index) { + // DISTINCT: a projection over the aggregate that deduplicates the select list + if (expose_error_flag) { + // a struct transport would change DISTINCT semantics (an error-masked NULL must not be + // distinguishable from a plain NULL) + if (strict) { + throw BinderException(location, "TRY over a subquery with result modifiers is only supported " + "when the subquery is the direct argument of TRY"); + } + return optional(); + } + // look through the DISTINCT to the select list column it forwards + auto &distinct_aggregate = projection.children[0]->Cast(); + auto distinct_binding = + projection.expressions[binding.column_index]->Cast().Binding(); + reference source(distinct_binding.table_index == distinct_aggregate.group_index + ? *distinct_aggregate.groups[distinct_binding.column_index] + : *distinct_aggregate.expressions[distinct_binding.column_index]); + if (source.get().GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { + source = *source.get().Cast().GetChildren()[0]; + } + binding = source.get().Cast().Binding(); + current = *distinct_aggregate.children[0]; + continue; + } if (projection.table_index != indexes.projection_index) { throw InternalException("TRY subquery: unexpected projection above the select list"); } diff --git a/src/duckdb/src/planner/binder/query_node/plan_query_node.cpp b/src/duckdb/src/planner/binder/query_node/plan_query_node.cpp index c448f2f11..e58129606 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_query_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_query_node.cpp @@ -1,38 +1,180 @@ #include "duckdb/parser/query_node.hpp" #include "duckdb/planner/binder.hpp" -#include "duckdb/planner/operator/logical_distinct.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_limit.hpp" #include "duckdb/planner/operator/logical_order.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/bound_result_modifier.hpp" +#include "duckdb/function/aggregate/distributive_functions.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" +#include "duckdb/function/function_binder.hpp" namespace duckdb { +//! Gives the plan that produces the result of a query node a new table index, returns the old table index +static TableIndex RenameResultIndex(LogicalOperator &root, TableIndex new_index) { + reference current(root); + while (true) { + auto &op = current.get(); + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + auto old_index = projection.table_index; + projection.table_index = new_index; + return old_index; + } + case LogicalOperatorType::LOGICAL_UNION: + case LogicalOperatorType::LOGICAL_EXCEPT: + case LogicalOperatorType::LOGICAL_INTERSECT: { + auto &setop = op.Cast(); + auto old_index = setop.table_index; + setop.table_index = new_index; + return old_index; + } + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_LIMIT: + current = *op.children[0]; + break; + default: + throw InternalException("DISTINCT is applied to an unexpected operator"); + } + } +} + +static void ReplaceTableIndex(unique_ptr &expr, TableIndex old_index, TableIndex new_index) { + ExpressionIterator::VisitExpressionMutable( + expr, [&](BoundColumnRefExpression &colref, unique_ptr &ref) { + auto &binding = colref.Binding(); + if (binding.table_index != old_index) { + return; + } + ref = make_uniq(colref.GetAlias(), colref.GetReturnType(), + ColumnBinding(new_index, binding.column_index), colref.Depth()); + }); +} + +static void ReplaceTableIndex(BoundOrderModifier &modifier, TableIndex old_index, TableIndex new_index) { + for (auto &order : modifier.orders) { + ReplaceTableIndex(order.expression, old_index, new_index); + } +} + +unique_ptr Binder::PlanDistinct(BoundDistinctModifier &distinct, + optional_ptr order, + unique_ptr root) { + // the result of the DISTINCT has the table index of the input so that the remainder of the plan remains valid + auto child_index = GenerateTableIndex(); + auto result_index = RenameResultIndex(*root, child_index); + // sorts and limits between the DISTINCT and the renamed operator reference the old index + for (reference current(*root); current.get().type == LogicalOperatorType::LOGICAL_ORDER_BY || + current.get().type == LogicalOperatorType::LOGICAL_LIMIT; + current = *current.get().children[0]) { + LogicalOperatorVisitor::EnumerateExpressions( + current.get(), [&](unique_ptr *expr) { ReplaceTableIndex(*expr, result_index, child_index); }); + } + if (IsBindingTrySubquery()) { + auto &try_indexes = GetTrySubqueryPlanIndexesMutable(); + if (try_indexes.recorded && try_indexes.projection_index == result_index) { + try_indexes.distinct_index = result_index; + try_indexes.projection_index = child_index; + } + } + root->ResolveOperatorTypes(); + auto child_bindings = root->GetColumnBindings(); + auto child_types = root->types; + D_ASSERT(child_bindings.size() == child_types.size()); + + // every distinct target becomes a group + auto group_index = GenerateTableIndex(); + auto aggregate_index = GenerateTableIndex(); + vector> groups; + unordered_map group_references; + for (auto &target : distinct.target_distincts) { + ReplaceTableIndex(target, result_index, child_index); + if (target->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { + auto &colref = target->Cast(); + group_references[colref.Binding().column_index.GetIndexUnsafe()] = groups.size(); + } + groups.push_back(std::move(target)); + } + distinct.target_distincts.clear(); + + unique_ptr first_order; + if (distinct.distinct_type == DistinctType::DISTINCT_ON && order) { + first_order = make_uniq(); + for (auto &order_node : order->orders) { + first_order->orders.push_back(order_node.Copy()); + } + ReplaceTableIndex(*first_order, result_index, child_index); + } + + // all other columns are the first value of the group + vector> aggregates; + vector> projections; + FunctionBinder function_binder(context); + for (idx_t i = 0; i < child_types.size(); i++) { + auto &type = child_types[i]; + auto entry = group_references.find(child_bindings[i].column_index.GetIndexUnsafe()); + if (entry != group_references.end()) { + projections.push_back( + make_uniq(type, ColumnBinding(group_index, ProjectionIndex(entry->second)))); + continue; + } + vector> first_children; + first_children.push_back(make_uniq(type, child_bindings[i])); + auto first_aggregate = + function_binder.BindAggregateFunction(GetBuiltinAggregateFunction(context, FirstFun::Name, {type}), + std::move(first_children), nullptr, AggregateType::NON_DISTINCT); + first_aggregate->GetOrderBysMutable() = first_order ? first_order->Copy() : nullptr; + projections.push_back(make_uniq( + type, ColumnBinding(aggregate_index, ProjectionIndex(aggregates.size())))); + aggregates.push_back(std::move(first_aggregate)); + } + + auto aggregate = make_uniq(group_index, aggregate_index, std::move(aggregates)); + // a single grouping set over all groups, as for GROUP BY, so statistics use the distinct counts of the groups + GroupingSet all_groups; + for (idx_t i = 0; i < groups.size(); i++) { + all_groups.insert(ProjectionIndex(i)); + } + aggregate->grouping_sets.push_back(std::move(all_groups)); + aggregate->groups = std::move(groups); + // without an ORDER BY, DISTINCT ON takes the first row of every group in input order + aggregate->preserve_input_order = + distinct.distinct_type == DistinctType::DISTINCT_ON && !first_order && !aggregate->expressions.empty(); + aggregate->AddChild(std::move(root)); + + auto projection = make_uniq(result_index, std::move(projections)); + projection->AddChild(std::move(aggregate)); + return std::move(projection); +} + unique_ptr Binder::VisitQueryNode(BoundQueryNode &node, unique_ptr root) { D_ASSERT(root); - for (auto &mod : node.modifiers) { + for (idx_t mod_idx = 0; mod_idx < node.modifiers.size(); mod_idx++) { + auto &mod = node.modifiers[mod_idx]; switch (mod->type) { case ResultModifierType::DISTINCT_MODIFIER: { auto &bound = mod->Cast(); if (bound.target_distincts.empty()) { break; } - auto distinct = make_uniq(std::move(bound.target_distincts), bound.distinct_type); - distinct->AddChild(std::move(root)); - root = std::move(distinct); + // DISTINCT ON takes the first row according to an ORDER BY that directly follows it + optional_ptr order; + if (mod_idx + 1 < node.modifiers.size() && + node.modifiers[mod_idx + 1]->type == ResultModifierType::ORDER_MODIFIER) { + order = node.modifiers[mod_idx + 1]->Cast(); + } + root = PlanDistinct(bound, order, std::move(root)); break; } case ResultModifierType::ORDER_MODIFIER: { auto &bound = mod->Cast(); - if (root->type == LogicalOperatorType::LOGICAL_DISTINCT) { - auto &distinct = root->Cast(); - if (distinct.distinct_type == DistinctType::DISTINCT_ON) { - auto order_by = make_uniq(); - for (auto &order_node : bound.orders) { - order_by->orders.push_back(order_node.Copy()); - } - distinct.order_by = std::move(order_by); - } - } auto order = make_uniq(std::move(bound.orders)); order->AddChild(std::move(root)); root = std::move(order); diff --git a/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp b/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp index adc1ec9d4..417afb060 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp @@ -706,6 +706,102 @@ void RecursiveDependentJoinPlanner::PlanJoinExpressions(LogicalOperator &op) { } } +static bool OperandIsCorrelated(const Expression &expr) { + bool correlated = false; + ExpressionIterator::VisitExpression( + expr, [&](const BoundColumnRefExpression &colref) { correlated |= colref.Depth() > 0; }); + return correlated; +} + +static bool JoinSideContributesOutput(JoinType join_type, idx_t side) { + if (side == 0) { + return join_type != JoinType::RIGHT_SEMI && join_type != JoinType::RIGHT_ANTI; + } + return join_type != JoinType::SEMI && join_type != JoinType::ANTI && join_type != JoinType::MARK; +} + +BindingReplacementGraph RecursiveDependentJoinPlanner::NormalizeJoinConditionOperands(unique_ptr &op) { + BindingReplacementGraph result; + if (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op->type != LogicalOperatorType::LOGICAL_ASOF_JOIN) { + return result; + } + auto &join = op->Cast(); + for (idx_t side = 0; side < 2; side++) { + // a comparison condition operand evaluates in its owning child's scope, but ownership + // does not imply permission to evaluate eagerly: joins may skip either operand entirely + // (an empty build short-circuits the probe, input swapping exchanges the roles, and the + // blockwise join evaluates nothing without candidate pairs), so operands always keep + // their computation at the join and only their outer references move into the child, + // where decorrelation rewrites them in the owning child's domain + vector>> operands; + for (auto &cond : join.conditions) { + if (!cond.IsComparison()) { + continue; + } + auto &operand = side == 0 ? cond.LeftReference() : cond.RightReference(); + if (OperandIsCorrelated(*operand)) { + operands.push_back(&operand); + } + } + if (operands.empty()) { + continue; + } + auto &child = op->children[side]; + child->ResolveOperatorTypes(); + auto child_bindings = child->GetColumnBindings(); + auto child_types = child->types; + auto projection_index = binder.GenerateTableIndex(); + vector> expressions; + expressions.reserve(child_bindings.size() + operands.size()); + for (idx_t i = 0; i < child_bindings.size(); i++) { + expressions.push_back(make_uniq(child_types[i], child_bindings[i])); + } + for (auto &operand_ptr : operands) { + // hoist each outer reference into the projection and keep the operand in place + std::function &)> hoist = [&](unique_ptr &expr) { + if (expr->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &colref = expr->Cast(); + if (colref.Depth() > 0) { + auto hoisted_binding = ColumnBinding(projection_index, ProjectionIndex(expressions.size())); + auto local = make_uniq(colref.GetReturnType(), hoisted_binding); + expressions.push_back(std::move(expr)); + expr = std::move(local); + } + return; + } + ExpressionIterator::EnumerateChildren(*expr, hoist); + }; + hoist(*operand_ptr); + } + auto projection = make_uniq(projection_index, std::move(expressions)); + projection->children.push_back(std::move(child)); + child = std::move(projection); + + // rewrite the join's remaining references to the child's columns + CorrelatedColumnBindingReplacer replacer; + for (idx_t i = 0; i < child_bindings.size(); i++) { + auto new_binding = ColumnBinding(projection_index, ProjectionIndex(i)); + replacer.replacement_bindings.emplace_back(child_bindings[i], new_binding); + result.Add(child_bindings[i], new_binding); + } + replacer.BuildIndex(); + replacer.VisitOperatorBindings(*op); + + // the hoisted columns are internal to the condition and must not join the output + if (JoinSideContributesOutput(join.join_type, side)) { + auto &projection_map = side == 0 ? join.left_projection_map : join.right_projection_map; + if (projection_map.empty()) { + projection_map.reserve(child_bindings.size()); + for (idx_t i = 0; i < child_bindings.size(); i++) { + projection_map.emplace_back(i); + } + } + } + } + return result; +} + void RecursiveDependentJoinPlanner::PlanJoinChildFilters(LogicalOperator &op) { if (!HasJoinConditionExpressions(op.type)) { return; @@ -758,6 +854,9 @@ BindingReplacementGraph RecursiveDependentJoinPlanner::PlanOperator(unique_ptrGetColumnBindings(), operator_replacements); return operator_replacements; diff --git a/src/duckdb/src/planner/binder/statement/bind_copy.cpp b/src/duckdb/src/planner/binder/statement/bind_copy.cpp index 3516d5925..43d413ba5 100644 --- a/src/duckdb/src/planner/binder/statement/bind_copy.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_copy.cpp @@ -463,7 +463,7 @@ BoundStatement Binder::BindCopyTo(CopyStatement &stmt, const CopyFunction &funct if (option_values.empty()) { throw BinderException("BATCH_SIZE_BYTES/ROW_GROUP_SIZE_BYTES cannot be empty"); } - parsed_options.batch_size_bytes = ParseBytesArg(option_name, option_values[0]); + parsed_options.batch_size_bytes = ParseBytesArg(context.GetContext(), option_name, option_values[0]); } else if (option_name == "file_size_bytes") { if (option_values.empty()) { throw BinderException("FILE_SIZE_BYTES cannot be empty"); @@ -471,7 +471,7 @@ BoundStatement Binder::BindCopyTo(CopyStatement &stmt, const CopyFunction &funct if (!function.file_size_bytes) { throw BinderException("FILE_SIZE_BYTES not implemented for %s", function.name); } - parsed_options.file_size_bytes = ParseBytesArg(option_name, option_values[0]); + parsed_options.file_size_bytes = ParseBytesArg(context.GetContext(), option_name, option_values[0]); } else if (option_name == "batches_per_file" || option_name == "row_groups_per_file") { if (option_values.empty()) { throw BinderException("BATCHES_PER_FILE/ROW_GROUPS_PER_FILE cannot be empty"); diff --git a/src/duckdb/src/planner/binder/statement/bind_create.cpp b/src/duckdb/src/planner/binder/statement/bind_create.cpp index 718f74709..52a6d163d 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create.cpp @@ -1116,7 +1116,7 @@ BoundStatement Binder::Bind(CreateStatement &stmt) { info.on_conflict, info.persist_type}; - result = SecretManager::Get(context).BindCreateSecret(transaction, create_secret_input); + result = SecretManager::Get(context).BindCreateSecret(context.GetContext(), transaction, create_secret_input); break; } case CatalogType::TRIGGER_ENTRY: { diff --git a/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp b/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp index a7a0ece96..5557f2b48 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp @@ -4,6 +4,7 @@ #include "duckdb/function/window/match_recognize_functions.hpp" #include "duckdb/function/window/window_match_recognize.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/main/config.hpp" #include "duckdb/parser/expression/case_expression.hpp" @@ -203,7 +204,8 @@ static bool HasExclusion(const ParsedExpression &expr) { //! PREV and NEXT walk the ordered partition rather than the match, so a measure's are computed per //! input row below the pattern window and read back from above it -static void HoistMeasureNavigation(unique_ptr &expr, const WindowExpression &pattern_window, +static void HoistMeasureNavigation(Context &context, unique_ptr &expr, + const WindowExpression &pattern_window, const case_insensitive_map_t> &symbols, const case_insensitive_map_t &universal, vector> &hoisted, GeneratedNames &names) { @@ -236,13 +238,13 @@ static void HoistMeasureNavigation(unique_ptr &expr, const Win return; } for (auto &argument : arguments) { - HoistMeasureNavigation(argument.GetExpressionMutable(), pattern_window, symbols, universal, hoisted, - names); + HoistMeasureNavigation(context, argument.GetExpressionMutable(), pattern_window, symbols, universal, + hoisted, names); } // a step is a fixed distance through the partition, so the offset is a non-negative // constant - a negative one would step the other way and a column a different way per row if (arguments.size() == 2) { - MatchRecognizeNavigationOffset(function_name, arguments[1].GetExpression()); + MatchRecognizeNavigationOffset(context, function_name, arguments[1].GetExpression()); } auto inner = std::move(arguments[0].GetExpressionMutable()); auto variable = MatchRecognizeNavigationVariable( @@ -253,7 +255,7 @@ static void HoistMeasureNavigation(unique_ptr &expr, const Win // which of that variable's rows (5.6.4). Stepping and then reading the row reached is the // same as reading the already-stepped column off the row it started from, so the step // becomes a column of the projection below and a navigation reads it from there. - auto stepped = MatchRecognizePeelStep(inner); + auto stepped = MatchRecognizePeelStep(context, inner); auto navigation = pattern_window.Copy(); auto &window = navigation->Cast(); window.SetFunctionName(function_name == "PREV" ? "lag" : "lead"); @@ -277,7 +279,7 @@ static void HoistMeasureNavigation(unique_ptr &expr, const Win } } ParsedExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { - HoistMeasureNavigation(child, pattern_window, symbols, universal, hoisted, names); + HoistMeasureNavigation(context, child, pattern_window, symbols, universal, hoisted, names); }); } @@ -1021,8 +1023,8 @@ BoundStatement Binder::Bind(MatchRecognizeRef &ref) { // PREV() and NEXT() in MEASURES walk the matcher's input, so they are computed down here too vector> measure_navigation; for (auto &expr : ref.config->measures_expression_list) { - HoistMeasureNavigation(expr, *window_template, measure_symbols, input_refs.universal, measure_navigation, - names); + HoistMeasureNavigation(context.GetContext(), expr, *window_template, measure_symbols, input_refs.universal, + measure_navigation, names); } if (!measure_navigation.empty()) { SelectBinder navigation_binder(*define_binder, context, define_node); diff --git a/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp b/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp index 3c8e608a4..ee7427b6f 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp @@ -179,7 +179,7 @@ static unique_ptr PivotFilteredAggregate(ClientContext &context, Piv for (auto &pivot_expr : pivot_column.pivot_expressions) { auto column_ref = make_uniq(LogicalType::VARCHAR, pivot_expr->Copy()); auto constant_value = ConstantExpression::FromValue( - pivot_value.values[pivot_value_idx++].DefaultCastAs(LogicalType::VARCHAR)); + pivot_value.values[pivot_value_idx++].CastAs(context, LogicalType::VARCHAR)); auto comp_expr = make_uniq(ExpressionType::COMPARE_NOT_DISTINCT_FROM, std::move(column_ref), std::move(constant_value)); if (filter) { diff --git a/src/duckdb/src/planner/binder/tableref/bind_showref.cpp b/src/duckdb/src/planner/binder/tableref/bind_showref.cpp index aa5a8e6aa..b7ee04b12 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_showref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_showref.cpp @@ -5,6 +5,10 @@ #include "duckdb/parser/tableref/showref.hpp" #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/planner/binder.hpp" +#include "duckdb/function/aggregate/distributive_functions.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_column_data_get.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -63,6 +67,32 @@ BaseTableColumnInfo FindBaseTableColumn(LogicalOperator &op, ColumnBinding bindi } break; } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + // a group or the first value of a column keeps the constraints of that column (DISTINCT plans this way) + auto &aggregate = op.Cast(); + if (aggregate.grouping_sets.size() > 1) { + // ROLLUP, CUBE and GROUPING SETS repeat keys and introduce NULLs + break; + } + optional_ptr source; + if (binding.table_index == aggregate.group_index) { + if (!aggregate.grouping_sets.empty() && + aggregate.grouping_sets[0].find(binding.column_index) == aggregate.grouping_sets[0].end()) { + break; + } + source = aggregate.GetExpression(binding); + } else if (binding.table_index == aggregate.aggregate_index && !aggregate.groups.empty()) { + // without groups first() returns NULL on empty input + auto &aggr = aggregate.GetExpression(binding).Cast(); + if (aggr.Function().GetName() == FirstFun::Name && !aggr.GetFilter() && aggr.GetChildren().size() == 1) { + source = *aggr.GetChildren()[0]; + } + } + if (source && source->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { + return FindBaseTableColumn(*aggregate.children[0], source->Cast().Binding()); + } + break; + } case LogicalOperatorType::LOGICAL_LIMIT: case LogicalOperatorType::LOGICAL_ORDER_BY: case LogicalOperatorType::LOGICAL_TOP_N: diff --git a/src/duckdb/src/planner/binder/tableref/plan_joinref.cpp b/src/duckdb/src/planner/binder/tableref/plan_joinref.cpp index 5cee18c17..27b3fc95c 100644 --- a/src/duckdb/src/planner/binder/tableref/plan_joinref.cpp +++ b/src/duckdb/src/planner/binder/tableref/plan_joinref.cpp @@ -4,6 +4,7 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression_binder/lateral_binder.hpp" @@ -353,6 +354,40 @@ static bool HasCorrelatedColumns(const Expression &root_expr) { return has_correlated_columns; } +static bool IsDependentCondition(const Expression &expr) { + return expr.HasSubquery() || HasCorrelatedColumns(expr); +} + +//! Push the conjuncts of a non-inner join condition that reference a single side into that child +//! Returns the remaining conjuncts, which have to be evaluated by the join +static unique_ptr PushSingleSideConjuncts(JoinType type, JoinRefType ref_type, + unique_ptr &left_child, + unique_ptr &right_child, + unique_ptr condition) { + unordered_set left_bindings, right_bindings; + LogicalJoin::GetTableReferences(*left_child, left_bindings); + LogicalJoin::GetTableReferences(*right_child, right_bindings); + + vector> expressions; + expressions.push_back(std::move(condition)); + LogicalFilter::SplitPredicates(expressions); + vector> remaining; + for (auto &expr : expressions) { + auto side = JoinSide::GetJoinSide(*expr, left_bindings, right_bindings); + if (side == JoinSide::LEFT && CanPushToLeftChild(type, ref_type)) { + PushFilterToChild(left_child, expr); + } else if (side == JoinSide::RIGHT && CanPushToRightChild(type, ref_type)) { + PushFilterToChild(right_child, expr); + } else { + remaining.push_back(std::move(expr)); + } + } + if (remaining.empty()) { + return make_uniq(Value::BOOLEAN(true)); + } + return BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(remaining)); +} + unique_ptr LogicalComparisonJoin::CreateJoin(ClientContext &context, JoinType type, JoinRefType reftype, unique_ptr left_child, @@ -422,16 +457,19 @@ unique_ptr Binder::CreatePlan(BoundJoinRef &ref) { break; } auto has_dependent_condition = ref.ref_type == JoinRefType::REGULAR && ref.type != JoinType::INNER && - (ref.condition->HasSubquery() || HasCorrelatedColumns(*ref.condition)) && - ref.duplicate_eliminated_columns.empty(); + IsDependentCondition(*ref.condition) && ref.duplicate_eliminated_columns.empty(); + if (has_dependent_condition) { + // only the conjuncts that remain at the join need dependent join planning + ref.condition = PushSingleSideConjuncts(ref.type, ref.ref_type, left, right, std::move(ref.condition)); + has_dependent_condition = IsDependentCondition(*ref.condition); + } if (!has_dependent_condition && ref.type == JoinType::RIGHT && ref.ref_type != JoinRefType::ASOF && !Optimizer::OptimizerDisabled(context, OptimizerType::BUILD_SIDE_PROBE_SIDE)) { // Binding follows the syntactic order. Normalize finalized RIGHT joins only after both sides and ON are bound. ref.type = JoinType::LEFT; std::swap(left, right); } - if (ref.type == JoinType::INNER && (ref.condition->HasSubquery() || HasCorrelatedColumns(*ref.condition)) && - ref.ref_type == JoinRefType::REGULAR) { + if (ref.type == JoinType::INNER && IsDependentCondition(*ref.condition) && ref.ref_type == JoinRefType::REGULAR) { // inner join, generate a cross product + filter // this will be later turned into a proper join by the join order optimizer auto root = LogicalCrossProduct::Create(std::move(left), std::move(right)); diff --git a/src/duckdb/src/planner/column_qualifier.cpp b/src/duckdb/src/planner/column_qualifier.cpp index 265e96fb0..ebe8b644a 100644 --- a/src/duckdb/src/planner/column_qualifier.cpp +++ b/src/duckdb/src/planner/column_qualifier.cpp @@ -257,16 +257,42 @@ void ColumnQualifier::QualifyColumnNames(unique_ptr &expr, vec }); } +bool ColumnQualifier::IsActiveLambdaParameter(const Identifier &name) { + // while qualifying a lambda body, the parameters live in definite_lambda_params + if (LambdaExpression::IsLambdaParameter(definite_lambda_params, name)) { + return true; + } + // while binding a lambda body, the parameters live in the lambda bindings + return LambdaRefExpression::FindMatchingBinding(lambda_bindings, name) != nullptr; +} + optional_ptr ColumnQualifier::QualifyFunction(FunctionExpression &function) { D_ASSERT(!ExpressionBinder::IsUnnestFunction(function.FunctionName())); // lookup the function in the catalog QueryErrorContext error_context(function.GetQueryLocation()); + EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, QualifiedName(function.FunctionName()), + error_context); + + // a lone qualifier that names a lambda parameter and a search-path function is a dot call on that parameter + if (function.GetQualifiedName().Catalog().empty() && !function.GetQualifiedName().Schema().empty() && + IsActiveLambdaParameter(function.GetQualifiedName().Schema())) { + auto func = binder.GetCatalogEntry(Identifier::InvalidCatalog(), Identifier::InvalidSchema(), function_lookup, + OnEntryNotFound::RETURN_NULL); + if (func) { + // leave the parameter as an unqualified column reference - the lambda binding resolves it + unique_ptr param_ref = + make_uniq(function.GetQualifiedName().Schema()); + function.GetArgumentsMutable().insert(function.GetArgumentsMutable().begin(), std::move(param_ref)); + function.SetQualifiedName(QualifiedName(function.GetQualifiedName().Name())); + return func; + } + // the function is not on the search path - fall through to the catalog and schema interpretation + } + // promote a lone qualifier that names an attached database to a catalog, so that "db.f()" is not mistaken for a // dot-call on a column named "db" by the rewrite below binder.BindSchemaOrCatalog(function.GetQualifiedNameMutable()); - EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, QualifiedName(function.FunctionName()), - error_context); // resolve the qualification: this decides whether a leading component (e.g. "s1" in "s1.s2.my_macro()") is a // catalog or the outermost schema of a nested schema path. The name as written is left alone - the dot-call // rewrite below turns the qualification into a column reference and needs it unresolved. @@ -334,11 +360,19 @@ void ColumnQualifier::QualifyColumnNamesInLambda(FunctionExpression &function, // push this level lambda_params.emplace_back(); + // an arrow can turn out to be the JSON operator, so only keyword parameters shadow function qualifiers + const bool is_keyword_lambda = lambda_expr.GetLambdaSyntaxType() == LambdaSyntaxType::LAMBDA_KEYWORD; + if (is_keyword_lambda) { + definite_lambda_params.emplace_back(); + } // push the lambda parameter names for (const auto &column_ref_expr : column_ref_expressions) { const auto &column_ref = column_ref_expr.get().Cast(); lambda_params.back().emplace(column_ref.GetName()); + if (is_keyword_lambda) { + definite_lambda_params.back().emplace(column_ref.GetName()); + } } // only qualify in RHS @@ -346,6 +380,9 @@ void ColumnQualifier::QualifyColumnNamesInLambda(FunctionExpression &function, // pop this level lambda_params.pop_back(); + if (is_keyword_lambda) { + definite_lambda_params.pop_back(); + } } } diff --git a/src/duckdb/src/planner/expression/bound_cast_expression.cpp b/src/duckdb/src/planner/expression/bound_cast_expression.cpp index e49a82cbf..7afbd4bae 100644 --- a/src/duckdb/src/planner/expression/bound_cast_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_cast_expression.cpp @@ -280,6 +280,62 @@ bool BoundCastExpression::CastIsInvertible(const LogicalType &source_type, const return true; } +bool BoundCastExpression::IsLosslessIntegralToFloatingCast(const LogicalType &source_type, + const LogicalType &target_type) { + if (target_type.id() == LogicalTypeId::DOUBLE) { + switch (source_type.id()) { + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + return true; + default: + return false; + } + } + if (target_type.id() == LogicalTypeId::FLOAT) { + switch (source_type.id()) { + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + return true; + default: + return false; + } + } + return false; +} + +bool BoundCastExpression::CastIsInvertibleForEquality(const LogicalType &source_type, const LogicalType &target_type) { + if (source_type.IsIntegral()) { + if (target_type.id() == LogicalTypeId::VARCHAR) { + // a collation can make distinct strings equal + return StringType::GetCollation(target_type).empty(); + } + if (IsLosslessIntegralToFloatingCast(source_type, target_type)) { + return true; + } + return target_type.IsIntegral() && CastIsInvertible(source_type, target_type); + } + return source_type.id() == LogicalTypeId::FLOAT && target_type.id() == LogicalTypeId::DOUBLE; +} + +optional BoundCastExpression::TryInvertConstant(ClientContext &context, const BoundFunctionExpression &cast_expr, + const Value &constant) { + auto source_constant = constant.TryCastAs(context, SourceType(cast_expr), nullptr, true); + if (!source_constant) { + return nullopt; + } + auto roundtrip = source_constant->TryCastAs(context, TargetType(cast_expr), nullptr, true); + if (!roundtrip || !Value::NotDistinctFrom(*roundtrip, constant)) { + return nullopt; + } + return source_constant; +} + //! The child type of a LIST or ARRAY static const LogicalType &ListOrArrayChildType(const LogicalType &type) { return type.id() == LogicalTypeId::ARRAY ? ArrayType::GetChildType(type) : ListType::GetChildType(type); diff --git a/src/duckdb/src/planner/expression_binder/match_recognize_binder.cpp b/src/duckdb/src/planner/expression_binder/match_recognize_binder.cpp index 9eb998214..5bb8efacb 100644 --- a/src/duckdb/src/planner/expression_binder/match_recognize_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/match_recognize_binder.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/client_context.hpp" #include "duckdb/planner/expression_binder/match_recognize_binder.hpp" #include "duckdb/function/function_binder.hpp" @@ -165,7 +166,8 @@ static bool HasAggregateModifiers(const FunctionExpression &function) { return function.Distinct() || function.Filter() || (function.OrderBy() && !function.OrderBy()->orders.empty()); } -idx_t MatchRecognizeNavigationOffset(const string &function_name, const ParsedExpression &offset_expr) { +idx_t MatchRecognizeNavigationOffset(Context &context, const string &function_name, + const ParsedExpression &offset_expr) { if (offset_expr.GetExpressionType() != ExpressionType::VALUE_CONSTANT) { throw BinderException("The offset of %s() must be a constant", function_name); } @@ -173,7 +175,7 @@ idx_t MatchRecognizeNavigationOffset(const string &function_name, const ParsedEx if (offset_value.IsNull()) { throw BinderException("The offset of %s() must be a non-negative integer, not NULL", function_name); } - if (!offset_value.DefaultTryCastAs(LogicalType::UBIGINT) || offset_value.IsNull()) { + if (!offset_value.TryCastAs(context, LogicalType::UBIGINT) || offset_value.IsNull()) { throw BinderException("The offset of %s() must be a non-negative integer", function_name); } const auto offset = offset_value.GetValue(); @@ -437,7 +439,7 @@ void MatchRecognizeRejectNestedStep(const ParsedExpression &inner, const string } } -MatchRecognizeSteppedNavigation MatchRecognizePeelStep(unique_ptr &inner) { +MatchRecognizeSteppedNavigation MatchRecognizePeelStep(Context &context, unique_ptr &inner) { MatchRecognizeSteppedNavigation result; if (inner->GetExpressionType() == ExpressionType::FUNCTION) { auto &marker = inner->Cast(); @@ -458,7 +460,7 @@ MatchRecognizeSteppedNavigation MatchRecognizePeelStep(unique_ptr 0; }, universal, function_name); - auto stepped = MatchRecognizePeelStep(inner); + auto stepped = MatchRecognizePeelStep(context.GetContext(), inner); if (stepped.final_semantics) { throw BinderException("FINAL reads the whole match, which a DEFINE condition is still assembling, so " "only RUNNING is available there"); @@ -720,10 +722,10 @@ BindResult MatchRecognizeDefineBinder::BindNeighbour(FunctionExpression &functio } // the classifier of the row a fixed distance from the row navigated to, which the matcher // reads off the attempt under way (5.9); a step naming no variable starts from the row tested - const auto distance = - arguments.size() == 2 - ? NumericCast(MatchRecognizeNavigationOffset(function_name, arguments[1].GetExpression())) - : int64_t(1); + const auto distance = arguments.size() == 2 + ? NumericCast(MatchRecognizeNavigationOffset( + context.GetContext(), function_name, arguments[1].GetExpression())) + : int64_t(1); auto symbol = variable.empty() ? string() : MatchRecognizeDefineColumn(variable); return BindNavigated(std::move(inner), std::move(symbol), !stepped.navigated || stepped.last, stepped.offset_value, depth, function_name == "PREV" ? -distance : distance); @@ -758,7 +760,7 @@ BindResult MatchRecognizeDefineBinder::BindNavigation(FunctionExpression &functi } idx_t offset = 0; if (arguments.size() == 2) { - offset = MatchRecognizeNavigationOffset(function_name, arguments[1].GetExpression()); + offset = MatchRecognizeNavigationOffset(context.GetContext(), function_name, arguments[1].GetExpression()); } auto inner = std::move(arguments[0].GetExpressionMutable()); auto variable = MatchRecognizeNavigationVariable( @@ -1005,12 +1007,13 @@ BindResult MatchRecognizeMeasureBinder::BindClassifierStep(FunctionExpression &f MatchRecognizeRejectNestedStep(arguments[0].GetExpression(), function_name); int64_t distance = 1; if (arguments.size() == 2) { - distance = NumericCast(MatchRecognizeNavigationOffset(function_name, arguments[1].GetExpression())); + distance = NumericCast( + MatchRecognizeNavigationOffset(context.GetContext(), function_name, arguments[1].GetExpression())); } auto inner = std::move(arguments[0].GetExpressionMutable()); auto variable = MatchRecognizeNavigationVariable( inner, [&](const string &name) { return symbols.find(name) != symbols.end(); }, universal, function_name); - auto stepped = MatchRecognizePeelStep(inner); + auto stepped = MatchRecognizePeelStep(context.GetContext(), inner); if (!IsClassifierRead(*inner)) { throw BinderException("%s() over CLASSIFIER() reads the classifier of the row it steps to, and nothing else " "of it", @@ -1082,7 +1085,8 @@ BindResult MatchRecognizeMeasureBinder::BindNavigation(FunctionExpression &funct bool root_expression) { idx_t offset = 0; if (function.GetArguments().size() == 2) { - offset = MatchRecognizeNavigationOffset(function_name, function.GetArguments()[1].GetExpression()); + offset = MatchRecognizeNavigationOffset(context.GetContext(), function_name, + function.GetArguments()[1].GetExpression()); } auto inner = std::move(function.GetArgumentsMutable()[0].GetExpressionMutable()); auto variable = MatchRecognizeNavigationVariable( diff --git a/src/duckdb/src/planner/sql_export/sql_export_relations.cpp b/src/duckdb/src/planner/sql_export/sql_export_relations.cpp index fa6335d85..667bb99cc 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_relations.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_relations.cpp @@ -18,6 +18,8 @@ #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/function/aggregate/distributive_functions.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/operator/logical_filter.hpp" @@ -340,10 +342,69 @@ LogicalPlanSQLExportResult LogicalSetOperation::ToSQL(LogicalPlanSQLExportContex return LogicalPlanSQLExportResult::Success({std::move(query), std::move(fields.GetValue())}); } +//! Whether the aggregate is a DISTINCT ON without ORDER BY: groups plus the first value of every other column +static bool IsInputOrderedDistinct(const LogicalAggregate &aggregate) { + if (!aggregate.preserve_input_order || aggregate.grouping_sets.size() > 1 || + !aggregate.grouping_functions.empty() || aggregate.groups.empty()) { + return false; + } + for (auto &expression : aggregate.expressions) { + auto &aggr = expression->Cast(); + if (aggr.Function().GetName() != FirstFun::Name || aggr.GetFilter() || aggr.GetOrderBys() || + aggr.GetChildren().size() != 1 || aggr.IsDistinct()) { + return false; + } + } + return true; +} + +//! Export as DISTINCT ON, which keeps the first row of every group in input order +static LogicalPlanSQLExportResult ExportInputOrderedDistinct(LogicalAggregate &aggregate, + LogicalPlanSQLExportContext &context, + const LogicalPlanVerificationPath &path) { + auto fields = LogicalPlanSQLExportHelpers::CreateFields(aggregate, path); + if (fields.HasError()) { + return LogicalPlanSQLExportResult::Failure(fields); + } + auto child = context.ExportChild(*aggregate.children[0], LogicalPlanSQLExportHelpers::PlanChildPath(path, 0)); + if (child.HasError()) { + return LogicalPlanSQLExportResult::Failure(child); + } + auto expression_context = + LogicalPlanSQLExportHelpers::CreateBindingContext(context.GetClientContext(), {child.GetValue()}); + vector> expressions; + for (auto &group : aggregate.groups) { + expressions.push_back(*group); + } + for (auto &expression : aggregate.expressions) { + expressions.push_back(*expression->Cast().GetChildren()[0]); + } + auto select = make_uniq(); + auto modifier = make_uniq(); + for (idx_t i = 0; i < expressions.size(); i++) { + ApplySemanticType(fields.GetValue()[i], expressions[i].get(), expression_context); + auto expression = context.ExportExpression(aggregate, expressions, i, expression_context, path); + if (expression.HasError()) { + return LogicalPlanSQLExportResult::Failure(expression); + } + if (i < aggregate.groups.size()) { + modifier->distinct_on_targets.push_back(expression.GetValue()->Copy()); + } + expression.GetValue()->SetAlias(LogicalPlanSQLExportHelpers::FieldIdentifier(i)); + select->select_list.push_back(std::move(expression.GetValue())); + } + select->modifiers.push_back(std::move(modifier)); + select->from_table = LogicalPlanSQLExportHelpers::CreateSubquery(std::move(child.GetValue())); + return LogicalPlanSQLExportResult::Success({std::move(select), std::move(fields.GetValue())}); +} + LogicalPlanSQLExportResult LogicalAggregate::ToSQL(LogicalPlanSQLExportContext &export_context, const LogicalPlanVerificationPath &path) { auto &aggregate = *this; D_ASSERT(aggregate.children.size() == 1); + if (IsInputOrderedDistinct(aggregate)) { + return ExportInputOrderedDistinct(aggregate, export_context, path); + } #ifdef D_ASSERT_IS_ENABLED for (auto &expression : aggregate.expressions) { D_ASSERT(expression && expression->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE); diff --git a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp index 13026b689..20e1ac134 100644 --- a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp +++ b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp @@ -2608,7 +2608,6 @@ static bool CanRestrictCorrelationDomain(LogicalOperator &op, unordered_set(); + for (auto &cond : join.conditions) { + if (!cond.IsComparison()) { + continue; + } + auto &operand = side == 0 ? cond.GetLHS() : cond.GetRHS(); + if (operand.IsVolatile()) { + return true; + } + } + return false; +} + optional_ptr FlattenDependentJoins::GetCorrelatedBase(const ColumnBinding &binding) const { auto entry = correlated_aliases.find(binding); if (entry == correlated_aliases.end()) { @@ -1195,8 +1218,8 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownJoin(unique vector state) { auto join_type = plan->Cast().join_type; D_ASSERT(plan->children.size() == 2); - bool left_requires_domain = RequiresDomain(*plan->children[0]); - bool right_requires_domain = RequiresDomain(*plan->children[1]); + bool left_requires_domain = RequiresDomain(*plan->children[0]) || JoinOperandRequiresDomain(*plan, 0); + bool right_requires_domain = RequiresDomain(*plan->children[1]) || JoinOperandRequiresDomain(*plan, 1); // An ASOF join selects at most one match per left row from its entire right input. If the right input // varies per domain, the left input must carry the domain too, so the selection partitions per domain. @@ -1459,15 +1482,6 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownSetOperatio return result; } -FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownDistinct(unique_ptr &plan, - bool propagate_null_values, - vector state) { - auto result = PushDownChild(plan, propagate_null_values, std::move(state), false); - auto &distinct = plan->Cast(); - AppendCorrelatedColumns(distinct.distinct_targets, result.bindings, false); - return result; -} - FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownExpressionGet(unique_ptr &plan, bool propagate_null_values, vector state) { @@ -1717,9 +1731,6 @@ FlattenDependentJoins::PushDownCorrelatedNodeInternal(unique_ptr(source_data.data())), count_t(scan_count)); } +//===--------------------------------------------------------------------===// +// Select +//===--------------------------------------------------------------------===// +template +void FixedSizeSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, + const SelectionVector &sel, idx_t sel_count, idx_t result_offset, ScanVectorType scan_type) { + auto &scan_state = state.scan_state->Cast(); + auto start = state.GetPositionInSegment(); + + auto source_data = scan_state.reader.GetArraySlice(0, start, vector_count); + + result.SetVectorType(VectorType::FLAT_VECTOR); + auto result_data = FlatVector::GetDataMutable(result) + result_offset; + for (idx_t i = 0; i < sel_count; i++) { + result_data[i] = source_data[sel.get_index(i)]; + } +} + //===--------------------------------------------------------------------===// // Append //===--------------------------------------------------------------------===// @@ -265,12 +283,14 @@ idx_t FixedSizeFinalizeAppend(ColumnSegment &segment, BaseStatistics &stats) { //===--------------------------------------------------------------------===// template CompressionFunction FixedSizeGetFunction(PhysicalType data_type) { - return CompressionFunction(CompressionType::COMPRESSION_UNCOMPRESSED, data_type, FixedSizeInitAnalyze, - FixedSizeAnalyze, FixedSizeFinalAnalyze, UncompressedFunctions::InitCompression, - UncompressedFunctions::Compress, UncompressedFunctions::FinalizeCompress, - FixedSizeInitScan, FixedSizeScan, FixedSizeScanPartial, - UncompressedFunctions::EmptySkip, nullptr, FixedSizeInitAppend, - FixedSizeAppend, FixedSizeFinalizeAppend); + auto function = + CompressionFunction(CompressionType::COMPRESSION_UNCOMPRESSED, data_type, FixedSizeInitAnalyze, + FixedSizeAnalyze, FixedSizeFinalAnalyze, UncompressedFunctions::InitCompression, + UncompressedFunctions::Compress, UncompressedFunctions::FinalizeCompress, FixedSizeInitScan, + FixedSizeScan, FixedSizeScanPartial, UncompressedFunctions::EmptySkip, nullptr, + FixedSizeInitAppend, FixedSizeAppend, FixedSizeFinalizeAppend); + function.select = FixedSizeSelect; + return function; } CompressionFunction FixedSizeUncompressed::GetFunction(PhysicalType data_type) { diff --git a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp index 440ba5ba4..f9366f67f 100644 --- a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp +++ b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp @@ -273,6 +273,7 @@ void LogicalAggregate::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault>(205, "grouping_sets", grouping_sets); serializer.WritePropertyWithDefault>>(206, "grouping_functions", grouping_functions); serializer.WritePropertyWithDefault(207, "distinct_validity", distinct_validity, TupleDataValidityType::CAN_HAVE_NULL_VALUES); + serializer.WritePropertyWithDefault(208, "preserve_input_order", preserve_input_order, false); } unique_ptr LogicalAggregate::Deserialize(Deserializer &deserializer) { @@ -285,6 +286,7 @@ unique_ptr LogicalAggregate::Deserialize(Deserializer &deserial deserializer.ReadPropertyWithDefault>(205, "grouping_sets", result->grouping_sets); deserializer.ReadPropertyWithDefault>>(206, "grouping_functions", result->grouping_functions); deserializer.ReadPropertyWithExplicitDefault(207, "distinct_validity", result->distinct_validity, TupleDataValidityType::CAN_HAVE_NULL_VALUES); + deserializer.ReadPropertyWithExplicitDefault(208, "preserve_input_order", result->preserve_input_order, false); return std::move(result); } diff --git a/src/duckdb/src/storage/statistics/array_stats.cpp b/src/duckdb/src/storage/statistics/array_stats.cpp index e128ed695..488165aa8 100644 --- a/src/duckdb/src/storage/statistics/array_stats.cpp +++ b/src/duckdb/src/storage/statistics/array_stats.cpp @@ -1,6 +1,7 @@ #include "duckdb/common/vector/array_vector.hpp" #include "duckdb/storage/statistics/array_stats.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/serializer/serializer.hpp" @@ -84,13 +85,20 @@ void ArrayStats::Deserialize(Deserializer &deserializer, BaseStatistics &base) { deserializer.Unset(); } -child_list_t ArrayStats::ToStruct(const BaseStatistics &stats) { +child_list_t ArrayStats::ToStruct(const BaseStatistics &stats, bool exact) { auto &child_stats = ArrayStats::GetChildStats(stats); child_list_t result; - result.emplace_back("child_stats", child_stats.ToStruct()); + result.emplace_back("child_stats", child_stats.ToStruct(exact)); return result; } +void ArrayStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + auto child = fields.Get("child_stats"); + if (child) { + GetChildStats(stats).SetFromStruct(*child, fields.FieldPath("child_stats")); + } +} + void ArrayStats::Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count) { auto &child_stats = ArrayStats::GetChildStats(stats); const auto &child_entry = ArrayVector::GetChild(vector); diff --git a/src/duckdb/src/storage/statistics/base_statistics.cpp b/src/duckdb/src/storage/statistics/base_statistics.cpp index b5365a6bb..dd80cc014 100644 --- a/src/duckdb/src/storage/statistics/base_statistics.cpp +++ b/src/duckdb/src/storage/statistics/base_statistics.cpp @@ -7,6 +7,7 @@ #include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" #include "duckdb/storage/statistics/array_stats.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" @@ -474,29 +475,29 @@ BaseStatistics BaseStatistics::Deserialize(Deserializer &deserializer) { return stats; } -Value BaseStatistics::ToStruct() const { +Value BaseStatistics::ToStruct(bool exact) const { child_list_t children; switch (GetStatsType()) { case StatisticsType::NUMERIC_STATS: children = NumericStats::ToStruct(*this); break; case StatisticsType::STRING_STATS: - children = StringStats::ToStruct(*this); + children = StringStats::ToStruct(*this, exact); break; case StatisticsType::LIST_STATS: - children = ListStats::ToStruct(*this); + children = ListStats::ToStruct(*this, exact); break; case StatisticsType::STRUCT_STATS: - children = StructStats::ToStruct(*this); + children = StructStats::ToStruct(*this, exact); break; case StatisticsType::ARRAY_STATS: - children = ArrayStats::ToStruct(*this); + children = ArrayStats::ToStruct(*this, exact); break; case StatisticsType::GEOMETRY_STATS: - children = GeometryStats::ToStruct(*this); + children = GeometryStats::ToStruct(*this, exact); break; case StatisticsType::VARIANT_STATS: - children = VariantStats::ToStruct(*this); + children = VariantStats::ToStruct(*this, exact); break; default: break; @@ -513,6 +514,46 @@ string BaseStatistics::ToString() const { return ToStruct().ToString(); } +void BaseStatistics::SetFromStruct(const Value &value, const string &path) { + StatsStructFields fields(value, path); + Value field; + if (fields.TryGet("has_null", LogicalType::BOOLEAN, field)) { + has_null = BooleanValue::Get(field); + } + if (fields.TryGet("has_no_null", LogicalType::BOOLEAN, field)) { + has_no_null = BooleanValue::Get(field); + } + if (fields.TryGet("approx_unique", LogicalType::UBIGINT, field)) { + distinct_count = UBigIntValue::Get(field); + } + switch (GetStatsType()) { + case StatisticsType::NUMERIC_STATS: + NumericStats::SetFromStruct(*this, fields); + break; + case StatisticsType::STRING_STATS: + StringStats::SetFromStruct(*this, fields); + break; + case StatisticsType::LIST_STATS: + ListStats::SetFromStruct(*this, fields); + break; + case StatisticsType::STRUCT_STATS: + StructStats::SetFromStruct(*this, fields); + break; + case StatisticsType::ARRAY_STATS: + ArrayStats::SetFromStruct(*this, fields); + break; + case StatisticsType::GEOMETRY_STATS: + GeometryStats::SetFromStruct(*this, fields); + break; + case StatisticsType::VARIANT_STATS: + VariantStats::SetFromStruct(*this, fields); + break; + default: + break; + } + fields.VerifyAllRead(type); +} + void BaseStatistics::Verify(const Vector &vector, const SelectionVector &sel, idx_t count, const bool ignore_has_null) const { D_ASSERT(vector.GetType() == this->type); diff --git a/src/duckdb/src/storage/statistics/geometry_stats.cpp b/src/duckdb/src/storage/statistics/geometry_stats.cpp index 7c6235bc7..bea8410e5 100644 --- a/src/duckdb/src/storage/statistics/geometry_stats.cpp +++ b/src/duckdb/src/storage/statistics/geometry_stats.cpp @@ -1,5 +1,6 @@ #include "duckdb/storage/statistics/geometry_stats.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/serializer/serializer.hpp" @@ -158,7 +159,7 @@ void GeometryStats::Deserialize(Deserializer &deserializer, BaseStatistics &base deserializer.ReadPropertyWithDefault(302, "flags", data.flags.flags); } -child_list_t GeometryStats::ToStruct(const BaseStatistics &stats) { +child_list_t GeometryStats::ToStruct(const BaseStatistics &stats, bool exact) { const auto &data = GetDataUnsafe(stats); child_list_t result; child_list_t extent; @@ -178,6 +179,15 @@ child_list_t GeometryStats::ToStruct(const BaseStatistics &stats) { result.emplace_back("extent", Value::STRUCT(std::move(extent))); + // the types the column holds are not part of the rendering stats() shows + if (exact && !data.types.IsUnknown()) { + vector types; + for (auto &name : data.types.ToString(true)) { + types.emplace_back(name); + } + result.emplace_back("types", Value::LIST(LogicalType::VARCHAR, std::move(types))); + } + result.emplace_back("has_empty_geom", Value::BOOLEAN(data.flags.HasEmptyGeometry())); result.emplace_back("has_non_empty_geom", Value::BOOLEAN(data.flags.HasNonEmptyGeometry())); result.emplace_back("has_empty_part", Value::BOOLEAN(data.flags.HasEmptyPart())); @@ -185,6 +195,85 @@ child_list_t GeometryStats::ToStruct(const BaseStatistics &stats) { return result; } +//! A bound of the extent, by the field name ToStruct gives it +struct GeometryExtentBound { + const char *name; + double &bound; +}; + +//! A flag of the statistics, by the field name ToStruct gives it +struct GeometryStatsFlag { + const char *name; + bool &value; +}; + +void GeometryStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + auto &data = GetDataUnsafe(stats); + Value field; + + auto extent = fields.Get("extent"); + if (extent) { + StatsStructFields bounds(*extent, fields.FieldPath("extent")); + const GeometryExtentBound axes[] = {{"x_min", data.extent.x_min}, {"x_max", data.extent.x_max}, + {"y_min", data.extent.y_min}, {"y_max", data.extent.y_max}, + {"z_min", data.extent.z_min}, {"z_max", data.extent.z_max}, + {"m_min", data.extent.m_min}, {"m_max", data.extent.m_max}}; + for (auto &axis : axes) { + if (bounds.TryGet(axis.name, LogicalType::DOUBLE, field)) { + axis.bound = DoubleValue::Get(field); + } + } + bounds.VerifyAllRead(stats.GetType()); + } + + auto types = fields.Get("types"); + if (types) { + if (types->type().id() != LogicalTypeId::LIST) { + fields.Throw("types", "expected a list of geometry type names, e.g. ['point', 'polygon_z']"); + } + auto type_set = GeometryTypeSet::Empty(); + for (auto &entry : ListValue::GetChildren(*types)) { + auto name = StatsStructFields::Plain(entry); + if (name.IsNull() || name.type().id() != LogicalTypeId::VARCHAR || + !type_set.TryAdd(StringValue::Get(name))) { + fields.Throw("types", + StringUtil::Format("'%s' is not a geometry type name, e.g. 'point' or 'polygon_z'", + name.ToString())); + } + } + data.types = type_set; + } + + // a flag that is not given keeps its value + bool has_empty_geom = data.flags.HasEmptyGeometry(); + bool has_non_empty_geom = data.flags.HasNonEmptyGeometry(); + bool has_empty_part = data.flags.HasEmptyPart(); + bool has_non_empty_part = data.flags.HasNonEmptyPart(); + const GeometryStatsFlag flags[] = {{"has_empty_geom", has_empty_geom}, + {"has_non_empty_geom", has_non_empty_geom}, + {"has_empty_part", has_empty_part}, + {"has_non_empty_part", has_non_empty_part}}; + for (auto &flag : flags) { + if (fields.TryGet(flag.name, LogicalType::BOOLEAN, field)) { + flag.value = BooleanValue::Get(field); + } + } + auto new_flags = GeometryStatsFlags::Empty(); + if (has_empty_geom) { + new_flags.SetHasEmptyGeometry(); + } + if (has_non_empty_geom) { + new_flags.SetHasNonEmptyGeometry(); + } + if (has_empty_part) { + new_flags.SetHasEmptyPart(); + } + if (has_non_empty_part) { + new_flags.SetHasNonEmptyPart(); + } + data.flags = new_flags; +} + void GeometryStats::Update(BaseStatistics &stats, const string_t &value) { auto &data = GetDataUnsafe(stats); data.Update(value); diff --git a/src/duckdb/src/storage/statistics/list_stats.cpp b/src/duckdb/src/storage/statistics/list_stats.cpp index b8ee6ecb5..3264b0d0b 100644 --- a/src/duckdb/src/storage/statistics/list_stats.cpp +++ b/src/duckdb/src/storage/statistics/list_stats.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/vector.hpp" @@ -216,7 +217,7 @@ void ListStats::Deserialize(Deserializer &deserializer, BaseStatistics &base) { list_data.total_list_length = total_list_length.IsValid() ? total_list_length.GetIndex() : 0; } -child_list_t ListStats::ToStruct(const BaseStatistics &stats) { +child_list_t ListStats::ToStruct(const BaseStatistics &stats, bool exact) { auto &child_stats = ListStats::GetChildStats(stats); child_list_t result; auto &list_data = GetDataUnsafe(stats); @@ -229,10 +230,31 @@ child_list_t ListStats::ToStruct(const BaseStatistics &stats) { if (list_data.has_total_list_length) { result.emplace_back("total_list_length", Value::UBIGINT(list_data.total_list_length)); } - result.emplace_back("child_stats", child_stats.ToStruct()); + result.emplace_back("child_stats", child_stats.ToStruct(exact)); return result; } +void ListStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + auto &list_data = GetDataUnsafe(stats); + Value field; + if (fields.TryGet("min_list_length", LogicalType::UBIGINT, field)) { + list_data.has_min_list_length = true; + list_data.min_list_length = UBigIntValue::Get(field); + } + if (fields.TryGet("max_list_length", LogicalType::UBIGINT, field)) { + list_data.has_max_list_length = true; + list_data.max_list_length = UBigIntValue::Get(field); + } + if (fields.TryGet("total_list_length", LogicalType::UBIGINT, field)) { + list_data.has_total_list_length = true; + list_data.total_list_length = UBigIntValue::Get(field); + } + auto child = fields.Get("child_stats"); + if (child) { + GetChildStats(stats).SetFromStruct(*child, fields.FieldPath("child_stats")); + } +} + void ListStats::Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count) { auto &child_stats = ListStats::GetChildStats(stats); const auto &child_entry = ListVector::GetChild(vector); diff --git a/src/duckdb/src/storage/statistics/numeric_stats.cpp b/src/duckdb/src/storage/statistics/numeric_stats.cpp index 5706cfa55..02f54c355 100644 --- a/src/duckdb/src/storage/statistics/numeric_stats.cpp +++ b/src/duckdb/src/storage/statistics/numeric_stats.cpp @@ -8,6 +8,7 @@ #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" #include @@ -692,6 +693,16 @@ child_list_t NumericStats::ToStruct(const BaseStatistics &stats) { return result; } +void NumericStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + Value bound; + if (fields.TryGet("min", stats.GetType(), bound)) { + SetMin(stats, bound); + } + if (fields.TryGet("max", stats.GetType(), bound)) { + SetMax(stats, bound); + } +} + [[noreturn]] static void ThrowStatisticsMismatch(const char *message, const BaseStatistics &stats, const Vector &vector) { throw InternalException("%s\nStatistics: %s\nVector: %s", message, stats.ToString(), vector.ToString()); diff --git a/src/duckdb/src/storage/statistics/stats_struct_fields.cpp b/src/duckdb/src/storage/statistics/stats_struct_fields.cpp new file mode 100644 index 000000000..edc7655e3 --- /dev/null +++ b/src/duckdb/src/storage/statistics/stats_struct_fields.cpp @@ -0,0 +1,99 @@ +#include "duckdb/storage/statistics/stats_struct_fields.hpp" + +#include "duckdb/common/exception.hpp" +#include "duckdb/common/string_util.hpp" + +namespace duckdb { + +Value StatsStructFields::Plain(const Value &value) { + if (value.type().id() != LogicalTypeId::VARIANT || value.IsNull()) { + return value; + } + return VariantValue::GetValue(value); +} + +StatsStructFields::StatsStructFields(const Value &input, string path_p) : value(Plain(input)), path(std::move(path_p)) { + if (value.IsNull()) { + Throw("expected a struct of statistics, got NULL"); + } + if (value.type().id() != LogicalTypeId::STRUCT) { + Throw(StringUtil::Format("expected a struct of statistics, got a value of type %s", value.type().ToString())); + } + read.resize(StructType::GetChildCount(value.type()), false); +} + +optional_ptr StatsStructFields::Get(const string &name) { + auto &child_types = StructType::GetChildTypes(value.type()); + for (idx_t i = 0; i < child_types.size(); i++) { + if (child_types[i].first == name) { + return FieldValue(i); + } + } + return nullptr; +} + +bool StatsStructFields::TryGet(const string &name, const LogicalType &type, Value &result) { + auto field = Get(name); + if (!field) { + return false; + } + auto plain = Plain(*field); + string error; + auto cast = plain.DefaultTryCastAs(type, &error, true); + if (!cast) { + Throw(name, StringUtil::Format("the value '%s' of type %s does not convert to %s", plain.ToString(), + plain.type().ToString(), type.ToString())); + } + result = std::move(*cast); + return true; +} + +idx_t StatsStructFields::FieldCount() const { + return read.size(); +} + +const string &StatsStructFields::FieldName(idx_t index) const { + return StructType::GetChildTypes(value.type())[index].first.GetIdentifierName(); +} + +optional_ptr StatsStructFields::FieldValue(idx_t index) { + read[index] = true; + auto &child = StructValue::GetChildren(value)[index]; + if (child.IsNull()) { + return nullptr; + } + return child; +} + +LogicalType StatsStructFields::FieldType(idx_t index) const { + return Plain(StructValue::GetChildren(value)[index]).type(); +} + +const string &StatsStructFields::Path() const { + return path; +} + +string StatsStructFields::FieldPath(const string &name) const { + return path.empty() ? name : path + "." + name; +} + +void StatsStructFields::Throw(const string &problem) const { + if (path.empty()) { + throw InvalidInputException("statistics: %s", problem); + } + throw InvalidInputException("statistics field '%s': %s", path, problem); +} + +void StatsStructFields::Throw(const string &name, const string &problem) const { + throw InvalidInputException("statistics field '%s': %s", FieldPath(name), problem); +} + +void StatsStructFields::VerifyAllRead(const LogicalType &type) const { + for (idx_t i = 0; i < read.size(); i++) { + if (!read[i]) { + Throw(FieldName(i), StringUtil::Format("statistics of type %s have no such part", type.ToString())); + } + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/storage/statistics/string_stats.cpp b/src/duckdb/src/storage/statistics/string_stats.cpp index 118d36e81..b726f9c78 100644 --- a/src/duckdb/src/storage/statistics/string_stats.cpp +++ b/src/duckdb/src/storage/statistics/string_stats.cpp @@ -12,6 +12,7 @@ #include "utf8proc_wrapper.hpp" #include "duckdb/common/types/blob.hpp" #include "duckdb/storage/statistics/stats_writer.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" namespace duckdb { @@ -809,12 +810,27 @@ FilterPropagateResult StringStats::CheckZonemap(string_t min, StringStatsType mi } } -child_list_t StringStats::ToStruct(const BaseStatistics &stats) { +//! A bound as a value of the column's type; a VARCHAR bound whose bytes (a truncated prefix) are not valid UTF-8 is +//! a BLOB +static Value StringStatsBoundValue(const LogicalType &type, const string_t &bound) { + if (type.id() == LogicalTypeId::VARCHAR && + Utf8Proc::Analyze(bound.GetData(), bound.GetSize()) != UnicodeType::INVALID) { + return Value(bound.GetString()); + } + return Value::BLOB(const_data_ptr_cast(bound.GetData()), bound.GetSize()); +} + +child_list_t StringStats::ToStruct(const BaseStatistics &stats, bool exact) { child_list_t result; auto &string_data = GetDataUnsafe(stats); if (HasMinMax(stats)) { - result.emplace_back("min", Blob::ToString(string_data.min)); - result.emplace_back("max", Blob::ToString(string_data.max)); + if (exact) { + result.emplace_back("min", StringStatsBoundValue(stats.GetType(), string_data.min)); + result.emplace_back("max", StringStatsBoundValue(stats.GetType(), string_data.max)); + } else { + result.emplace_back("min", Blob::ToString(string_data.min)); + result.emplace_back("max", Blob::ToString(string_data.max)); + } } result.emplace_back("has_unicode", Value::BOOLEAN(string_data.has_unicode)); if (string_data.HasMinStringLength()) { @@ -829,6 +845,50 @@ child_list_t StringStats::ToStruct(const BaseStatistics &stats) { return result; } +//! The bytes of a bound: a BLOB or VARCHAR value holds them as they are, any other value is cast to text +static bool TryGetStringBound(StatsStructFields &fields, const string &name, string &result) { + auto field = fields.Get(name); + if (!field) { + return false; + } + auto plain = StatsStructFields::Plain(*field); + if (plain.type().id() == LogicalTypeId::BLOB || plain.type().id() == LogicalTypeId::VARCHAR) { + result = StringValue::Get(plain); + return true; + } + Value text; + fields.TryGet(name, LogicalType::VARCHAR, text); + result = StringValue::Get(text); + return true; +} + +void StringStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + auto &string_data = GetDataUnsafe(stats); + Value field; + string bound; + // a bound may be a truncated prefix, as a file format stores them + if (TryGetStringBound(fields, "min", bound)) { + SetMin(stats, string_t(bound), StringStatsType::TRUNCATED_STATS); + } + if (TryGetStringBound(fields, "max", bound)) { + SetMax(stats, string_t(bound), StringStatsType::TRUNCATED_STATS); + } + if (fields.TryGet("has_unicode", LogicalType::BOOLEAN, field)) { + string_data.has_unicode = BooleanValue::Get(field); + } + if (fields.TryGet("min_string_length", LogicalType::UINTEGER, field)) { + string_data.has_min_string_length = true; + string_data.min_string_length = UIntegerValue::Get(field); + } + if (fields.TryGet("max_string_length", LogicalType::UINTEGER, field)) { + SetMaxStringLength(stats, UIntegerValue::Get(field)); + } + if (fields.TryGet("total_string_length", LogicalType::UBIGINT, field)) { + string_data.has_total_string_length = true; + string_data.total_string_length = UBigIntValue::Get(field); + } +} + void StringStats::Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count) { auto &string_data = GetDataUnsafe(stats); diff --git a/src/duckdb/src/storage/statistics/struct_stats.cpp b/src/duckdb/src/storage/statistics/struct_stats.cpp index dd9a26b04..a144b9595 100644 --- a/src/duckdb/src/storage/statistics/struct_stats.cpp +++ b/src/duckdb/src/storage/statistics/struct_stats.cpp @@ -2,6 +2,8 @@ #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" +#include "duckdb/common/string_util.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/serializer/serializer.hpp" @@ -119,17 +121,68 @@ void StructStats::Deserialize(Deserializer &deserializer, BaseStatistics &base) }); } -child_list_t StructStats::ToStruct(const BaseStatistics &stats) { +child_list_t StructStats::ToStruct(const BaseStatistics &stats, bool exact) { child_list_t result; child_list_t child_info; auto &child_types = StructType::GetChildTypes(stats.GetType()); for (idx_t i = 0; i < child_types.size(); i++) { - child_info.emplace_back(child_types[i].first, stats.child_stats[i].ToStruct()); + child_info.emplace_back(child_types[i].first, stats.child_stats[i].ToStruct(exact)); } result.emplace_back("child_stats", Value::STRUCT(std::move(child_info))); return result; } +//! The children of a TUPLE's `child_stats` are positional: a TUPLE as ToStruct renders it, or a LIST as stats() does +static void SetTupleChildrenFromValue(BaseStatistics &stats, const Value &children, StatsStructFields &fields) { + auto plain = StatsStructFields::Plain(children); + optional_ptr> values; + switch (plain.type().id()) { + case LogicalTypeId::TUPLE: + values = StructValue::GetChildren(plain); + break; + case LogicalTypeId::LIST: + values = ListValue::GetChildren(plain); + break; + default: + fields.Throw("child_stats", StringUtil::Format("expected a tuple of statistics, got a value of type %s", + plain.type().ToString())); + } + auto count = StructType::GetChildCount(stats.GetType()); + if (values->size() != count) { + fields.Throw("child_stats", + StringUtil::Format("expected the statistics of %llu elements, got %llu", count, values->size())); + } + auto path = fields.FieldPath("child_stats"); + for (idx_t i = 0; i < count; i++) { + auto &child = (*values)[i]; + if (child.IsNull()) { + continue; + } + StructStats::GetChildStats(stats, i).SetFromStruct(child, path + "." + TupleType::GetChildName(i)); + } +} + +void StructStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + auto children = fields.Get("child_stats"); + if (!children) { + return; + } + if (stats.GetType().id() == LogicalTypeId::TUPLE) { + SetTupleChildrenFromValue(stats, *children, fields); + return; + } + StatsStructFields child_fields(*children, fields.FieldPath("child_stats")); + auto &child_types = StructType::GetChildTypes(stats.GetType()); + for (idx_t i = 0; i < child_types.size(); i++) { + auto &name = child_types[i].first.GetIdentifierName(); + auto child = child_fields.Get(name); + if (child) { + stats.child_stats[i].SetFromStruct(*child, child_fields.FieldPath(name)); + } + } + child_fields.VerifyAllRead(stats.GetType()); +} + void StructStats::Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count) { const auto &child_entries = StructVector::GetEntries(vector); for (idx_t i = 0; i < child_entries.size(); i++) { diff --git a/src/duckdb/src/storage/statistics/variant_stats.cpp b/src/duckdb/src/storage/statistics/variant_stats.cpp index 166a389fa..b93245035 100644 --- a/src/duckdb/src/storage/statistics/variant_stats.cpp +++ b/src/duckdb/src/storage/statistics/variant_stats.cpp @@ -13,6 +13,8 @@ #include "duckdb/common/types/variant_visitor.hpp" #include "duckdb/function/variant/variant_shredding.hpp" #include "duckdb/function/cast/cast_statistics.hpp" +#include "duckdb/storage/statistics/stats_struct_fields.hpp" +#include "duckdb/common/algorithm.hpp" namespace duckdb { @@ -398,7 +400,7 @@ void VariantStats::Deserialize(Deserializer &deserializer, BaseStatistics &base) } } -static Value GetShreddedStatsStruct(const BaseStatistics &stats, bool fully_shredded) { +static Value GetShreddedStatsStruct(const BaseStatistics &stats, bool fully_shredded, bool exact) { if (VariantShreddedStats::IsFullyShredded(stats) != fully_shredded) { return Value(); } @@ -409,7 +411,7 @@ static Value GetShreddedStatsStruct(const BaseStatistics &stats, bool fully_shre // list auto &child_stats = ListStats::GetChildStats(typed_value); child_list_t result; - auto result_stats = GetShreddedStatsStruct(child_stats, fully_shredded); + auto result_stats = GetShreddedStatsStruct(child_stats, fully_shredded, exact); if (result_stats.IsNull()) { return Value(); } @@ -433,7 +435,7 @@ static Value GetShreddedStatsStruct(const BaseStatistics &stats, bool fully_shre for (idx_t i = 0; i < indices.size(); i++) { auto &child_stats = StructStats::GetChildStats(typed_value, indices[i]); auto &field = fields[indices[i]]; - auto child_stats_entry = GetShreddedStatsStruct(child_stats, fully_shredded); + auto child_stats_entry = GetShreddedStatsStruct(child_stats, fully_shredded, exact); if (child_stats_entry.IsNull()) { continue; } @@ -446,21 +448,21 @@ static Value GetShreddedStatsStruct(const BaseStatistics &stats, bool fully_shre } child_list_t result; result.emplace_back("type", Value(typed_value.GetType().ToString())); - result.emplace_back("stats", typed_value.ToStruct()); + result.emplace_back("stats", typed_value.ToStruct(exact)); return Value::STRUCT(std::move(result)); } -child_list_t VariantStats::ToStruct(const BaseStatistics &stats) { +child_list_t VariantStats::ToStruct(const BaseStatistics &stats, bool exact) { child_list_t result; bool is_shredded = IsShredded(stats); auto &data = GetDataUnsafe(stats); result.emplace_back("shredding_state", Value(EnumUtil::ToString(data.shredding_state))); if (is_shredded) { - auto fully_shredded_stats = GetShreddedStatsStruct(stats.child_stats[1], true); + auto fully_shredded_stats = GetShreddedStatsStruct(stats.child_stats[1], true, exact); if (!fully_shredded_stats.IsNull()) { result.emplace_back("fully_shredded", std::move(fully_shredded_stats)); } - auto partially_shredded_stats = GetShreddedStatsStruct(stats.child_stats[1], false); + auto partially_shredded_stats = GetShreddedStatsStruct(stats.child_stats[1], false, exact); if (!partially_shredded_stats.IsNull()) { result.emplace_back("partially_shredded", std::move(partially_shredded_stats)); } @@ -468,6 +470,208 @@ child_list_t VariantStats::ToStruct(const BaseStatistics &stats) { return result; } +//! What a node of a shredded layout tree (as ToStruct renders it) describes +enum class VariantStatsNodeKind { LEAF, LIST, OBJECT }; + +//! A leaf is {type, stats} with a type name, a list {child_stats}, anything else the fields of an object (whose +//! fields may be named type and stats as well, holding nodes rather than a name) +static VariantStatsNodeKind VariantStatsClassifyNode(const StatsStructFields &fields) { + if (fields.FieldCount() == 1 && fields.FieldName(0) == "child_stats") { + return VariantStatsNodeKind::LIST; + } + if (fields.FieldCount() == 2) { + auto &first = fields.FieldName(0); + auto &second = fields.FieldName(1); + bool type_first = first == "type" && second == "stats"; + bool stats_first = first == "stats" && second == "type"; + if ((type_first || stats_first) && fields.FieldType(type_first ? 0 : 1).id() == LogicalTypeId::VARCHAR) { + return VariantStatsNodeKind::LEAF; + } + } + return VariantStatsNodeKind::OBJECT; +} + +//! The type a shredded leaf holds, from its rendering +static LogicalType VariantStatsLeafType(StatsStructFields &fields) { + Value name; + if (!fields.TryGet("type", LogicalType::VARCHAR, name)) { + fields.Throw("type", "expected the name of the type the values are shredded on"); + } + auto &text = StringValue::Get(name); + LogicalType type; + try { + type = UnboundType::TryParseAndDefaultBind(text); + } catch (std::exception &) { + fields.Throw("type", StringUtil::Format("'%s' is not a type", text)); + } + if (type.id() == LogicalTypeId::INVALID || TypeVisitor::Contains(type, LogicalTypeId::UNBOUND)) { + fields.Throw("type", StringUtil::Format("'%s' is not a type", text)); + } + const bool shreddable = type.id() != LogicalTypeId::UNKNOWN && type.id() != LogicalTypeId::ANY && + type.id() != LogicalTypeId::SQLNULL && type.id() != LogicalTypeId::VARIANT && + type.id() != LogicalTypeId::ENUM; + if (!shreddable) { + fields.Throw("type", StringUtil::Format("'%s' is not a type a VARIANT is shredded on", text)); + } + if (type.IsNested() || type.IsJSONType()) { + fields.Throw("type", StringUtil::Format("'%s' is not a type a VARIANT is shredded on: an object is described " + "by its fields, an array by its 'child_stats'", + text)); + } + return type; +} + +static BaseStatistics VariantStatsBuildNode(optional_ptr fully, + optional_ptr partially); + +//! The statistics of a child node, from the (optional) fully and partially shredded renderings of it +static BaseStatistics VariantStatsBuildChild(optional_ptr fully, + optional_ptr partially, const string &name) { + optional_ptr fully_child; + optional_ptr partially_child; + if (fully) { + fully_child = fully->Get(name); + } + if (partially) { + partially_child = partially->Get(name); + } + if (!fully_child && !partially_child) { + auto &present = fully ? *fully : *partially; + present.Throw(name, "expected the statistics of the shredded values"); + } + unique_ptr fully_fields; + unique_ptr partially_fields; + if (fully_child) { + fully_fields = make_uniq(*fully_child, fully->FieldPath(name)); + } + if (partially_child) { + partially_fields = make_uniq(*partially_child, partially->FieldPath(name)); + } + return VariantStatsBuildNode(fully_fields.get(), partially_fields.get()); +} + +//! Builds the STRUCT(typed_value, untyped_value_index) statistics of a layout node from its renderings: a node in the +//! fully shredded tree has no values in the generic layout (an untyped_value_index of 0 throughout) +static BaseStatistics VariantStatsBuildNode(optional_ptr fully, + optional_ptr partially) { + auto &any = fully ? *fully : *partially; + auto kind = VariantStatsClassifyNode(any); + if (fully && partially && VariantStatsClassifyNode(*partially) != kind) { + partially->Throw("describes another kind of value than the fully shredded statistics"); + } + unique_ptr typed_value; + switch (kind) { + case VariantStatsNodeKind::LEAF: { + if (fully && partially) { + partially->Throw("a shredded value is either fully or partially shredded, not both"); + } + auto type = VariantStatsLeafType(any); + auto stats = any.Get("stats"); + if (!stats) { + any.Throw("stats", "expected the statistics of the shredded values"); + } + typed_value = BaseStatistics::CreateUnknown(type).ToUnique(); + typed_value->SetFromStruct(*stats, any.FieldPath("stats")); + break; + } + case VariantStatsNodeKind::LIST: { + auto child = VariantStatsBuildChild(fully, partially, "child_stats"); + typed_value = BaseStatistics::CreateUnknown(LogicalType::LIST(child.GetType())).ToUnique(); + ListStats::SetChildStats(*typed_value, child.ToUnique()); + break; + } + case VariantStatsNodeKind::OBJECT: { + // the fields of the fully shredded rendering first, then those only the partially shredded one has; a NULL + // field is absent + vector names; + for (auto source : {fully, partially}) { + for (idx_t i = 0; source && i < source->FieldCount(); i++) { + auto &name = source->FieldName(i); + if (source->FieldValue(i) && std::find(names.begin(), names.end(), name) == names.end()) { + names.push_back(name); + } + } + } + if (names.empty()) { + any.Throw("expected a shredded value ({'type', 'stats'}), an array ({'child_stats'}) or the fields of an " + "object"); + } + child_list_t child_types; + vector children; + for (auto &name : names) { + children.push_back(VariantStatsBuildChild(fully, partially, name)); + child_types.emplace_back(name, children.back().GetType()); + } + typed_value = BaseStatistics::CreateUnknown(LogicalType::STRUCT(std::move(child_types))).ToUnique(); + for (idx_t i = 0; i < children.size(); i++) { + StructStats::SetChildStats(*typed_value, i, children[i]); + } + break; + } + } + for (auto source : {fully, partially}) { + if (source) { + source->VerifyAllRead(LogicalType::VARIANT()); + } + } + + child_list_t node_type; + node_type.emplace_back("typed_value", typed_value->GetType()); + node_type.emplace_back("untyped_value_index", LogicalType::UINTEGER); + auto node = BaseStatistics::CreateUnknown(LogicalType::STRUCT(std::move(node_type))); + // the node itself is never NULL: a NULL or missing value is a NULL typed_value + node.Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); + StructStats::SetChildStats(node, VariantStats::TYPED_VALUE_INDEX, *typed_value); + auto untyped_value_index = + fully ? BaseStatistics::FromConstant(Value::UINTEGER(0)) : BaseStatistics::CreateUnknown(LogicalType::UINTEGER); + StructStats::SetChildStats(node, VariantStats::UNTYPED_VALUE_INDEX, untyped_value_index); + return node; +} + +void VariantStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fields) { + auto &data = GetDataUnsafe(stats); + Value state_name; + bool has_state = fields.TryGet("shredding_state", LogicalType::VARCHAR, state_name); + auto state = VariantStatsShreddingState::UNINITIALIZED; + if (has_state) { + try { + state = EnumUtil::FromString(StringValue::Get(state_name).c_str()); + } catch (std::exception &) { + fields.Throw("shredding_state", + StringUtil::Format("'%s' is not a shredding state (UNINITIALIZED, NOT_SHREDDED, SHREDDED or " + "INCONSISTENT)", + StringValue::Get(state_name))); + } + } + + auto fully = fields.Get("fully_shredded"); + auto partially = fields.Get("partially_shredded"); + if (fully || partially) { + if (has_state && state != VariantStatsShreddingState::SHREDDED) { + fields.Throw(fully ? "fully_shredded" : "partially_shredded", + "only SHREDDED statistics describe a shredded layout"); + } + unique_ptr fully_fields; + unique_ptr partially_fields; + if (fully) { + fully_fields = make_uniq(*fully, fields.FieldPath("fully_shredded")); + } + if (partially) { + partially_fields = make_uniq(*partially, fields.FieldPath("partially_shredded")); + } + auto layout = VariantStatsBuildNode(fully_fields.get(), partially_fields.get()); + // the layout replaces the shredding known so far + BaseStatistics::Construct(stats.child_stats[1], layout.GetType()); + stats.child_stats[1].Copy(layout); + data.shredding_state = VariantStatsShreddingState::SHREDDED; + return; + } + // SHREDDED without a layout tells nothing: the shredding known so far stays + if (has_state && state != VariantStatsShreddingState::SHREDDED) { + data.shredding_state = state; + } +} + static BaseStatistics WrapTypedValue(const BaseStatistics &typed_value, optional_ptr untyped_value_index) { if (!untyped_value_index && !typed_value.GetType().IsNested()) { diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index 956a675dd..bb3ddb3d4 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -83,7 +83,7 @@ void StorageOptions::SetEncryptionVersion(string &storage_version_user_provided) encryption_version = target_encryption_version; } -void StorageOptions::Initialize(unordered_map &options) { +void StorageOptions::Initialize(Context &context, unordered_map &options) { string storage_version_user_provided = ""; for (auto &entry : options) { if (entry.first == "block_size") { @@ -99,7 +99,7 @@ void StorageOptions::Initialize(unordered_map &options) { } else if (entry.second.GetValue().empty()) { throw BinderException("Not a valid key. A key cannot be empty"); } - user_key = make_shared_ptr(StringValue::Get(entry.second.DefaultCastAs(LogicalType::BLOB))); + user_key = make_shared_ptr(StringValue::Get(entry.second.CastAs(context, LogicalType::BLOB))); block_header_size = DEFAULT_ENCRYPTION_BLOCK_HEADER_SIZE; encryption = true; } else if (entry.first == "encryption_cipher") { @@ -115,7 +115,7 @@ void StorageOptions::Initialize(unordered_map &options) { storage_version_user_provided = entry.second.ToString(); storage_version = StorageCompatibility::FromString(storage_version_user_provided).storage_version; } else if (entry.first == "compress") { - if (entry.second.DefaultCastAs(LogicalType::BOOLEAN).GetValue()) { + if (entry.second.CastAs(context, LogicalType::BOOLEAN).GetValue()) { compress_in_memory = CompressInMemory::COMPRESS; } else { compress_in_memory = CompressInMemory::DO_NOT_COMPRESS; @@ -163,7 +163,8 @@ StorageManager::StorageManager(AttachedDatabase &db, string path_p, AttachOption auto &fs = FileSystem::Get(db); path = fs.ExpandPath(path); - storage_options.Initialize(options.options); + auto services = db.GetDatabase().Services(); + storage_options.Initialize(*services, options.options); } StorageManager::~StorageManager() { diff --git a/src/duckdb/src/storage/table/list_column_data.cpp b/src/duckdb/src/storage/table/list_column_data.cpp index ffb60ebe4..49b8f7824 100644 --- a/src/duckdb/src/storage/table/list_column_data.cpp +++ b/src/duckdb/src/storage/table/list_column_data.cpp @@ -3,6 +3,9 @@ #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/storage/table/list_column_data.hpp" #include "duckdb/storage/statistics/list_stats.hpp" +#include "duckdb/storage/statistics/array_stats.hpp" +#include "duckdb/storage/statistics/struct_stats.hpp" +#include "duckdb/storage/table/struct_column_data.hpp" #include "duckdb/storage/storage_info.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" @@ -504,19 +507,44 @@ bool ListColumnData::HasAnyChanges() const { return ColumnData::HasAnyChanges() || validity->HasAnyChanges() || child_column->HasAnyChanges(); } -optional_ptr ListColumnData::GetColumnStatistics() const { - if (stats) { - return stats->statistics; +//! Resolves the statistics of a column from the statistics of its root column +//! A nested column can hold its own statistics (e.g. when it was created by a checkpoint), but those are not updated: +//! the statistics of nested columns are tracked in the statistics of the root column +static optional_ptr ResolveColumnStatistics(const ColumnData &column) { + if (!column.HasParent()) { + return column.GetStatisticsRef(); + } + auto &parent = column.Parent(); + auto parent_stats = ResolveColumnStatistics(parent); + if (!parent_stats) { + return nullptr; } - if (!HasParent()) { + switch (parent.GetType().id()) { + case LogicalTypeId::LIST: + case LogicalTypeId::MAP: + return ListStats::GetChildStats(*parent_stats); + case LogicalTypeId::ARRAY: + return ArrayStats::GetChildStats(*parent_stats); + case LogicalTypeId::STRUCT: + case LogicalTypeId::TUPLE: + case LogicalTypeId::UNION: { + auto &struct_data = parent.Cast(); + auto child_count = StructType::GetChildCount(parent.GetType()); + for (idx_t i = 0; i < child_count; i++) { + if (RefersToSameObject(struct_data.GetChildColumn(i), column)) { + return StructStats::GetChildStats(*parent_stats, i); + } + } return nullptr; } - // the statistics of the children of these columns are not tracked in their parent - auto parent_type = Parent().GetType().id(); - if (parent_type == LogicalTypeId::VARIANT || parent_type == LogicalTypeId::GEOMETRY) { + default: + // the statistics of the children of other columns (e.g. VARIANT, GEOMETRY) are not tracked in their parent return nullptr; } - return GetStatisticsRef(); +} + +optional_ptr ListColumnData::GetColumnStatistics() const { + return ResolveColumnStatistics(*this); } bool ListPersistentColumnData::IsSupported(const Serializer &serializer) const { diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index 01842616d..d9880aa76 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -119,6 +119,13 @@ void StandardColumnData::Select(TransactionData transaction, idx_t vector_index, ColumnData::Select(transaction, vector_index, state, result, sel, sel_count); return; } + // a scan references uncompressed data without copying it: slicing beats gathering unless few rows are selected + static constexpr idx_t UNCOMPRESSED_SELECT_DENSITY = 5; + if (compression->type == CompressionType::COMPRESSION_UNCOMPRESSED && + sel_count * UNCOMPRESSED_SELECT_DENSITY > target_count) { + ColumnData::Select(transaction, vector_index, state, result, sel, sel_count); + return; + } SelectVector(state, result, target_count, sel, sel_count, scan_type); validity->SelectVector(state.child_states[0], result, target_count, sel, sel_count, scan_type); } diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index ef0c6c90d..cd8b94b34 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -977,7 +977,19 @@ void WriteAheadLogDeserializer::ReplayIndexData(IndexStorageInfo &info) { void WriteAheadLogDeserializer::ReplayAlter() { auto info = deserializer.ReadProperty>(101, "info"); + if (!info || info->info_type != ParseInfoType::ALTER_INFO) { + throw DataCorruptionException("Corrupt WAL file: alter entry does not carry alter information"); + } auto &alter_info = info->Cast(); + // IsAddUniqueConstraint() below dereferences the constraint of an ADD_CONSTRAINT entry, so it must be present + if (alter_info.type == AlterType::ALTER_TABLE) { + auto &table_info = alter_info.Cast(); + if (table_info.alter_table_type == AlterTableType::ADD_CONSTRAINT) { + if (!table_info.Cast().constraint) { + throw DataCorruptionException("Corrupt WAL file: add constraint entry is missing its constraint"); + } + } + } alter_info.bind_mode = AlterBindMode::SKIP_BINDING; if (!alter_info.IsAddUniqueConstraint()) { return ReplayWithoutIndex(context, catalog, alter_info, DeserializeOnly()); diff --git a/src/duckdb/ub_src_optimizer_compressed_materialization.cpp b/src/duckdb/ub_src_optimizer_compressed_materialization.cpp index 880ae8986..183ef6cc6 100644 --- a/src/duckdb/ub_src_optimizer_compressed_materialization.cpp +++ b/src/duckdb/ub_src_optimizer_compressed_materialization.cpp @@ -2,7 +2,5 @@ #include "src/optimizer/compressed_materialization/compress_comparison_join.cpp" -#include "src/optimizer/compressed_materialization/compress_distinct.cpp" - #include "src/optimizer/compressed_materialization/compress_order.cpp" diff --git a/src/duckdb/ub_src_optimizer_pushdown.cpp b/src/duckdb/ub_src_optimizer_pushdown.cpp index be80f512f..bb641e2aa 100644 --- a/src/duckdb/ub_src_optimizer_pushdown.cpp +++ b/src/duckdb/ub_src_optimizer_pushdown.cpp @@ -2,8 +2,6 @@ #include "src/optimizer/pushdown/pushdown_cross_product.cpp" -#include "src/optimizer/pushdown/pushdown_distinct.cpp" - #include "src/optimizer/pushdown/pushdown_filter.cpp" #include "src/optimizer/pushdown/pushdown_get.cpp" diff --git a/src/duckdb/ub_src_storage_statistics.cpp b/src/duckdb/ub_src_storage_statistics.cpp index 07cb6874f..4af74db3d 100644 --- a/src/duckdb/ub_src_storage_statistics.cpp +++ b/src/duckdb/ub_src_storage_statistics.cpp @@ -14,6 +14,8 @@ #include "src/storage/statistics/segment_statistics.cpp" +#include "src/storage/statistics/stats_struct_fields.cpp" + #include "src/storage/statistics/string_stats.cpp" #include "src/storage/statistics/struct_stats.cpp"