From 5cf1e46e5fa1c9644c7eee2fd611c18cb9406459 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Thu, 12 Nov 2026 03:05:07 +0000 Subject: [PATCH] Update vendored DuckDB sources to 331f91a84f8 --- .../aggregate/nested/binned_histogram.cpp | 22 +- .../core_functions/scalar/list/list_sort.cpp | 18 +- .../core_functions/scalar/math/numeric.cpp | 2 +- .../core_functions/scalar/string/hex.cpp | 56 ++- src/duckdb/extension/icu/icu-dateadd.cpp | 68 ++- .../json_functions/json_serialize_sql.cpp | 6 + .../json/json_functions/json_transform.cpp | 3 +- src/duckdb/extension/json/json_reader.cpp | 32 +- .../decoder/delta_byte_array_decoder.cpp | 9 +- .../include/writer/enum_column_writer.hpp | 3 +- .../extension/parquet/parquet_crypto.cpp | 34 +- .../extension/parquet/parquet_int96.cpp | 2 + .../extension/parquet/parquet_timestamp.cpp | 33 +- .../parquet/writer/enum_column_writer.cpp | 41 +- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/common/bignum.cpp | 2 +- src/duckdb/src/common/types.cpp | 1 + src/duckdb/src/common/types/hugeint.cpp | 68 +-- src/duckdb/src/common/types/interval.cpp | 22 + src/duckdb/src/common/types/time.cpp | 78 ++-- src/duckdb/src/common/types/uhugeint.cpp | 41 +- .../variant/parquet_variant_encoding.cpp | 442 ++++++++++-------- .../common/vector_operations/vector_hash.cpp | 24 +- .../scanner/string_value_scanner.cpp | 8 +- .../physical_plan/plan_create_table.cpp | 5 +- src/duckdb/src/function/cast/bignum_casts.cpp | 2 + src/duckdb/src/function/function_binder.cpp | 8 +- .../function/scalar/comparison/between.cpp | 13 +- .../src/function/scalar/operator/add.cpp | 63 +++ .../function/scalar/operator/arithmetic.cpp | 105 ++++- .../scalar/operator/decimal_division.cpp | 119 +++-- .../src/function/scalar/operator/subtract.cpp | 15 + .../src/function/scalar/strftime_format.cpp | 12 + .../table/system/system_catalog_scanner.cpp | 7 +- .../function/table/version/pragma_version.cpp | 6 +- .../common/multi_file/multi_file_function.hpp | 47 +- .../include/duckdb/common/operator/add.hpp | 26 +- .../duckdb/common/operator/subtract.hpp | 6 + .../serializer/deserialization_policy.hpp | 46 ++ .../duckdb/common/serializer/deserializer.hpp | 18 + .../include/duckdb/common/types/interval.hpp | 11 + .../include/duckdb/common/types/uhugeint.hpp | 2 + .../function/table/system_catalog_scanner.hpp | 4 +- .../main/extension_repository_manager.hpp | 2 + .../duckdb/main/http/http_retry_budget.hpp | 6 + .../include/duckdb/main/http/http_util.hpp | 4 + .../duckdb/main/secret/secret_storage.hpp | 2 + .../src/include/duckdb/main/settings.hpp | 28 ++ .../duckdb/optimizer/filter_pushdown.hpp | 2 + .../parser/peg/ast/expression_chain.hpp | 15 + .../duckdb/parser/peg/inlined_grammar.hpp | 15 +- .../include/duckdb/parser/peg/peg_rule_id.hpp | 8 +- .../peg/transformer/peg_transformer.hpp | 39 +- .../duckdb/planner/column_qualifier.hpp | 4 + .../expression/bound_between_expression.hpp | 12 +- .../planner/logical_operator_visitor.hpp | 4 +- .../subquery/flatten_dependent_join.hpp | 2 + src/duckdb/src/main/capi/v1/cast/utils-c.cpp | 4 + src/duckdb/src/main/capi/v1/result-c.cpp | 4 + src/duckdb/src/main/config.cpp | 2 + .../src/main/extension/extension_helper.cpp | 4 +- .../extension/extension_install_dynamic.cpp | 13 +- .../extension_repository_manager.cpp | 11 + .../src/main/http/http_retry_budget.cpp | 28 +- src/duckdb/src/main/http/http_util.cpp | 7 + src/duckdb/src/main/secret/secret_storage.cpp | 63 +-- src/duckdb/src/optimizer/filter_pushdown.cpp | 24 +- src/duckdb/src/optimizer/join_elimination.cpp | 3 + .../pushdown/pushdown_inner_join.cpp | 7 + .../optimizer/pushdown/pushdown_left_join.cpp | 4 +- .../optimizer/pushdown/pushdown_mark_join.cpp | 4 +- .../pushdown/pushdown_outer_join.cpp | 4 +- .../pushdown/pushdown_semi_anti_join.cpp | 4 +- .../pushdown/pushdown_single_join.cpp | 4 +- .../struct_extract_struct_pack_folding.cpp | 5 +- .../src/optimizer/topn_window_elimination.cpp | 8 + src/duckdb/src/parallel/executor.cpp | 5 + src/duckdb/src/parallel/scan_read_ahead.cpp | 4 + .../parser/expression/window_expression.cpp | 29 +- src/duckdb/src/parser/peg/peg_rule_id.cpp | 8 +- .../transformer/peg_transformer_factory.cpp | 3 +- .../peg/transformer/transform_expression.cpp | 79 +++- .../transform_generated_trampoline.cpp | 215 ++++++--- .../peg/transformer/transform_select.cpp | 58 ++- .../parser/query_node/insert_query_node.cpp | 20 +- .../parser/query_node/merge_query_node.cpp | 2 +- .../src/parser/tableref/delimgetref.cpp | 4 +- .../src/parser/tableref/emptytableref.cpp | 4 +- src/duckdb/src/parser/tableref/joinref.cpp | 2 +- src/duckdb/src/parser/tableref/pivotref.cpp | 2 +- .../expression/bind_aggregate_expression.cpp | 9 + .../expression/bind_function_expression.cpp | 2 +- .../planner/binder/expression/bind_lambda.cpp | 28 -- .../binder/query_node/plan_select_node.cpp | 4 + src/duckdb/src/planner/column_qualifier.cpp | 41 +- .../expression/bound_cast_expression.cpp | 5 +- .../expression/bound_constant_expression.cpp | 23 +- .../src/planner/sql_export/sql_export_dml.cpp | 5 + .../subquery/flatten_dependent_join.cpp | 33 ++ .../src/storage/metadata/metadata_manager.cpp | 4 +- .../storage/serialization/serialize_nodes.cpp | 1 + src/duckdb/src/storage/storage_manager.cpp | 4 - .../src/storage/table/row_id_column_data.cpp | 4 +- src/duckdb/src/storage/wal_replay.cpp | 69 ++- .../third_party/fmt/include/fmt/format-inl.h | 2 +- src/duckdb/third_party/jemalloc/src/pages.c | 2 + src/duckdb/third_party/utf8proc/utf8proc.cpp | 2 +- 107 files changed, 1786 insertions(+), 771 deletions(-) create mode 100644 src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp diff --git a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp index 3158a924a..078ea887c 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp @@ -318,7 +318,16 @@ void HistogramBinFinalizeFunction(Vector &state_vector, AggregateFinalizeInputDa if (state.counts->back() > 0 && supports_other_bucket) { // add overflow bucket ("others") // set bin boundary to NULL for overflow bucket - keys.SetValue(current_offset, OtherBucketValue(keys.GetType())); + auto other_value = OtherBucketValue(keys.GetType()); + for (idx_t bin_idx = list_entry.offset; bin_idx < current_offset; bin_idx++) { + if (Value::NotDistinctFrom(keys.GetValue(bin_idx), other_value)) { + throw InvalidInputException( + "Histogram bin %s collides with the key of the \"other values\" bucket, " + "which has entries - use a different bin value", + other_value.ToSQLString()); + } + } + keys.SetValue(current_offset, other_value); count_entries[current_offset] = state.counts->back(); current_offset++; } @@ -392,7 +401,8 @@ unique_ptr HistogramBinBindFunction(BindAggregateFunctionInput &in } } - function.ReplaceImplementation(GetHistogramBinFunction(arguments[0]->GetReturnType())); + // the template signature resolved both parameters to the deduced bin type + function.ReplaceImplementation(GetHistogramBinFunction(function.GetArguments()[0])); return nullptr; } @@ -402,8 +412,8 @@ AggregateFunction HistogramFun::BinnedHistogramFunction() { AggregateFunction function("histogram", {}, LogicalTypeId::MAP, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, HistogramBinBindFunction, nullptr); function.GetSignature() - .AddParameter("arg", LogicalType::ANY) - .AddParameter("bins", LogicalType::LIST(LogicalType::ANY)); + .AddParameter("arg", LogicalType::TEMPLATE("T")) + .AddParameter("bins", LogicalType::LIST(LogicalType::TEMPLATE("T"))); return function; } @@ -411,8 +421,8 @@ AggregateFunction HistogramExactFun::GetFunction() { AggregateFunction function("histogram_exact", {}, LogicalTypeId::MAP, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, HistogramBinBindFunction, nullptr); function.GetSignature() - .AddParameter("arg", LogicalType::ANY) - .AddParameter("bins", LogicalType::LIST(LogicalType::ANY)); + .AddParameter("arg", LogicalType::TEMPLATE("T")) + .AddParameter("bins", LogicalType::LIST(LogicalType::TEMPLATE("T"))); return function; } diff --git a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp index 717a4ea57..6313dac67 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp @@ -318,20 +318,11 @@ static void ListSortFunction(DataChunk &args, ExpressionState &state, Vector &re static unique_ptr ListSortBind(ClientContext &context, BoundScalarFunction &bound_function, vector> &arguments, OrderType &order, OrderByNullType &null_order) { - LogicalType child_type; - if (arguments[0]->GetReturnType() == LogicalTypeId::UNKNOWN) { - bound_function.GetArguments()[0] = LogicalTypeId::UNKNOWN; - bound_function.SetReturnType(LogicalType::SQLNULL); - child_type = bound_function.GetReturnType(); - return make_uniq(order, null_order, false, bound_function.GetReturnType(), child_type, - context); - } - arguments[0] = BoundCastExpression::AddArrayCastToList(context, std::move(arguments[0])); if (arguments[0]->GetReturnType().id() != LogicalTypeId::LIST) { throw BinderException("list_sort can only operate on LISTs"); } - child_type = ListType::GetChildType(arguments[0]->GetReturnType()); + auto child_type = ListType::GetChildType(arguments[0]->GetReturnType()); bound_function.GetArguments()[0] = arguments[0]->GetReturnType(); bound_function.SetReturnType(arguments[0]->GetReturnType()); @@ -365,13 +356,6 @@ static unique_ptr ListGradeUpBind(BindScalarFunctionInput &input) order = config.ResolveOrder(context, order); null_order = config.ResolveNullOrder(context, order, null_order); - if (arguments[0]->GetReturnType().id() == LogicalTypeId::UNKNOWN) { - bound_function.GetArguments()[0] = LogicalTypeId::UNKNOWN; - bound_function.SetReturnType(LogicalType::SQLNULL); - return make_uniq(order, null_order, true, bound_function.GetReturnType(), - bound_function.GetReturnType(), context); - } - arguments[0] = BoundCastExpression::AddArrayCastToList(context, std::move(arguments[0])); if (arguments[0]->GetReturnType().id() != LogicalTypeId::LIST) { throw BinderException("list_grade_up can only operate on LISTs"); diff --git a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp index 6dc14b993..623aaac10 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); diff --git a/src/duckdb/extension/core_functions/scalar/string/hex.cpp b/src/duckdb/extension/core_functions/scalar/string/hex.cpp index d5c51cab3..cfad8ba69 100644 --- a/src/duckdb/extension/core_functions/scalar/string/hex.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/hex.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/bignum.hpp" #include "duckdb/common/bit_utils.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -64,6 +65,43 @@ static void WriteHugeIntBinBytes(T x, char *&output, idx_t buffer_size) { } } +//! A BIGNUM has no fixed width, so a negative value prints as a sign and its magnitude rather than two's complement. +template +static string_t WriteBignumDigits(const bignum_t &input, StringHeap &heap) { + constexpr uint8_t DIGITS_PER_BYTE = 8 / BITS_PER_DIGIT; + constexpr uint8_t DIGIT_MASK = (1 << BITS_PER_DIGIT) - 1; + + const BignumIntermediate value(input); + const idx_t start = value.GetStartDataPos(); + if (start == value.size) { + auto target = heap.EmptyString(1); + *target.GetDataWriteable() = '0'; + target.Finalize(); + return target; + } + + idx_t leading_bits = 32 - CountZeros::Leading(value.GetAbsoluteByte(NumericCast(start))); + idx_t leading_digits = (leading_bits + BITS_PER_DIGIT - 1) / BITS_PER_DIGIT; + idx_t result_size = (value.is_negative ? 1 : 0) + leading_digits + (value.size - start - 1) * DIGITS_PER_BYTE; + + auto target = heap.EmptyString(result_size); + auto output = target.GetDataWriteable(); + if (value.is_negative) { + *output++ = '-'; + } + for (idx_t i = start; i < value.size; i++) { + auto byte = value.GetAbsoluteByte(NumericCast(i)); + idx_t digits = i == start ? leading_digits : DIGITS_PER_BYTE; + for (idx_t d = digits; d >= 1; d--) { + auto digit = static_cast((byte >> ((d - 1) * BITS_PER_DIGIT)) & DIGIT_MASK); + *output++ = Blob::HEX_TABLE[digit]; + } + } + + target.Finalize(); + return target; +} + struct HexStrOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { @@ -167,6 +205,13 @@ struct HexUhugeIntOperator { } }; +struct HexBignumOperator { + template + static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { + return WriteBignumDigits<4>(input, heap); + } +}; + template static void ToHexFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 1); @@ -276,6 +321,13 @@ struct BinaryUhugeIntOperator { } }; +struct BinaryBignumOperator { + template + static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { + return WriteBignumDigits<1>(input, heap); + } +}; + struct FromHexOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) { @@ -389,7 +441,7 @@ ScalarFunctionSet HexFun::GetFunctions() { AddHexParam(string_fun, LogicalType::VARCHAR, "string"); to_hex.AddFunction(string_fun); - ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToHexFunction); + ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToHexFunction); AddHexParam(bignum_fun, LogicalType::BIGNUM, "value"); to_hex.AddFunction(bignum_fun); @@ -430,7 +482,7 @@ ScalarFunctionSet BinFun::GetFunctions() { AddHexParam(string_fun, LogicalType::VARCHAR, "string"); to_binary.AddFunction(string_fun); - ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToBinaryFunction); + ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToBinaryFunction); AddHexParam(bignum_fun, LogicalType::BIGNUM, "value"); to_binary.AddFunction(bignum_fun); diff --git a/src/duckdb/extension/icu/icu-dateadd.cpp b/src/duckdb/extension/icu/icu-dateadd.cpp index 0085d1c20..9a697edab 100644 --- a/src/duckdb/extension/icu/icu-dateadd.cpp +++ b/src/duckdb/extension/icu/icu-dateadd.cpp @@ -125,12 +125,39 @@ timestamp_tz_t ICUCalendarAdd::Operation(interval_t interval, timestamp_tz_t tim return Operation(timestamp, interval, calendar); } +template <> +timestamp_tz_ns_t ICUCalendarAdd::Operation(timestamp_tz_ns_t ns, interval_t interval, TZCalendar &calendar) { + if (!ns.IsFinite()) { + return ns; + } + timestamp_tz_t us; + int64_t nanos; + const auto precision = ns.PRECISION / us.PRECISION; + Timestamp::SplitTime(ns.value, precision, us.value, nanos); + us = Operation(us, interval, calendar); + if (!Timestamp::TryCombineUnits(us.value, nanos, precision, ns.value)) { + throw OutOfRangeException("Cannot add interval to timestamp_tz_ns"); + } + return ns; +} + +template <> +timestamp_tz_ns_t ICUCalendarAdd::Operation(interval_t interval, timestamp_tz_ns_t timestamp, TZCalendar &calendar) { + return Operation(timestamp, interval, calendar); +} + template <> timestamp_tz_t ICUCalendarSub::Operation(timestamp_tz_t timestamp, interval_t interval, TZCalendar &calendar) { const auto negated = Interval::Invert(interval); return ICUCalendarAdd::template Operation(timestamp, negated, calendar); } +template <> +timestamp_tz_ns_t ICUCalendarSub::Operation(timestamp_tz_ns_t ns, interval_t interval, TZCalendar &calendar) { + const auto negated = Interval::Invert(interval); + return ICUCalendarAdd::template Operation(ns, negated, calendar); +} + template <> interval_t ICUCalendarSub::Operation(timestamp_tz_t end_date, timestamp_tz_t start_date, TZCalendar &calendar_p) { if (!end_date.IsFinite() || !start_date.IsFinite()) { @@ -249,24 +276,33 @@ struct ICUDateAdd : public ICUDateFunc { ICUBindIntervalMonths); } - template - static ScalarFunction GetDateAddFunction(const LogicalTypeId &left_type, const LogicalTypeId &right_type) { - return GetBinaryDateFunction(left_type, right_type, LogicalType::TIMESTAMP_TZ); + template + static ScalarFunction GetDateAddFunction(const LogicalTypeId &left_type, const LogicalTypeId &right_type, + const LogicalTypeId &result_type) { + return GetBinaryDateFunction(left_type, right_type, result_type); } - static void AddDateAddOperators(const Identifier &name, ExtensionLoader &loader) { + template + static void AddDateAddFunctions(ScalarFunctionSet &set, const LogicalTypeId &type) { // temporal + interval - ScalarFunctionSet set {name}; - auto tstz_interval_fun = GetDateAddFunction( - LogicalType::TIMESTAMP_TZ, LogicalType::INTERVAL); + auto tstz_interval_fun = + GetDateAddFunction(type, LogicalType::INTERVAL, type); tstz_interval_fun.GetSignature().GetParameter(0).SetName("left"); tstz_interval_fun.GetSignature().GetParameter(1).SetName("right"); set.AddFunction(tstz_interval_fun); - auto interval_tstz_fun = GetDateAddFunction( - LogicalType::INTERVAL, LogicalType::TIMESTAMP_TZ); + + // interval + temporal + auto interval_tstz_fun = + GetDateAddFunction(LogicalType::INTERVAL, type, type); interval_tstz_fun.GetSignature().GetParameter(0).SetName("left"); interval_tstz_fun.GetSignature().GetParameter(1).SetName("right"); set.AddFunction(interval_tstz_fun); + } + + static void AddDateAddOperators(const Identifier &name, ExtensionLoader &loader) { + ScalarFunctionSet set {name}; + AddDateAddFunctions(set, LogicalType::TIMESTAMP_TZ); + AddDateAddFunctions(set, LogicalType::TIMESTAMP_TZ_NS); // throws for dates that overflow the timestamp range set.SetFallible(); set.SetStability(FunctionStability::CONSISTENT_WITHIN_QUERY); @@ -283,14 +319,20 @@ struct ICUDateAdd : public ICUDateFunc { return GetBinaryDateFunction(left_type, right_type, LogicalType::INTERVAL); } - static void AddDateSubOperators(const Identifier &name, ExtensionLoader &loader) { + template + static void AddDateSubFunction(ScalarFunctionSet &set, const LogicalTypeId &type) { // temporal - interval - ScalarFunctionSet set {name}; - auto tstz_interval_fun = GetDateAddFunction( - LogicalType::TIMESTAMP_TZ, LogicalType::INTERVAL); + auto tstz_interval_fun = + GetDateAddFunction(type, LogicalType::INTERVAL, type); tstz_interval_fun.GetSignature().GetParameter(0).SetName("left"); tstz_interval_fun.GetSignature().GetParameter(1).SetName("right"); set.AddFunction(tstz_interval_fun); + } + + static void AddDateSubOperators(const Identifier &name, ExtensionLoader &loader) { + ScalarFunctionSet set {name}; + AddDateSubFunction(set, LogicalType::TIMESTAMP_TZ); + AddDateSubFunction(set, LogicalType::TIMESTAMP_TZ_NS); // temporal - temporal auto tstz_tstz_fun = GetBinaryAgeFunction( diff --git a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp index eab0ce04b..b608f1bbc 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp @@ -8,6 +8,7 @@ #include "json_functions.hpp" #include "json_serializer.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/literal.hpp" namespace duckdb { @@ -194,6 +195,10 @@ static vector> DeserializeSelectStatement(string_t i throw ParserException("Error parsing json: no statements"); } + DeserializationPolicy policy; + policy.Disallow(LogicalTypeId::POINTER); + policy.Disallow(LiteralKind::POINTER); + vector> result; idx_t idx; @@ -201,6 +206,7 @@ static vector> DeserializeSelectStatement(string_t i yyjson_val *stmt_json; yyjson_arr_foreach(statements, idx, max, stmt_json) { JsonDeserializer deserializer(stmt_json, doc); + deserializer.SetPolicy(policy); auto stmt = SelectStatement::Deserialize(deserializer); if (!stmt->node) { throw ParserException("Error parsing json: no select node found in json"); diff --git a/src/duckdb/extension/json/json_functions/json_transform.cpp b/src/duckdb/extension/json/json_functions/json_transform.cpp index b4b35c76f..9466fcbc8 100644 --- a/src/duckdb/extension/json/json_functions/json_transform.cpp +++ b/src/duckdb/extension/json/json_functions/json_transform.cpp @@ -984,8 +984,7 @@ static bool TransformObjectToMap(yyjson_val *objects[], yyjson_alc *alc, Vector // Transform keys if (!JSONTransform::Transform(keys, alc, MapVector::GetKeys(result), list_size, options, nullptr)) { - throw ConversionException( - StringUtil::Format("%s. Cannot default to NULL, because map keys cannot be NULL", options.error_message)); + success = false; } // Transform values diff --git a/src/duckdb/extension/json/json_reader.cpp b/src/duckdb/extension/json/json_reader.cpp index 70a967e0c..def1a669e 100644 --- a/src/duckdb/extension/json/json_reader.cpp +++ b/src/duckdb/extension/json/json_reader.cpp @@ -107,7 +107,7 @@ bool JSONFileHandle::GetPositionAndSize(idx_t &position, idx_t &size, idx_t requ read_position += size; requested_reads++; - if (size == 0) { + if (Remaining() == 0) { last_read_requested = true; } @@ -1145,18 +1145,16 @@ void JSONReader::FinalizeBuffer(JSONReaderScanState &scan_state) { } // we read something - // skip over the array start if required - if (!scan_state.is_last) { - if (scan_state.buffer_index.GetIndex() == 0) { - // the file starts at the buffer offset, which leaves room for the end of a previous buffer when the file - // is read in parallel - idx_t bom_size = 0; - StringUtil::SkipBOM(scan_state.buffer_ptr + scan_state.buffer_offset, - scan_state.buffer_size - scan_state.buffer_offset, bom_size); - scan_state.buffer_offset += bom_size; - if (GetFormat() == JSONFormat::ARRAY) { - SkipOverArrayStart(scan_state); - } + // skip over the BOM and the array start if required + if (scan_state.buffer_index.GetIndex() == 0 && scan_state.buffer_size >= scan_state.buffer_offset) { + // the file starts at the buffer offset, which leaves room for the end of a previous buffer when the file + // is read in parallel + idx_t bom_size = 0; + StringUtil::SkipBOM(scan_state.buffer_ptr + scan_state.buffer_offset, + scan_state.buffer_size - scan_state.buffer_offset, bom_size); + scan_state.buffer_offset += bom_size; + if (GetFormat() == JSONFormat::ARRAY) { + SkipOverArrayStart(scan_state); } } // then finalize the buffer @@ -1280,19 +1278,19 @@ bool JSONReader::PrepareBufferForRead(JSONReaderScanState &scan_state) { bool JSONReader::PrepareBufferSeek(JSONReaderScanState &scan_state) { scan_state.request_size = scan_state.buffer_capacity / 2 - scan_state.prev_buffer_remainder - YYJSON_PADDING_SIZE; - if (!IsOpen()) { + if (!HasFileHandle()) { return false; } auto &file_handle = GetFileHandle(); - - if (file_handle.LastReadRequested()) { + // the last read may close the handle concurrently, so check this before IsOpen() + if (file_handle.LastReadRequested() || !IsOpen()) { return false; } if (!file_handle.GetPositionAndSize(scan_state.read_position, scan_state.read_size, scan_state.request_size)) { return false; // We weren't able to read } scan_state.buffer_index = GetBufferIndex(); - scan_state.is_last = scan_state.read_size == 0; + scan_state.is_last = file_handle.LastReadRequested(); scan_state.needs_to_read = true; scan_state.buffer_size = 0; return true; diff --git a/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp b/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp index 5b4028a59..4dc20134e 100644 --- a/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/delta_byte_array_decoder.cpp @@ -115,12 +115,13 @@ void DeltaByteArrayDecoder::InitializePage() { output += sizeof(uint32_t); } - memcpy(output, prev_value.data(), prefix_len); block.available(suffix_len); - memcpy(output + prefix_len, block.ptr, suffix_len); + if (value_len > 0) { + memcpy(output, prev_value.data(), prefix_len); + memcpy(output + prefix_len, block.ptr, suffix_len); + memcpy(prev_value.data(), output, value_len); + } block.inc(suffix_len); - - memcpy(prev_value.data(), output, value_len); prev_len = value_len; output += value_len; } diff --git a/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp b/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp index 884e7b40b..6e732fe38 100644 --- a/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp +++ b/src/duckdb/extension/parquet/include/writer/enum_column_writer.hpp @@ -32,6 +32,7 @@ class EnumColumnWriter : public PrimitiveColumnWriter { EnumColumnWriter(ParquetWriter &writer, ParquetColumnSchema &&column_schema, vector schema_path_p); ~EnumColumnWriter() override = default; + unique_ptr InitializeWriteState(duckdb_parquet::RowGroup &row_group) override; unique_ptr InitializeStatsState() override; void WriteVector(WriteStream &temp_writer, ColumnWriterStatistics *stats_p, ColumnWriterPageState *page_state_p, @@ -57,8 +58,6 @@ class EnumColumnWriter : public PrimitiveColumnWriter { EnumWriterPageState &page_state); uint32_t bit_width; - //! Tracks which enum values have actually been written. - vector seen_enum; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/parquet_crypto.cpp b/src/duckdb/extension/parquet/parquet_crypto.cpp index 2f8a08513..aebc50fc1 100644 --- a/src/duckdb/extension/parquet/parquet_crypto.cpp +++ b/src/duckdb/extension/parquet/parquet_crypto.cpp @@ -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_int96.cpp b/src/duckdb/extension/parquet/parquet_int96.cpp index 2178ad62e..afbcee2b4 100644 --- a/src/duckdb/extension/parquet/parquet_int96.cpp +++ b/src/duckdb/extension/parquet/parquet_int96.cpp @@ -52,6 +52,8 @@ unique_ptr CreateInt96AsStructExpression(ClientContext &context) { args.push_back(std::move(ref)); ScalarFunction func("__internal_int96_as_struct", vector {LogicalType::BLOB}, Int96StructType(), Int96AsStructFunction); + // a day or a time outside its range is an error of the file, not an internal one + func.SetFallible(); return func.Bind(context, std::move(args)); } diff --git a/src/duckdb/extension/parquet/parquet_timestamp.cpp b/src/duckdb/extension/parquet/parquet_timestamp.cpp index e6fdb4ead..c87f5a4a4 100644 --- a/src/duckdb/extension/parquet/parquet_timestamp.cpp +++ b/src/duckdb/extension/parquet/parquet_timestamp.cpp @@ -21,6 +21,17 @@ static constexpr int64_t MICROSECONDS_PER_DAY = MILLISECONDS_PER_DAY * 1000LL; static constexpr int64_t NANOSECONDS_PER_MICRO = 1000LL; static constexpr int64_t NANOSECONDS_PER_DAY = MICROSECONDS_PER_DAY * 1000LL; +bool ParquetTimeIsValid(const int64_t &raw, const int64_t day) { + return raw >= 0 && raw <= day; +} + +template +static void CheckParquetTime(const T &raw, const int64_t day) { + if (!ParquetTimeIsValid(raw, day)) { + throw InvalidInputException("Invalid TIME value %d in Parquet file - TIME values must be within a day", raw); + } +} + static inline int64_t ImpalaTimestampToDays(const Int96 &impala_timestamp) { return impala_timestamp.value[2] - JULIAN_TO_UNIX_EPOCH_DAYS; } @@ -72,11 +83,18 @@ timestamp_t ImpalaTimestampToTimestamp(const Int96 &raw_ts) { } date_t ImpalaTimestampToDate(const Int96 &raw_ts) { - return date_t(NumericCast(ImpalaTimestampToDays(raw_ts))); + auto days_since_epoch = ImpalaTimestampToDays(raw_ts); + // the Julian day is unsigned, so the day count can lie outside the finite DATE range + if (days_since_epoch <= date_t::ninfinity().days || days_since_epoch >= date_t::infinity().days) { + throw InvalidInputException("Int96 timestamp is out of range"); + } + return date_t(static_cast(days_since_epoch)); } dtime_ns_t ImpalaTimestampToTimeNs(const Int96 &raw_ts) { - return dtime_ns_t(Load(const_data_ptr_cast(raw_ts.value))); + auto nanoseconds = Load(const_data_ptr_cast(raw_ts.value)); + CheckParquetTime(nanoseconds, Interval::NANOS_PER_DAY); + return dtime_ns_t(nanoseconds); } Int96 TimestampToImpalaTimestamp(timestamp_t &ts) { @@ -143,17 +161,6 @@ static T ParquetWrapTime(const T &raw, const T day) { return modulus + (modulus < 0) * day; } -bool ParquetTimeIsValid(const int64_t &raw, const int64_t day) { - return raw >= 0 && raw <= day; -} - -template -static void CheckParquetTime(const T &raw, const int64_t day) { - if (!ParquetTimeIsValid(raw, day)) { - throw InvalidInputException("Invalid TIME value %d in Parquet file - TIME values must be within a day", raw); - } -} - dtime_t ParquetMsIntToTime(const int32_t &raw_millis) { CheckParquetTime(raw_millis, Interval::MSECS_PER_SEC * Interval::SECS_PER_DAY); return Time::FromTimeMs(raw_millis); diff --git a/src/duckdb/extension/parquet/writer/enum_column_writer.cpp b/src/duckdb/extension/parquet/writer/enum_column_writer.cpp index b030cc307..841ab3a03 100644 --- a/src/duckdb/extension/parquet/writer/enum_column_writer.cpp +++ b/src/duckdb/extension/parquet/writer/enum_column_writer.cpp @@ -32,22 +32,40 @@ class EnumStatisticsState : public StringStatisticsState { return false; } }; + +class EnumColumnWriterState : public PrimitiveColumnWriterState { +public: + EnumColumnWriterState(ParquetWriter &writer, duckdb_parquet::RowGroup &row_group, idx_t col_idx, idx_t enum_count) + : PrimitiveColumnWriterState(writer, row_group, col_idx), seen_enum(enum_count, false) { + } + + //! Tracks which enum values have been written in this row group + vector seen_enum; +}; } // namespace class EnumWriterPageState : public ColumnWriterPageState { public: - explicit EnumWriterPageState(uint32_t bit_width) : encoder(bit_width), written_value(false) { + EnumWriterPageState(uint32_t bit_width, vector &seen_enum) + : encoder(bit_width), written_value(false), seen_enum(seen_enum) { } RleBpEncoder encoder; bool written_value; + vector &seen_enum; }; EnumColumnWriter::EnumColumnWriter(ParquetWriter &writer, ParquetColumnSchema &&column_schema, vector schema_path_p) : PrimitiveColumnWriter(writer, std::move(column_schema), std::move(schema_path_p)) { bit_width = RleBpDecoder::ComputeBitWidthFromValueCount(EnumType::GetSize(Type())); - seen_enum.resize(EnumType::GetSize(Type()), false); +} + +unique_ptr EnumColumnWriter::InitializeWriteState(duckdb_parquet::RowGroup &row_group) { + auto result = + make_uniq(writer, row_group, row_group.columns.size(), EnumType::GetSize(Type())); + RegisterToRowGroup(row_group); + return std::move(result); } unique_ptr EnumColumnWriter::InitializeStatsState() { @@ -68,7 +86,7 @@ void EnumColumnWriter::WriteEnumInternal(WriteStream &temp_writer, Vector &input page_state.written_value = true; } page_state.encoder.WriteValue(temp_writer, ptr[r]); - seen_enum[ptr[r]] = true; + page_state.seen_enum[ptr[r]] = true; } } } @@ -92,9 +110,10 @@ void EnumColumnWriter::WriteVector(WriteStream &temp_writer, ColumnWriterStatist } } -unique_ptr EnumColumnWriter::InitializePageState(PrimitiveColumnWriterState &state, +unique_ptr EnumColumnWriter::InitializePageState(PrimitiveColumnWriterState &state_p, idx_t page_idx) { - return make_uniq(bit_width); + auto &state = state_p.Cast(); + return make_uniq(bit_width, state.seen_enum); } void EnumColumnWriter::FlushPageState(WriteStream &temp_writer, ColumnWriterPageState *state_p) { @@ -117,10 +136,16 @@ bool EnumColumnWriter::HasDictionary(PrimitiveColumnWriterState &state) { } idx_t EnumColumnWriter::DictionarySize(PrimitiveColumnWriterState &state_p) { - return EnumType::GetSize(Type()); + auto &state = state_p.Cast(); + idx_t distinct_count = 0; + for (auto seen : state.seen_enum) { + distinct_count += seen; + } + return distinct_count; } -void EnumColumnWriter::FlushDictionary(PrimitiveColumnWriterState &state, ColumnWriterStatistics *stats_p) { +void EnumColumnWriter::FlushDictionary(PrimitiveColumnWriterState &state_p, ColumnWriterStatistics *stats_p) { + auto &state = state_p.Cast(); auto &stats = stats_p->Cast(); auto &enum_values = EnumType::GetValuesInsertOrder(Type()); auto enum_count = EnumType::GetSize(Type()); @@ -129,7 +154,7 @@ void EnumColumnWriter::FlushDictionary(PrimitiveColumnWriterState &state, Column auto temp_writer = make_uniq(BufferAllocator::Get(writer.GetContext())); for (idx_t r = 0; r < enum_count; r++) { D_ASSERT(!FlatVector::IsNull(enum_values, r)); - if (seen_enum[r]) { + if (state.seen_enum[r]) { stats.Update(string_values[r]); temp_writer->Write(string_values[r].GetSize()); temp_writer->WriteData(const_data_ptr_cast(string_values[r].GetData()), string_values[r].GetSize()); diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index f579d8ad9..bc0e7087d 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.0.1-alpha54836"; + descriptor->api_version = "v2.0.1-alpha55117"; 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.0.1-alpha54836"; + descriptor->api_version = "v2.0.1-alpha55117"; 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.0.1-alpha54836"; + descriptor->api_version = "v2.0.1-alpha55117"; 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.0.1-alpha54836"; + descriptor->api_version = "v2.0.1-alpha55117"; 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 02c1ffe07..31302e2fb 100644 --- a/src/duckdb/src/common/bignum.cpp +++ b/src/duckdb/src/common/bignum.cpp @@ -268,7 +268,7 @@ string_t BignumIntermediate::Negate(StringHeap &heap) const { ptr[i + Bignum::BIGNUM_HEADER_SIZE] = static_cast(~data[i]); } } - + target.Finalize(); return target; } diff --git a/src/duckdb/src/common/types.cpp b/src/duckdb/src/common/types.cpp index 0b56aec34..5b710410f 100644 --- a/src/duckdb/src/common/types.cpp +++ b/src/duckdb/src/common/types.cpp @@ -1442,6 +1442,7 @@ void LogicalType::Serialize(Serializer &serializer) const { LogicalType LogicalType::Deserialize(Deserializer &deserializer) { auto id = deserializer.ReadProperty(100, "id"); + deserializer.CheckAllowed(id); auto type_info = deserializer.ReadPropertyWithDefault>(101, "type_info"); if (id == LogicalTypeId::LEGACY_AGGREGATE_STATE) { // convert legacy aggregate state to blob on deserialize diff --git a/src/duckdb/src/common/types/hugeint.cpp b/src/duckdb/src/common/types/hugeint.cpp index b98611ddb..16024a0b4 100644 --- a/src/duckdb/src/common/types/hugeint.cpp +++ b/src/duckdb/src/common/types/hugeint.cpp @@ -185,11 +185,7 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { return false; } uint64_t upper = uint64_t(result_i128 >> 64); - if (upper & 0x8000000000000000) { - return false; - } - result.upper = int64_t(upper); - result.lower = uint64_t(result_i128 & 0xffffffffffffffff); + uint64_t lower = uint64_t(result_i128 & 0xffffffffffffffff); #else // Multiply code adapted from: // https://github.com/calccrypto/uint128_t/blob/master/uint128_t.cpp @@ -213,8 +209,8 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { return false; } // if the high bits of any of these are set, there is always an overflow - if ((products[0][3] & 0xffffffff80000000) || (products[1][2] & 0xffffffff80000000) || - (products[2][1] & 0xffffffff80000000) || (products[3][0] & 0xffffffff80000000)) { + if ((products[0][3] & 0xffffffff00000000) || (products[1][2] & 0xffffffff00000000) || + (products[2][1] & 0xffffffff00000000) || (products[3][0] & 0xffffffff00000000)) { return false; } @@ -244,7 +240,7 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { first32 += second32 >> 32; // check if the combination of the different products resulted in an overflow - if (first32 & 0xffffff80000000) { + if (first32 & 0xffffffff00000000) { return false; } @@ -255,11 +251,17 @@ bool Hugeint::TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result) { first32 &= 0xffffffff; // combine components - result.lower = (third32 << 32) | fourth32; - result.upper = (first32 << 32) | second32; + uint64_t lower = (third32 << 32) | fourth32; + uint64_t upper = (first32 << 32) | second32; #endif - if (lhs_negative ^ rhs_negative) { - NegateInPlace(result); + // The magnitude 2**127 fits only with a negative sign, as the minimum. + bool negative = lhs_negative != rhs_negative; + if (upper > 0x8000000000000000 || (upper == 0x8000000000000000 && (!negative || lower != 0))) { + return false; + } + result = hugeint_t(int64_t(upper), lower); + if (negative) { + result = HugeintNegate(result); } return true; } @@ -446,28 +448,25 @@ bool Hugeint::TryCast(hugeint_t input, uhugeint_t &result) { return true; } -template <> -bool Hugeint::TryCast(hugeint_t input, float &result) { - double dbl_result; - Hugeint::TryCast(input, dbl_result); - result = (float)dbl_result; - return true; -} - template bool CastBigintToFloating(hugeint_t input, REAL_T &result) { - switch (input.upper) { - case -1: - // special case for upper = -1 to avoid rounding issues in small negative numbers - result = -REAL_T(NumericLimits::Maximum() - input.lower) - 1; - break; - default: - result = REAL_T(input.lower) + REAL_T(input.upper) * (REAL_T(NumericLimits::Maximum()) + 1); - break; + const bool negative = input.upper < 0; + uhugeint_t magnitude(static_cast(input.upper), input.lower); + if (negative) { + magnitude = -magnitude; + } + Uhugeint::TryCast(magnitude, result); + if (negative) { + result = -result; } return true; } +template <> +bool Hugeint::TryCast(hugeint_t input, float &result) { + return CastBigintToFloating(input, result); +} + template <> bool Hugeint::TryCast(hugeint_t input, double &result) { return CastBigintToFloating(input, result); @@ -553,17 +552,20 @@ bool ConvertFloatingToBigint(REAL_T value, hugeint_t &result) { if (!Value::IsFinite(value)) { return false; } - if (value <= -170141183460469231731687303715884105728.0 || value >= 170141183460469231731687303715884105727.0) { + if (value < -170141183460469231731687303715884105728.0 || value >= 170141183460469231731687303715884105728.0) { return false; } - bool negative = value < 0; + static constexpr REAL_T TWO_TO_THE_64 = REAL_T(18446744073709551616.0); + const bool negative = value < 0; if (negative) { value = -value; } - result.lower = (uint64_t)fmod(value, REAL_T(NumericLimits::Maximum())); - result.upper = (int64_t)(value / REAL_T(NumericLimits::Maximum())); + // The magnitude of the minimum has an upper word of 2**63; it wraps to INT64_MIN, which HugeintNegate keeps. + const auto upper = static_cast(value / TWO_TO_THE_64); + const auto lower = static_cast(std::fmod(value, TWO_TO_THE_64)); + result = hugeint_t(static_cast(upper), lower); if (negative) { - Hugeint::NegateInPlace(result); + result = HugeintNegate(result); } return true; } diff --git a/src/duckdb/src/common/types/interval.cpp b/src/duckdb/src/common/types/interval.cpp index d416360fd..ec03a4a2c 100644 --- a/src/duckdb/src/common/types/interval.cpp +++ b/src/duckdb/src/common/types/interval.cpp @@ -647,6 +647,21 @@ bool Interval::TryAdd(timestamp_t left, interval_t right, timestamp_t &result) { return Timestamp::TryFromDatetime(new_date, new_time, result); } +bool Interval::TryAdd(timestamp_ns_t ns, interval_t interval, timestamp_ns_t &result) { + if (!ns.IsFinite()) { + result = ns; + return true; + } + timestamp_t us; + int64_t nanos; + const auto precision = ns.PRECISION / us.PRECISION; + Timestamp::SplitTime(ns.value, precision, us.value, nanos); + if (!Interval::TryAdd(us, interval, us)) { + return false; + } + return Timestamp::TryCombineUnits(us.value, nanos, precision, result.value); +} + dtime_t Interval::Add(dtime_t left, interval_t right, date_t &date) { int64_t diff = right.micros - ((right.micros / Interval::MICROS_PER_DAY) * Interval::MICROS_PER_DAY); left += diff; @@ -676,4 +691,11 @@ timestamp_t Interval::Add(timestamp_t left, interval_t right) { return Timestamp::FromDatetime(new_date, new_time); } +timestamp_ns_t Interval::Add(timestamp_ns_t ns, interval_t interval) { + if (!TryAdd(ns, interval, ns)) { + throw OutOfRangeException("Cannot add interval to timestamp_ns"); + } + return ns; +} + } // namespace duckdb diff --git a/src/duckdb/src/common/types/time.cpp b/src/duckdb/src/common/types/time.cpp index 299708a0e..26732d3fd 100644 --- a/src/duckdb/src/common/types/time.cpp +++ b/src/duckdb/src/common/types/time.cpp @@ -16,6 +16,33 @@ namespace duckdb { static_assert(sizeof(dtime_t) == sizeof(int64_t), "dtime_t was padded"); +static bool OnlySpaceRemains(const char *buf, idx_t len, idx_t &pos) { + while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { + pos++; + } + return pos == len; +} + +// The offset is Z or ±HH[:MM[:SS]] (PG claims they don't support :SS but they do...) +static bool TryParseOffsetSuffix(const char *buf, idx_t len, idx_t &pos, int32_t &offset, bool &has_offset) { + has_offset = !OnlySpaceRemains(buf, len, pos); + int hh = 0; + int mm = 0; + int ss = 0; + if (has_offset && buf[pos] == 'Z') { + pos++; + } else if (has_offset && !Timestamp::TryParseUTCOffset(buf, pos, len, hh, mm, ss)) { + return false; + } + + // Offsets are in seconds in the open interval (-16:00:00, +16:00:00) + offset = ((hh * Interval::MINS_PER_HOUR) + mm) * Interval::SECS_PER_MINUTE + ss; + if (offset < dtime_tz_t::MIN_OFFSET || offset > dtime_tz_t::MAX_OFFSET) { + return false; + } + return OnlySpaceRemains(buf, len, pos); +} + // string format is hh:mm:ss.microsecondsZ // microseconds and Z are optional // ISO 8601 @@ -124,16 +151,8 @@ bool Time::TryConvertInternal(const char *buf, idx_t len, idx_t &pos, dtime_t &r } } - // in strict mode, check remaining string for non-space characters - if (strict) { - // skip trailing spaces - while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { - pos++; - } - // check position. if end was not reached, non-space chars remaining - if (pos < len) { - return false; - } + if (strict && !OnlySpaceRemains(buf, len, pos)) { + return false; } // a negative interval accumulates below zero, so its minimum fits @@ -173,6 +192,12 @@ bool Time::TryConvertTime(const char *buf, idx_t len, idx_t &pos, dtime_t &resul } return false; } + // a TIME drops a UTC offset, as the TIMESTAMP cast does; a strict parse has already rejected one + int32_t offset; + bool has_offset; + if (!TryParseOffsetSuffix(buf, len, pos, offset, has_offset)) { + return false; + } return result.value <= Interval::MICROS_PER_DAY; } @@ -200,40 +225,11 @@ bool Time::TryConvertTimeTZ(const char *buf, idx_t len, idx_t &pos, dtime_tz_t & return false; } - // skip optional whitespace before offset - while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { - pos++; - } - - // Get the ±HH[:MM[:SS]] part - // (PG claims they don't support :SS but they do...) - int hh = 0; - int mm = 0; - int ss = 0; - has_offset = (pos < len); - if (has_offset && !Timestamp::TryParseUTCOffset(buf, pos, len, hh, mm, ss)) { + int32_t offset; + if (!TryParseOffsetSuffix(buf, len, pos, offset, has_offset)) { return false; } - // Offsets are in seconds in the open interval (-16:00:00, +16:00:00) - int32_t offset = ((hh * Interval::MINS_PER_HOUR) + mm) * Interval::SECS_PER_MINUTE + ss; - - if (offset < dtime_tz_t::MIN_OFFSET || offset > dtime_tz_t::MAX_OFFSET) { - return false; - } - - // in strict mode, check remaining string for non-space characters - if (strict) { - // skip trailing spaces - while (pos < len && StringUtil::CharacterIsSpace(buf[pos])) { - pos++; - } - // check position. if end was not reached, non-space chars remaining - if (pos < len) { - return false; - } - } - result = dtime_tz_t(time_part, offset); return true; diff --git a/src/duckdb/src/common/types/uhugeint.cpp b/src/duckdb/src/common/types/uhugeint.cpp index d62f84449..ea9679eed 100644 --- a/src/duckdb/src/common/types/uhugeint.cpp +++ b/src/duckdb/src/common/types/uhugeint.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/bit_utils.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/algorithm.hpp" @@ -407,25 +408,42 @@ bool Uhugeint::TryCast(uhugeint_t input, hugeint_t &result) { return true; } -template <> -bool Uhugeint::TryCast(uhugeint_t input, float &result) { - double dbl_result; - Uhugeint::TryCast(input, dbl_result); - result = (float)dbl_result; - return true; -} - template bool CastUhugeintToFloating(uhugeint_t input, REAL_T &result) { - result = REAL_T(input.lower) + REAL_T(input.upper) * REAL_T(NumericLimits::Maximum()); + static constexpr REAL_T TWO_TO_THE_64 = REAL_T(18446744073709551616.0); + if (std::numeric_limits::digits >= 64) { + // Both halves convert exactly, so the sum is the only rounding. + result = REAL_T(input.upper) * TWO_TO_THE_64 + REAL_T(input.lower); + return true; + } + if (input.upper == 0) { + result = REAL_T(input.lower); + return true; + } + // The top 64 bits with every lower bit folded into the last one round to the mantissa as the whole value does. + const auto leading = CountZeros::Leading(input.upper); + // The lower half shifts in two steps because a shift by 64, when leading is 0, is undefined. + const uint64_t top = + (input.upper << leading) | ((input.lower >> 1) >> (63 - leading)) | uint64_t((input.lower << leading) != 0); + result = REAL_T(top) * REAL_T(uint64_t(1) << (63 - leading)) * REAL_T(2); return true; } +template <> +bool Uhugeint::TryCast(uhugeint_t input, float &result) { + return CastUhugeintToFloating(input, result); +} + template <> bool Uhugeint::TryCast(uhugeint_t input, double &result) { return CastUhugeintToFloating(input, result); } +template <> +bool Uhugeint::TryCast(uhugeint_t input, long double &result) { + return CastUhugeintToFloating(input, result); +} + template uhugeint_t UhugeintConvertInteger(DST input) { uhugeint_t result; @@ -516,8 +534,9 @@ bool ConvertFloatingToUhugeint(REAL_T value, uhugeint_t &result) { if (value < 0 || value >= 340282366920938463463374607431768211456.0) { return false; } - result.lower = (uint64_t)fmod(value, REAL_T(NumericLimits::Maximum())); - result.upper = (uint64_t)(value / REAL_T(NumericLimits::Maximum())); + static constexpr REAL_T TWO_TO_THE_64 = REAL_T(18446744073709551616.0); + result.lower = static_cast(std::fmod(value, TWO_TO_THE_64)); + result.upper = static_cast(value / TWO_TO_THE_64); return true; } diff --git a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp index 12b84ff0e..f045f6029 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp @@ -240,87 +240,12 @@ vector GetChildIndices(const UnifiedVariantVectorData &variant, idx_t row return child_indices; } -static idx_t AnalyzeValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, - vector &offsets, optional_ptr shredding_state) { - idx_t total_size = 0; +//! The size of a primitive value, the value header included +static idx_t AnalyzePrimitiveValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + VariantLogicalType type_id) { //! Every value has at least a value header - total_size++; - - idx_t offset_size = offsets.size(); - VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; - if (variant.RowIsValid(row)) { - type_id = variant.GetTypeId(row, values_index); - } + idx_t total_size = 1; switch (type_id) { - case VariantLogicalType::OBJECT: { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - //! Calculate value and key offsets for all children - idx_t total_offset = 0; - uint32_t highest_keys_index = 0; - - auto child_indices = GetChildIndices(variant, row, nested_data, shredding_state); - if (nested_data.child_count && child_indices.empty()) { - //! All fields of the object are shredded, omit the object entirely - return 0; - } - - auto num_elements = child_indices.size(); - offsets.resize(offset_size + num_elements + 1); - - for (idx_t entry = 0; entry < child_indices.size(); entry++) { - auto i = child_indices[entry]; - auto keys_index = variant.GetKeysIndex(row, i + nested_data.children_idx); - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); - offsets[offset_size + entry] = NumericCast(total_offset); - - total_offset += AnalyzeValueData(variant, row, values_index, offsets, nullptr); - highest_keys_index = MaxValue(highest_keys_index, keys_index); - } - offsets[offset_size + num_elements] = NumericCast(total_offset); - - //! Calculate the sizes for the objects value data - auto field_id_size = CalculateByteLength(highest_keys_index); - auto field_offset_size = CalculateByteLength(total_offset); - const bool is_large = num_elements > NumericLimits::Maximum(); - - //! Now add the sizes for the objects value data - if (is_large) { - total_size += sizeof(uint32_t); - } else { - total_size += sizeof(uint8_t); - } - total_size += num_elements * field_id_size; - total_size += (num_elements + 1) * field_offset_size; - total_size += total_offset; - break; - } - case VariantLogicalType::ARRAY: { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - idx_t total_offset = 0; - offsets.resize(offset_size + nested_data.child_count + 1); - for (idx_t i = 0; i < nested_data.child_count; i++) { - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); - offsets[offset_size + i] = NumericCast(total_offset); - - total_offset += AnalyzeValueData(variant, row, values_index, offsets, nullptr); - } - offsets[offset_size + nested_data.child_count] = NumericCast(total_offset); - - auto field_offset_size = CalculateByteLength(total_offset); - auto num_elements = nested_data.child_count; - const bool is_large = num_elements > NumericLimits::Maximum(); - - if (is_large) { - total_size += sizeof(uint32_t); - } else { - total_size += sizeof(uint8_t); - } - total_size += (num_elements + 1) * field_offset_size; - total_size += total_offset; - break; - } case VariantLogicalType::BLOB: case VariantLogicalType::VARCHAR: { auto string_value = VariantUtils::DecodeStringData(variant, row, values_index); @@ -410,6 +335,107 @@ static idx_t AnalyzeValueData(const UnifiedVariantVectorData &variant, idx_t row return total_size; } +//! The size of the header of a nested value, the value header, the element count, the field ids and the field offsets +static idx_t NestedHeaderSize(idx_t num_elements, idx_t field_id_size, idx_t field_offset_size) { + idx_t total_size = 1; + if (num_elements > NumericLimits::Maximum()) { + total_size += sizeof(uint32_t); + } else { + total_size += sizeof(uint8_t); + } + total_size += num_elements * field_id_size; + total_size += (num_elements + 1) * field_offset_size; + return total_size; +} + +//! A nested value whose children are being measured. The explicit stack replaces recursion, so the nesting depth of +//! a value is not bounded by the thread stack +struct AnalyzeFrame { + VariantLogicalType type_id; + VariantNestedData nested_data; + //! The children of an object in the order of the Parquet value, unused for an array + vector child_indices; + idx_t num_elements = 0; + //! Where the field offsets of this value start in 'offsets' + idx_t offset_start = 0; + idx_t next_child = 0; + //! The size of the children measured so far + idx_t total_offset = 0; + uint32_t highest_keys_index = 0; +}; + +//! The caller keeps 'stack' across rows, so its capacity is reused +static idx_t AnalyzeValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + vector &offsets, optional_ptr shredding_state, + vector &stack) { + stack.clear(); + auto current = values_index; + for (;;) { + //! Measure 'current', entering it when it is nested + VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; + if (variant.RowIsValid(row)) { + type_id = variant.GetTypeId(row, current); + } + if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { + AnalyzeFrame frame; + frame.type_id = type_id; + frame.nested_data = VariantUtils::DecodeNestedData(variant, row, current); + if (type_id == VariantLogicalType::OBJECT) { + //! The shredding state only applies to the root + frame.child_indices = + GetChildIndices(variant, row, frame.nested_data, stack.empty() ? shredding_state : nullptr); + if (frame.nested_data.child_count && frame.child_indices.empty()) { + //! All fields of the object are shredded, omit the object entirely + D_ASSERT(stack.empty()); + return 0; + } + frame.num_elements = frame.child_indices.size(); + } else { + frame.num_elements = frame.nested_data.child_count; + } + frame.offset_start = offsets.size(); + offsets.resize(frame.offset_start + frame.num_elements + 1); + stack.push_back(std::move(frame)); + } else { + auto size = AnalyzePrimitiveValueData(variant, row, current, type_id); + if (stack.empty()) { + return size; + } + stack.back().total_offset += size; + } + //! Finish the nested values whose children are all measured, then move to the next child + for (;;) { + auto &frame = stack.back(); + if (frame.next_child < frame.num_elements) { + auto child = frame.type_id == VariantLogicalType::OBJECT ? frame.child_indices[frame.next_child] + : frame.next_child; + auto child_position = child + frame.nested_data.children_idx; + offsets[frame.offset_start + frame.next_child] = NumericCast(frame.total_offset); + if (frame.type_id == VariantLogicalType::OBJECT) { + frame.highest_keys_index = + MaxValue(frame.highest_keys_index, variant.GetKeysIndex(row, child_position)); + } + current = variant.GetValuesIndex(row, child_position); + frame.next_child++; + break; + } + //! All children are measured, the header sizes follow from them + offsets[frame.offset_start + frame.num_elements] = NumericCast(frame.total_offset); + idx_t field_id_size = 0; + if (frame.type_id == VariantLogicalType::OBJECT) { + field_id_size = CalculateByteLength(frame.highest_keys_index); + } + auto field_offset_size = CalculateByteLength(frame.total_offset); + auto size = NestedHeaderSize(frame.num_elements, field_id_size, field_offset_size) + frame.total_offset; + stack.pop_back(); + if (stack.empty()) { + return size; + } + stack.back().total_offset += size; + } + } +} + template void WritePrimitiveTypeHeader(data_ptr_t &value_data) { uint8_t value_header = 0; @@ -632,148 +658,166 @@ static void WritePrimitiveValueData(const UnifiedVariantVectorData &variant, idx } } -static void WriteValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, - data_ptr_t &value_data, const vector &offsets, idx_t &offset_index, - optional_ptr shredding_state) { - VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; - if (variant.RowIsValid(row)) { - type_id = variant.GetTypeId(row, values_index); - } - if (type_id == VariantLogicalType::OBJECT) { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - //! -- Object value header -- +//! A nested value whose children are being written +struct WriteFrame { + VariantLogicalType type_id; + VariantNestedData nested_data; + //! The children of an object in the order of the Parquet value, unused for an array + vector child_indices; + idx_t num_elements = 0; + idx_t field_offset_size = 0; + idx_t next_child = 0; + //! The size of the children written so far + idx_t total_offset = 0; + //! Where the next field offset is written + data_ptr_t offsets_ptr = nullptr; + //! Where the next child is written + data_ptr_t children_ptr = nullptr; + //! Where the child being written started + data_ptr_t child_start = nullptr; +}; - auto child_indices = GetChildIndices(variant, row, nested_data, shredding_state); - if (nested_data.child_count && child_indices.empty()) { +//! Writes the header of a nested value, the value header, the element count and for an object the field ids, and +//! leaves the frame ready to write the field offsets and the children +static WriteFrame WriteNestedHeader(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + VariantLogicalType type_id, data_ptr_t &value_data, const vector &offsets, + idx_t &offset_index, optional_ptr shredding_state) { + WriteFrame frame; + frame.type_id = type_id; + frame.nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); + idx_t field_id_size = 0; + if (type_id == VariantLogicalType::OBJECT) { + frame.child_indices = GetChildIndices(variant, row, frame.nested_data, shredding_state); + if (frame.nested_data.child_count && frame.child_indices.empty()) { throw InternalException( "The entire should be omitted, should have been handled by the Analyze step already"); } - auto num_elements = child_indices.size(); + frame.num_elements = frame.child_indices.size(); //! Determine the 'field_id_size' uint32_t highest_keys_index = 0; - for (auto &i : child_indices) { - auto keys_index = variant.GetKeysIndex(row, i + nested_data.children_idx); + for (auto &i : frame.child_indices) { + auto keys_index = variant.GetKeysIndex(row, i + frame.nested_data.children_idx); highest_keys_index = MaxValue(highest_keys_index, keys_index); } - auto field_id_size = CalculateByteLength(highest_keys_index); + field_id_size = CalculateByteLength(highest_keys_index); + } else { + frame.num_elements = frame.nested_data.child_count; + } - uint32_t last_offset = 0; - if (num_elements) { - last_offset = offsets[offset_index + num_elements]; - } - offset_index += num_elements + 1; - auto field_offset_size = CalculateByteLength(last_offset); + uint32_t last_offset = 0; + if (frame.num_elements) { + last_offset = offsets[offset_index + frame.num_elements]; + } + offset_index += frame.num_elements + 1; + frame.field_offset_size = CalculateByteLength(last_offset); - const bool is_large = num_elements > NumericLimits::Maximum(); + const bool is_large = frame.num_elements > NumericLimits::Maximum(); - uint8_t value_header = 0; + uint8_t value_header = 0; + if (type_id == VariantLogicalType::OBJECT) { value_header |= static_cast(VariantBasicType::OBJECT); value_header |= static_cast(is_large) << 6; value_header |= (static_cast(field_id_size) - 1) << 4; - value_header |= (static_cast(field_offset_size) - 1) << 2; - -#ifdef DEBUG - auto object_value_header = VariantValueMetadata::FromHeaderByte(value_header); - D_ASSERT(object_value_header.basic_type == VariantBasicType::OBJECT); - D_ASSERT(object_value_header.is_large == is_large); - D_ASSERT(object_value_header.field_offset_size == field_offset_size); - D_ASSERT(object_value_header.field_id_size == field_id_size); -#endif - - *value_data = value_header; - value_data++; - - //! Write the 'num_elements' - if (is_large) { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint32_t); - } else { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint8_t); - } - - //! Write the 'field_id' entries - for (auto &i : child_indices) { - auto keys_index = variant.GetKeysIndex(row, i + nested_data.children_idx); - memcpy(value_data, reinterpret_cast(&keys_index), field_id_size); - value_data += field_id_size; - } - - //! Write the 'field_offset' entries and the child 'value's - auto children_ptr = value_data + ((num_elements + 1) * field_offset_size); - idx_t total_offset = 0; - for (auto &i : child_indices) { - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); - - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - auto start_ptr = children_ptr; - WriteValueData(variant, row, values_index, children_ptr, offsets, offset_index, nullptr); - total_offset += NumericCast(children_ptr - start_ptr); - } - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - D_ASSERT(children_ptr - total_offset == value_data); - value_data = children_ptr; - } else if (type_id == VariantLogicalType::ARRAY) { - auto nested_data = VariantUtils::DecodeNestedData(variant, row, values_index); - - //! -- Array value header -- - - uint32_t last_offset = 0; - if (nested_data.child_count) { - last_offset = offsets[offset_index + nested_data.child_count]; - } - offset_index += nested_data.child_count + 1; - auto field_offset_size = CalculateByteLength(last_offset); - - auto num_elements = nested_data.child_count; - const bool is_large = num_elements > NumericLimits::Maximum(); - - uint8_t value_header = 0; + value_header |= (static_cast(frame.field_offset_size) - 1) << 2; + } else { value_header |= static_cast(VariantBasicType::ARRAY); value_header |= static_cast(is_large) << 4; - value_header |= (static_cast(field_offset_size) - 1) << 2; + value_header |= (static_cast(frame.field_offset_size) - 1) << 2; + } #ifdef DEBUG - auto array_value_header = VariantValueMetadata::FromHeaderByte(value_header); - D_ASSERT(array_value_header.basic_type == VariantBasicType::ARRAY); - D_ASSERT(array_value_header.is_large == is_large); - D_ASSERT(array_value_header.field_offset_size == field_offset_size); + auto nested_value_header = VariantValueMetadata::FromHeaderByte(value_header); + D_ASSERT(nested_value_header.basic_type == + (type_id == VariantLogicalType::OBJECT ? VariantBasicType::OBJECT : VariantBasicType::ARRAY)); + D_ASSERT(nested_value_header.is_large == is_large); + D_ASSERT(nested_value_header.field_offset_size == frame.field_offset_size); + if (type_id == VariantLogicalType::OBJECT) { + D_ASSERT(nested_value_header.field_id_size == field_id_size); + } #endif - *value_data = value_header; - value_data++; + *value_data = value_header; + value_data++; - //! Write the 'num_elements' - if (is_large) { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint32_t); - } else { - Store(static_cast(num_elements), value_data); - value_data += sizeof(uint8_t); - } + //! Write the 'num_elements' + if (is_large) { + Store(static_cast(frame.num_elements), value_data); + value_data += sizeof(uint32_t); + } else { + Store(static_cast(frame.num_elements), value_data); + value_data += sizeof(uint8_t); + } - //! Write the 'field_offset' entries and the child 'value's - auto children_ptr = value_data + ((num_elements + 1) * field_offset_size); - idx_t total_offset = 0; - for (idx_t i = 0; i < nested_data.child_count; i++) { - auto values_index = variant.GetValuesIndex(row, i + nested_data.children_idx); + //! Write the 'field_id' entries + for (auto &i : frame.child_indices) { + auto keys_index = variant.GetKeysIndex(row, i + frame.nested_data.children_idx); + memcpy(value_data, reinterpret_cast(&keys_index), field_id_size); + value_data += field_id_size; + } - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - auto start_ptr = children_ptr; - WriteValueData(variant, row, values_index, children_ptr, offsets, offset_index, nullptr); - total_offset += NumericCast(children_ptr - start_ptr); + //! The 'field_offset' entries come next, the children follow them + frame.offsets_ptr = value_data; + frame.children_ptr = value_data + ((frame.num_elements + 1) * frame.field_offset_size); + return frame; +} + +//! The explicit stack replaces recursion, so the nesting depth of a value is not bounded by the thread stack. The +//! caller keeps it across rows, so its capacity is reused +static void WriteValueData(const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index, + data_ptr_t &value_data, const vector &offsets, idx_t &offset_index, + optional_ptr shredding_state, vector &stack) { + stack.clear(); + auto current = values_index; + auto cursor = value_data; + for (;;) { + //! Write 'current' at 'cursor', entering it when it is nested + VariantLogicalType type_id = VariantLogicalType::VARIANT_NULL; + if (variant.RowIsValid(row)) { + type_id = variant.GetTypeId(row, current); + } + if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { + //! The shredding state only applies to the root + stack.push_back(WriteNestedHeader(variant, row, current, type_id, cursor, offsets, offset_index, + stack.empty() ? shredding_state : nullptr)); + } else { + WritePrimitiveValueData(variant, row, current, cursor, offsets, offset_index); + if (stack.empty()) { + value_data = cursor; + return; + } + auto &parent = stack.back(); + parent.total_offset += NumericCast(cursor - parent.child_start); + parent.children_ptr = cursor; + } + //! Finish the nested values whose children are all written, then move to the next child + for (;;) { + auto &frame = stack.back(); + if (frame.next_child < frame.num_elements) { + auto child = frame.type_id == VariantLogicalType::OBJECT ? frame.child_indices[frame.next_child] + : frame.next_child; + memcpy(frame.offsets_ptr, reinterpret_cast(&frame.total_offset), frame.field_offset_size); + frame.offsets_ptr += frame.field_offset_size; + frame.child_start = frame.children_ptr; + cursor = frame.children_ptr; + current = variant.GetValuesIndex(row, child + frame.nested_data.children_idx); + frame.next_child++; + break; + } + //! All children are written, the last field offset is their total size + memcpy(frame.offsets_ptr, reinterpret_cast(&frame.total_offset), frame.field_offset_size); + frame.offsets_ptr += frame.field_offset_size; + D_ASSERT(frame.children_ptr - frame.total_offset == frame.offsets_ptr); + cursor = frame.children_ptr; + stack.pop_back(); + if (stack.empty()) { + value_data = cursor; + return; + } + auto &parent = stack.back(); + parent.total_offset += NumericCast(cursor - parent.child_start); + parent.children_ptr = cursor; } - memcpy(value_data, reinterpret_cast(&total_offset), field_offset_size); - value_data += field_offset_size; - D_ASSERT(children_ptr - total_offset == value_data); - value_data = children_ptr; - } else { - WritePrimitiveValueData(variant, row, values_index, value_data, offsets, offset_index); } } @@ -784,6 +828,8 @@ static void CreateValues(UnifiedVariantVectorData &variant, Vector &value, optio auto &validity = FlatVector::ValidityMutable(value); auto value_data = FlatVector::GetDataMutable(value); + vector analyze_stack; + vector write_stack; for (idx_t i = 0; i < count; i++) { uint32_t value_index = 0; if (value_index_sel) { @@ -815,7 +861,7 @@ static void CreateValues(UnifiedVariantVectorData &variant, Vector &value, optio //! The (relative) offsets for each value, in the case of nesting vector offsets; //! Determine the size of this 'value' blob - idx_t blob_length = AnalyzeValueData(variant, row, value_index, offsets, shredding_state); + idx_t blob_length = AnalyzeValueData(variant, row, value_index, offsets, shredding_state, analyze_stack); if (!blob_length) { //! This is only allowed to happen for a shredded OBJECT, where there are no excess fields to write for the //! OBJECT @@ -829,7 +875,7 @@ static void CreateValues(UnifiedVariantVectorData &variant, Vector &value, optio auto value_blob_data = reinterpret_cast(value_blob.GetDataWriteable()); idx_t offset_index = 0; - WriteValueData(variant, row, value_index, value_blob_data, offsets, offset_index, shredding_state); + WriteValueData(variant, row, value_index, value_blob_data, offsets, offset_index, shredding_state, write_stack); D_ASSERT(data_ptr_cast(value_blob.GetDataWriteable() + blob_length) == value_blob_data); value_blob.SetSizeAndFinalize(NumericCast(blob_length), blob_length); } diff --git a/src/duckdb/src/common/vector_operations/vector_hash.cpp b/src/duckdb/src/common/vector_operations/vector_hash.cpp index 8a303ca2e..664a52015 100644 --- a/src/duckdb/src/common/vector_operations/vector_hash.cpp +++ b/src/duckdb/src/common/vector_operations/vector_hash.cpp @@ -131,12 +131,26 @@ void StructLoopHash(const Vector &input, Vector &hashes, const SelectionVector * } } -template -void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { - // FIXME: if we want to be more efficient we shouldn't flatten, but the logic here currently requires it +template +hash_t *FlattenHashesForCombine(Vector &hashes, const SelectionVector *rsel, idx_t count) { + const bool is_constant = hashes.GetVectorType() == VectorType::CONSTANT_VECTOR; + const hash_t constant_hash = is_constant ? *ConstantVector::GetData(hashes) : 0; hashes.Flatten(); FlatVector::SetSize(hashes, count_t(count)); auto hdata = FlatVector::GetDataMutable(hashes); + if (is_constant) { + // Flatten fills only the first Size() slots, but a selection reads and writes the hashes at its own positions. + for (idx_t i = 0; i < count; i++) { + hdata[HAS_RSEL ? rsel->get_index(i) : i] = constant_hash; + } + } + return hdata; +} + +template +void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { + // FIXME: if we want to be more efficient we shouldn't flatten, but the logic here currently requires it + auto hdata = FlattenHashesForCombine(hashes, rsel, count); UnifiedVectorFormat idata; input.ToUnifiedFormat(idata); @@ -225,9 +239,7 @@ void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rs template void ArrayLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { - hashes.Flatten(); - FlatVector::SetSize(hashes, count_t(count)); - auto hdata = FlatVector::GetDataMutable(hashes); + auto hdata = FlattenHashesForCombine(hashes, rsel, count); UnifiedVectorFormat idata; input.ToUnifiedFormat(idata); diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp index 24ccfc2a0..606cf9290 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp @@ -749,11 +749,9 @@ bool LineError::HandleErrors(StringValueResult &result) { result.current_line_position.begin.GetGlobalPosition(result.requested_size, first_nl), line_pos.GetGlobalPosition(result.requested_size), result.path); } - // the file types are those of the projected columns - auto &file_types = result.csv_file_scan->file_types; - if (cur_error.chunk_idx < file_types.size() && - !StringValueScanner::CanDirectlyCast(file_types[cur_error.chunk_idx], result.icu_loaded)) { - result.number_of_rows--; + // the value is invalid: make it NULL so that casting the column does not report a second error for it + if (cur_error.chunk_idx < result.validity_mask.size()) { + result.validity_mask[cur_error.chunk_idx]->SetInvalid(static_cast(result.number_of_rows)); } break; } diff --git a/src/duckdb/src/execution/physical_plan/plan_create_table.cpp b/src/duckdb/src/execution/physical_plan/plan_create_table.cpp index 94350b014..28cb05cba 100644 --- a/src/duckdb/src/execution/physical_plan/plan_create_table.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_create_table.cpp @@ -38,8 +38,9 @@ PhysicalOperator &DuckCatalog::PlanCreateTableAs(ClientContext &context, Physica PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCreateTable &op) { const auto &create_info = op.info->base->Cast(); auto &catalog = op.info->schema.catalog; - auto existing_entry = catalog.GetEntry(context, CatalogType::TABLE_ENTRY, create_info.GetQualifiedName().Schema(), - create_info.GetTableName(), OnEntryNotFound::RETURN_NULL); + // probe the bound schema entry directly: re-resolving by name can hit a sibling schema with the same leaf name + auto existing_entry = op.info->schema.GetEntry(catalog.GetCatalogTransaction(context), CatalogType::TABLE_ENTRY, + create_info.GetTableName()); bool replace = op.info->Base().on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT; if ((!existing_entry || replace) && !op.children.empty()) { auto &plan = CreatePlan(*op.children[0]); diff --git a/src/duckdb/src/function/cast/bignum_casts.cpp b/src/duckdb/src/function/cast/bignum_casts.cpp index a222595e3..db75f6eee 100644 --- a/src/duckdb/src/function/cast/bignum_casts.cpp +++ b/src/duckdb/src/function/cast/bignum_casts.cpp @@ -195,6 +195,8 @@ static bool DoubleToBignum(T double_value, bignum_t &result_value, Vector &resul // We can't cast inf -inf nan return false; } + // Round half to even like the casts to BIGINT and HUGEINT; the byte loop below is only exact for whole numbers. + double_value = std::nearbyint(double_value); // Determine if the number is negative bool is_negative = double_value < 0; // Determine the number of data bytes diff --git a/src/duckdb/src/function/function_binder.cpp b/src/duckdb/src/function/function_binder.cpp index 5e3900edc..d8e46de03 100644 --- a/src/duckdb/src/function/function_binder.cpp +++ b/src/duckdb/src/function/function_binder.cpp @@ -774,6 +774,10 @@ void FunctionBinder::CastToFunctionArguments(BoundSimpleFunction &function, vect "Function %s returned a STRING_LITERAL or INTEGER_LITERAL type - return an explicit type instead", function.GetName()); } + if (children[i]->GetReturnType().id() == LogicalTypeId::UNKNOWN && !target_type.IsComplete()) { + // an unresolved parameter cannot take an incomplete type, the statement is bound again at EXECUTE + throw ParameterNotResolvedException(); + } target_type.Verify(); // don't cast lambda children, their slot only ever holds a placeholder if (children[i]->GetReturnType().id() == LogicalTypeId::LAMBDA) { @@ -791,9 +795,9 @@ void FunctionBinder::CastToFunctionArguments(BoundSimpleFunction &function, vect // except for one special case: if the function accepts ANY argument // in that case we don't add a cast if (cast_result == LogicalTypeComparisonResult::DIFFERENT_TYPES) { - if (target_has_any && children[i]->GetReturnType().id() != LogicalTypeId::UNKNOWN) { + if (target_has_any) { // a type that is not concrete cannot be cast to (e.g. a NULL or a VARIANT passed to LIST(ANY)) - the - // function has to handle the argument as-is. Unresolved parameters are still assigned the type. + // function has to handle the argument as-is continue; } if (IsIncompleteCastTarget(target_type)) { diff --git a/src/duckdb/src/function/scalar/comparison/between.cpp b/src/duckdb/src/function/scalar/comparison/between.cpp index 94dc9a55c..07af88c26 100644 --- a/src/duckdb/src/function/scalar/comparison/between.cpp +++ b/src/duckdb/src/function/scalar/comparison/between.cpp @@ -5,6 +5,7 @@ #include "duckdb/function/scalar/comparison_functions.hpp" #include "duckdb/function/scalar_function.hpp" #include "duckdb/parser/expression/between_expression.hpp" +#include "duckdb/parser/expression/comparison_expression.hpp" #include "duckdb/planner/expression/bound_between_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/legacy_bound_between_expression.hpp" @@ -221,7 +222,17 @@ unique_ptr BindBetweenFun(BindScalarFunctionInput &input) { } string BetweenToString(FunctionToStringInput &input) { - return BetweenExpression::ToString(*input.children[0], *input.children[1], *input.children[2]); + auto &between_info = input.bind_data->Cast(); + auto &between_input = input.GetChild(0); + auto &lower = input.GetChild(1); + auto &upper = input.GetChild(2); + if (between_info.lower_inclusive && between_info.upper_inclusive) { + return BetweenExpression::ToString(between_input, lower, upper); + } + auto lower_type = BoundBetweenExpression::LowerComparisonType(between_info.lower_inclusive); + auto upper_type = BoundBetweenExpression::UpperComparisonType(between_info.upper_inclusive); + return "(" + ComparisonExpression::ToString(lower_type, between_input, lower) + " AND " + + ComparisonExpression::ToString(upper_type, between_input, upper) + ")"; } ExpressionType BetweenGetExpressionType(FunctionToStringInput &input) { diff --git a/src/duckdb/src/function/scalar/operator/add.cpp b/src/duckdb/src/function/scalar/operator/add.cpp index 22bce3f0e..f951f2068 100644 --- a/src/duckdb/src/function/scalar/operator/add.cpp +++ b/src/duckdb/src/function/scalar/operator/add.cpp @@ -8,6 +8,7 @@ #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/operator/cast_operators.hpp" namespace duckdb { @@ -107,11 +108,41 @@ timestamp_t AddOperator::Operation(timestamp_t left, interval_t right) { return Interval::Add(left, right); } +template <> +timestamp_t AddOperator::Operation(timestamp_sec_t left, interval_t right) { + return Interval::Add(Cast::Operation(left), right); +} + +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, interval_t right) { + return Interval::Add(Cast::Operation(left), right); +} + +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, interval_t right) { + return Interval::Add(left, right); +} + +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_sec_t right) { + return AddOperator::Operation(right, left); +} + +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_ms_t right) { + return AddOperator::Operation(right, left); +} + template <> timestamp_t AddOperator::Operation(interval_t left, timestamp_t right) { return AddOperator::Operation(right, left); } +template <> +timestamp_ns_t AddOperator::Operation(interval_t left, timestamp_ns_t right) { + return AddOperator::Operation(right, left); +} + template <> timestamp_t AddOperator::Operation(timestamp_t left, double right) { timestamp_t result; @@ -121,6 +152,33 @@ timestamp_t AddOperator::Operation(timestamp_t left, double right) { return result; } +template <> +timestamp_t AddOperator::Operation(timestamp_sec_t left, double right) { + timestamp_t result; + if (!TryAddOperator::Operation(left.value, int64_t(right), result.value)) { + throw OutOfRangeException("Overflow in timestamp (s) addition"); + } + return result; +} + +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, double right) { + timestamp_t result; + if (!TryAddOperator::Operation(left.value, int64_t(right), result.value)) { + throw OutOfRangeException("Overflow in timestamp (ms) addition"); + } + return result; +} + +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, double right) { + timestamp_ns_t result; + if (!TryAddOperator::Operation(left.value, int64_t(right), result.value)) { + throw OutOfRangeException("Overflow in timestamp_ns addition"); + } + return result; +} + //===--------------------------------------------------------------------===// // + [add] with overflow check //===--------------------------------------------------------------------===// @@ -167,6 +225,11 @@ bool TryAddOperator::Operation(timestamp_t left, interval_t right, timestamp_t & return Interval::TryAdd(left, right, result); } +template <> +bool TryAddOperator::Operation(timestamp_ns_t left, interval_t right, timestamp_ns_t &result) { + return Interval::TryAdd(left, right, result); +} + template <> bool TryAddOperator::Operation(date_t left, int32_t right, date_t &result) { if (left == date_t::infinity() || left == date_t::ninfinity()) { diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index ff525fa21..4ae635d65 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -611,6 +611,30 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi // not monotonic: adding months clamps the day but keeps the time, e.g. // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' return function; + } else if (right_type.id() == LogicalTypeId::TIMESTAMP_SEC) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: adding months clamps the day but keeps the time, e.g. + // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + return function; + } else if (right_type.id() == LogicalTypeId::TIMESTAMP_MS) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: adding months clamps the day but keeps the time, e.g. + // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + return function; + } else if (right_type.id() == LogicalTypeId::TIMESTAMP_NS) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP_NS, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: adding months clamps the day but keeps the time, e.g. + // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + return function; } break; case LogicalTypeId::TIME: @@ -640,6 +664,26 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi return function; } break; + case LogicalTypeId::TIMESTAMP_SEC: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: see INTERVAL + TIMESTAMP_SEC + return function; + } + break; + case LogicalTypeId::TIMESTAMP_MS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: see INTERVAL + TIMESTAMP_MS + return function; + } + break; case LogicalTypeId::TIMESTAMP: if (right_type.id() == LogicalTypeId::INTERVAL) { ScalarFunction function("+", {left_type, right_type}, LogicalType::TIMESTAMP, @@ -649,6 +693,16 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi return function; } break; + case LogicalTypeId::TIMESTAMP_NS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "+", {left_type, right_type}, LogicalType::TIMESTAMP_NS, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: see INTERVAL + TIMESTAMP + return function; + } + break; default: break; } @@ -697,9 +751,18 @@ ScalarFunctionSet OperatorAddFun::GetFunctions() { add.AddFunction(AddFunction::GetFunction(LogicalType::TIME, LogicalType::INTERVAL)); add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIME)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP_S, LogicalType::INTERVAL)); + add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP_S)); + + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP_MS, LogicalType::INTERVAL)); + add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP_MS)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP, LogicalType::INTERVAL)); add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIMESTAMP_NS, LogicalType::INTERVAL)); + add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIMESTAMP_NS)); + add.AddFunction(AddFunction::GetFunction(LogicalType::TIME_TZ, LogicalType::INTERVAL)); add.AddFunction(AddFunction::GetFunction(LogicalType::INTERVAL, LogicalType::TIME_TZ)); @@ -903,6 +966,42 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const return function; } break; + case LogicalTypeId::TIMESTAMP_SEC: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "-", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' + + return function; + } + break; + case LogicalTypeId::TIMESTAMP_MS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "-", {left_type, right_type}, LogicalType::TIMESTAMP, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' + + return function; + } + break; + case LogicalTypeId::TIMESTAMP_NS: + if (right_type.id() == LogicalTypeId::INTERVAL) { + ScalarFunction function( + "-", {left_type, right_type}, LogicalType::TIMESTAMP_NS, + ScalarFunction::BinaryFunction); + function.SetFallible(); + // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' + + return function; + } + break; case LogicalTypeId::INTERVAL: if (right_type.id() == LogicalTypeId::INTERVAL) { ScalarFunction function( @@ -964,6 +1063,9 @@ ScalarFunctionSet OperatorSubtractFun::GetFunctions() { subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::DATE, LogicalType::INTERVAL)); subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIME, LogicalType::INTERVAL)); subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP, LogicalType::INTERVAL)); + subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP_S, LogicalType::INTERVAL)); + subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP_MS, LogicalType::INTERVAL)); + subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIMESTAMP_NS, LogicalType::INTERVAL)); subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::TIME_TZ, LogicalType::INTERVAL)); // we can negate intervals subtract.AddFunction(SubtractFunction::GetFunction(LogicalType::INTERVAL)); @@ -1794,7 +1896,8 @@ hugeint_t InterpolateOperator::Operation(const hugeint_t &lo, const double d, co hugeint_t delta_hugeint = hi; if (Hugeint::TrySubtractInPlace(delta_hugeint, lo)) { const auto delta = Hugeint::Cast(delta_hugeint); - return lo + Hugeint::Convert(delta * d); + // Rounding delta to double can carry the offset past hi, and past the HUGEINT range when hi is the minimum. + return Hugeint::Add(lo, Hugeint::Convert(delta * d)); } // if delta overflows, we fall back to original subtraction to avoid UB diff --git a/src/duckdb/src/function/scalar/operator/decimal_division.cpp b/src/duckdb/src/function/scalar/operator/decimal_division.cpp index d90950655..d46cc6747 100644 --- a/src/duckdb/src/function/scalar/operator/decimal_division.cpp +++ b/src/duckdb/src/function/scalar/operator/decimal_division.cpp @@ -40,9 +40,63 @@ struct DecimalDivBindData : public FunctionData { // hugeint_t -- otherwise //===--------------------------------------------------------------------===// +template +static constexpr uint8_t DecimalTierWidth() { + if constexpr (std::is_same_v) { + return Decimal::MAX_WIDTH_INT16; + } else if constexpr (std::is_same_v) { + return Decimal::MAX_WIDTH_INT32; + } else if constexpr (std::is_same_v) { + return Decimal::MAX_WIDTH_INT64; + } else { + return Decimal::MAX_WIDTH_DECIMAL; + } +} + +template +static void WidenDecimal(Vector &input, Vector &widened, idx_t count) { + if constexpr (sizeof(SOURCE_TYPE) < sizeof(INPUT_TYPE)) { + auto widen = [](SOURCE_TYPE value) { + return INPUT_TYPE(value); + }; + UnaryExecutor::Execute(input, widened, count, widen); + } else { + throw InternalException("decimal_division: argument is wider than the compute tier"); + } +} + +//! Bring an argument to the physical type of the wider argument; a decimal keeps its integer value at the same scale +template +static Vector &GetDecimalInput(Vector &input, idx_t count, unique_ptr &widened) { + auto source_physical = input.GetType().InternalType(); + if (source_physical == GetTypeId()) { + return input; + } + auto scale = DecimalType::GetScale(input.GetType()); + widened = make_uniq(LogicalType::DECIMAL(DecimalTierWidth(), scale), count); + switch (source_physical) { + case PhysicalType::INT16: + WidenDecimal(input, *widened, count); + break; + case PhysicalType::INT32: + WidenDecimal(input, *widened, count); + break; + case PhysicalType::INT64: + WidenDecimal(input, *widened, count); + break; + default: + throw InternalException("decimal_division: unexpected argument physical type"); + } + return *widened; +} + template static void DecimalDivExecute(DataChunk &args, ExpressionState &state, Vector &result) { auto &bind_data = state.expr.Cast().BindInfo()->Cast(); + unique_ptr lhs_widened; + unique_ptr rhs_widened; + auto &lhs = GetDecimalInput(args.data[0], args.size(), lhs_widened); + auto &rhs = GetDecimalInput(args.data[1], args.size(), rhs_widened); bool scale_divisor = bind_data.scale_exp < 0; uint8_t abs_exp = UnsafeNumericCast(AbsValue(bind_data.scale_exp)); @@ -56,7 +110,7 @@ static void DecimalDivExecute(DataChunk &args, ExpressionState &state, Vector &r auto result_width = DecimalType::GetWidth(result.GetType()); BinaryExecutor::Execute( - args.data[0], args.data[1], result, args.size(), [&](INPUT_TYPE a, INPUT_TYPE b) -> RESULT_TYPE { + lhs, rhs, result, args.size(), [&](INPUT_TYPE a, INPUT_TYPE b) -> RESULT_TYPE { if (b == INPUT_TYPE(0)) { throw InvalidInputException("decimal_division: division by zero"); } @@ -160,6 +214,8 @@ static scalar_function_t GetDecimalDivExecuteFunction(PhysicalType result_physic // Bind function //===--------------------------------------------------------------------===// +static void SelectDecimalDivFunction(BoundScalarFunction &bound_function); + // Result width and scale for e1 / e2 (SQL Server semantics): // result_scale = max(6, s1 + p2 + 1) // result_width = p1 - s1 + s2 + result_scale @@ -173,6 +229,9 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) if (!lhs_type.GetDecimalProperties(p1, s1) || !rhs_type.GetDecimalProperties(p2, s2)) { throw InvalidInputException("decimal_division: both arguments must be DECIMAL"); } + // an integer argument is an implicit DECIMAL(p, 0): bind on its canonical DECIMAL type + auto lhs_decimal_type = lhs_type.id() == LogicalTypeId::DECIMAL ? lhs_type : LogicalType::DECIMAL(p1, s1); + auto rhs_decimal_type = rhs_type.id() == LogicalTypeId::DECIMAL ? rhs_type : LogicalType::DECIMAL(p2, s2); uint8_t result_scale; if (input.GetArgumentCount() == 3) { @@ -209,50 +268,22 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) result_width, Decimal::MAX_WIDTH_DECIMAL); } - PhysicalType result_physical; - if (result_width <= Decimal::MAX_WIDTH_INT16) { - result_physical = PhysicalType::INT16; - } else if (result_width <= Decimal::MAX_WIDTH_INT32) { - result_physical = PhysicalType::INT32; - } else if (result_width <= Decimal::MAX_WIDTH_INT64) { - result_physical = PhysicalType::INT64; - } else { - result_physical = PhysicalType::INT128; - } - bound_function.SetReturnType(LogicalType::DECIMAL(result_width, result_scale)); + // keep the argument types: a narrower argument is widened at execution, so binding again yields the same types + bound_function.GetArguments()[0] = lhs_decimal_type; + bound_function.GetArguments()[1] = rhs_decimal_type; + SelectDecimalDivFunction(bound_function); +} - auto lhs_physical = lhs_type.InternalType(); - auto rhs_physical = rhs_type.InternalType(); - auto wider = MaxValue(lhs_physical, rhs_physical); - - int32_t scale_exp = s2 + result_scale - s1; - int32_t abs_scale_exp = scale_exp < 0 ? -scale_exp : scale_exp; - - uint8_t input_max_width; - switch (wider) { - case PhysicalType::INT16: - input_max_width = Decimal::MAX_WIDTH_INT16; - break; - case PhysicalType::INT32: - input_max_width = Decimal::MAX_WIDTH_INT32; - break; - case PhysicalType::INT64: - input_max_width = Decimal::MAX_WIDTH_INT64; - break; - case PhysicalType::INT128: - input_max_width = Decimal::MAX_WIDTH_DECIMAL; - break; - default: - throw InternalException("decimal_division: unexpected physical type"); - } - - // For same-tier inputs, preserve the original argument type so bind is idempotent - // during plan deserialization (bind is re-called with the stored argument types, and - // changing p changes the result-width formula). - // For cross-tier inputs, promote the narrower argument to the wider physical tier. - bound_function.GetArguments()[0] = (lhs_physical != wider) ? LogicalType::DECIMAL(input_max_width, s1) : lhs_type; - bound_function.GetArguments()[1] = (rhs_physical != wider) ? LogicalType::DECIMAL(input_max_width, s2) : rhs_type; +//! Pick the execute function from the resolved argument and return types +static void SelectDecimalDivFunction(BoundScalarFunction &bound_function) { + auto &arguments = bound_function.GetArguments(); + const auto result_physical = bound_function.GetReturnType().InternalType(); + const auto wider = MaxValue(arguments[0].InternalType(), arguments[1].InternalType()); + const int32_t scale_exp = int32_t(DecimalType::GetScale(arguments[1])) + + int32_t(DecimalType::GetScale(bound_function.GetReturnType())) - + int32_t(DecimalType::GetScale(arguments[0])); + const int32_t abs_scale_exp = scale_exp < 0 ? -scale_exp : scale_exp; switch (wider) { case PhysicalType::INT16: @@ -287,7 +318,7 @@ static unique_ptr DecimalDivisionBind(BindScalarFunctionInput &inp auto lhs_scale = DecimalType::GetScale(bound_function.GetArguments()[0]); auto rhs_scale = DecimalType::GetScale(bound_function.GetArguments()[1]); auto result_scale = DecimalType::GetScale(bound_function.GetReturnType()); - return make_uniq(rhs_scale + result_scale - lhs_scale); + return make_uniq(int32_t(rhs_scale) + int32_t(result_scale) - int32_t(lhs_scale)); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/function/scalar/operator/subtract.cpp b/src/duckdb/src/function/scalar/operator/subtract.cpp index f33936b9e..87cd193d6 100644 --- a/src/duckdb/src/function/scalar/operator/subtract.cpp +++ b/src/duckdb/src/function/scalar/operator/subtract.cpp @@ -72,6 +72,21 @@ timestamp_t SubtractOperator::Operation(timestamp_t left, interval_t right) { return AddOperator::Operation(left, Interval::Invert(right)); } +template <> +timestamp_t SubtractOperator::Operation(timestamp_ms_t left, interval_t right) { + return AddOperator::Operation(left, Interval::Invert(right)); +} + +template <> +timestamp_t SubtractOperator::Operation(timestamp_sec_t left, interval_t right) { + return AddOperator::Operation(left, Interval::Invert(right)); +} + +template <> +timestamp_ns_t SubtractOperator::Operation(timestamp_ns_t left, interval_t right) { + return AddOperator::Operation(left, Interval::Invert(right)); +} + template <> interval_t SubtractOperator::Operation(timestamp_t left, timestamp_t right) { return Interval::GetDifference(left, right); diff --git a/src/duckdb/src/function/scalar/strftime_format.cpp b/src/duckdb/src/function/scalar/strftime_format.cpp index 2c25fa174..889d82d13 100644 --- a/src/duckdb/src/function/scalar/strftime_format.cpp +++ b/src/duckdb/src/function/scalar/strftime_format.cpp @@ -1483,6 +1483,10 @@ date_t StrpTimeFormat::ParseResult::ToDate() { } bool StrpTimeFormat::ParseResult::TryToDate(date_t &result) { + if (is_special) { + result = special; + return true; + } return Date::TryFromDate(data[0], data[1], data[2], result); } @@ -1526,6 +1530,10 @@ timestamp_t StrpTimeFormat::ParseResult::ToTimestamp() { } bool StrpTimeFormat::ParseResult::TryToTimestamp(timestamp_t &result) { + if (is_special) { + result = ToTimestamp(); + return true; + } date_t date; if (!TryToDate(date)) { return false; @@ -1560,6 +1568,10 @@ timestamp_ns_t StrpTimeFormat::ParseResult::ToTimestampNS() { } bool StrpTimeFormat::ParseResult::TryToTimestampNS(timestamp_ns_t &result) { + if (is_special) { + result = ToTimestampNS(); + return true; + } date_t date; if (!TryToDate(date)) { return false; diff --git a/src/duckdb/src/function/table/system/system_catalog_scanner.cpp b/src/duckdb/src/function/table/system/system_catalog_scanner.cpp index f04c5a121..f3d7b8b03 100644 --- a/src/duckdb/src/function/table/system/system_catalog_scanner.cpp +++ b/src/duckdb/src/function/table/system/system_catalog_scanner.cpp @@ -79,11 +79,16 @@ unique_ptr SystemCatalogScanner::CreateBindData(const vectorCast(); vector bindings; ColumnLifetimeAnalyzer::ExtractColumnBindings(expr, bindings); diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index cff604f58..f5f5f8d99 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 "1-alpha54836" +#define DUCKDB_PATCH_VERSION "1-alpha55117" #endif #ifndef DUCKDB_MINOR_VERSION #define DUCKDB_MINOR_VERSION 0 @@ -8,10 +8,10 @@ #define DUCKDB_MAJOR_VERSION 2 #endif #ifndef DUCKDB_VERSION -#define DUCKDB_VERSION "v2.0.1-alpha54836" +#define DUCKDB_VERSION "v2.0.1-alpha55117" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "925bcdf357" +#define DUCKDB_SOURCE_ID "331f91a84f" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp index 0e446aa63..b8aa71338 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 @@ -1144,11 +1144,8 @@ class MultiFileFunction : public TableFunction { auto &bind_data = input.bind_data->Cast(); auto &column_index = input.column_index; - if (!bind_data.initial_reader) { - // no reader - 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 = bind_data.initial_reader != nullptr; if (column_index.IsVirtualColumn()) { return nullptr; } @@ -1158,7 +1155,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->GetVirtualColumnStatistics( @@ -1190,27 +1187,39 @@ 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; if (multiple_files && !bind_data.file_options.union_by_name) { // multiple files, but no union_by_name: no luck! return nullptr; } - auto result = bind_data.initial_reader->GetStatistics(context, col_name); - if (result && !bind_data.file_options.bound_schema.empty() && - !bind_data.MatchesPhysicalColumn(primary_index, col_name, result->GetType())) { - // Check the whole root before interpreting an extracted child's positional statistics. - return nullptr; - } - if (result && multiple_files) { - for (idx_t i = 1; i < bind_data.union_readers.size(); i++) { - auto &union_reader = *bind_data.union_readers[i]; - auto stats = union_reader.GetStatistics(context, col_name); - if (!stats || result->GetType() != stats->GetType()) { - return nullptr; + unique_ptr result; + try { + result = bind_data.initial_reader->GetStatistics(context, col_name); + if (result && !bind_data.file_options.bound_schema.empty() && + !bind_data.MatchesPhysicalColumn(primary_index, col_name, result->GetType())) { + // Check the whole root before interpreting an extracted child's positional statistics. + return nullptr; + } + if (result && multiple_files) { + for (idx_t i = 1; i < bind_data.union_readers.size(); i++) { + auto &union_reader = *bind_data.union_readers[i]; + auto stats = union_reader.GetStatistics(context, col_name); + if (!stats || result->GetType() != stats->GetType()) { + return nullptr; + } + result->Merge(*stats); } - result->Merge(*stats); } + } catch (std::exception &ex) { + // undecodable statistics of one of multiple files just mean there are none - the data may still read fine + if (!multiple_files || ErrorData(ex).Type() == ExceptionType::INTERRUPT) { + throw; + } + return nullptr; } if (!result || !column_index.IsPushdownExtract()) { return result; diff --git a/src/duckdb/src/include/duckdb/common/operator/add.hpp b/src/duckdb/src/include/duckdb/common/operator/add.hpp index 591f064b8..0c9b8ce55 100644 --- a/src/duckdb/src/include/duckdb/common/operator/add.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/add.hpp @@ -45,11 +45,29 @@ timestamp_t AddOperator::Operation(date_t left, interval_t right); template <> timestamp_t AddOperator::Operation(interval_t left, date_t right); template <> -timestamp_t AddOperator::Operation(timestamp_t left, interval_t right); +timestamp_t AddOperator::Operation(timestamp_sec_t left, interval_t right); template <> -timestamp_t AddOperator::Operation(timestamp_t left, double right); +timestamp_t AddOperator::Operation(timestamp_sec_t left, double right); template <> -timestamp_t AddOperator::Operation(interval_t left, timestamp_t right); +timestamp_t AddOperator::Operation(interval_t left, timestamp_sec_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, interval_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_ms_t left, double right); +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_ms_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_us_t left, interval_t right); +template <> +timestamp_t AddOperator::Operation(timestamp_us_t left, double right); +template <> +timestamp_t AddOperator::Operation(interval_t left, timestamp_us_t right); +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, interval_t right); +template <> +timestamp_ns_t AddOperator::Operation(timestamp_ns_t left, double right); +template <> +timestamp_ns_t AddOperator::Operation(interval_t left, timestamp_ns_t right); struct TryAddOperator { template @@ -70,6 +88,8 @@ template <> bool TryAddOperator::Operation(date_t left, int32_t right, date_t &result); template <> bool TryAddOperator::Operation(timestamp_t left, interval_t right, timestamp_t &result); +template <> +bool TryAddOperator::Operation(timestamp_ns_t left, interval_t right, timestamp_ns_t &result); template <> bool TryAddOperator::Operation(int8_t left, int8_t right, int8_t &result); diff --git a/src/duckdb/src/include/duckdb/common/operator/subtract.hpp b/src/duckdb/src/include/duckdb/common/operator/subtract.hpp index 5b11fd797..5f4aeb1fb 100644 --- a/src/duckdb/src/include/duckdb/common/operator/subtract.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/subtract.hpp @@ -42,6 +42,12 @@ timestamp_t SubtractOperator::Operation(date_t left, interval_t right); template <> timestamp_t SubtractOperator::Operation(timestamp_t left, interval_t right); template <> +timestamp_t SubtractOperator::Operation(timestamp_ms_t left, interval_t right); +template <> +timestamp_t SubtractOperator::Operation(timestamp_sec_t left, interval_t right); +template <> +timestamp_ns_t SubtractOperator::Operation(timestamp_ns_t left, interval_t right); +template <> interval_t SubtractOperator::Operation(timestamp_t left, timestamp_t right); template <> int64_t SubtractOperator::Operation(timestamp_t left, timestamp_t right); diff --git a/src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp b/src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp new file mode 100644 index 000000000..ee9f523db --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/serializer/deserialization_policy.hpp @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/serializer/deserialization_policy.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/bitset.hpp" +#include "duckdb/common/limits.hpp" +#include "duckdb/common/types.hpp" +#include "duckdb/parser/literal.hpp" + +namespace duckdb { + +//! Restrictions on the type and literal identifiers a deserializer may reconstruct. +class DeserializationPolicy { +public: + void Disallow(LogicalTypeId type) { + disallowed_types.set(static_cast(type)); + } + + void Disallow(LiteralKind kind) { + disallowed_literals.set(static_cast(kind)); + } + + bool IsAllowed(LogicalTypeId type) const { + return !disallowed_types.test(static_cast(type)); + } + + bool IsAllowed(LiteralKind kind) const { + return !disallowed_literals.test(static_cast(kind)); + } + +private: + using LogicalTypeStorage = std::underlying_type::type; + using LiteralKindStorage = std::underlying_type::type; + + //! Size each bitset for the full range of its enum's underlying type. + bitset(NumericLimits::Maximum()) + 1> disallowed_types; + bitset(NumericLimits::Maximum()) + 1> disallowed_literals; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp b/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp index 47d39ca5f..c514d64a4 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/deserializer.hpp @@ -9,6 +9,8 @@ #pragma once #include "duckdb/common/enum_util.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/serializer/deserialization_policy.hpp" #include "duckdb/common/serializer/serialization_data.hpp" #include "duckdb/common/serializer/serialization_traits.hpp" #include "duckdb/common/identifier.hpp" @@ -28,6 +30,10 @@ class Deserializer { bool deserialize_enum_from_string = false; SerializationData data; +private: + //! Without a policy, no identifiers are blocked. + optional policy; + public: virtual ~Deserializer() { } @@ -57,6 +63,18 @@ class Deserializer { public: virtual bool CanDeserializeProperty(const field_id_t field_id, const char *tag) = 0; + void SetPolicy(const DeserializationPolicy &policy_p) { + policy = policy_p; + } + + //! Reject identifiers disallowed by the active policy. + template + void CheckAllowed(T value) const { + if (policy && !policy->IsAllowed(value)) { + throw SerializationException("Deserialization of %s is not allowed", EnumUtil::ToString(value)); + } + } + // Read into an existing value template inline void ReadProperty(const field_id_t field_id, const char *tag, T &ret) { diff --git a/src/duckdb/src/include/duckdb/common/types/interval.hpp b/src/duckdb/src/include/duckdb/common/types/interval.hpp index c0f7f607e..2e97480ca 100644 --- a/src/duckdb/src/include/duckdb/common/types/interval.hpp +++ b/src/duckdb/src/include/duckdb/common/types/interval.hpp @@ -50,6 +50,13 @@ struct interval_t { // NOLINT return !(*this == right); } + //! True when the raw (months, days, micros) fields are identical, without normalizing first. Unlike operator== + //! (which falls back to a normalized comparison, so INTERVAL 1 MONTH == INTERVAL 30 DAY), this is a strict + //! field-wise test: two intervals that are only equal after normalization are not the same here. + inline bool SameFields(const interval_t &right) const { + return months == right.months && days == right.days && micros == right.micros; + } + inline bool operator>(const interval_t &right) const { const auto &left = *this; int64_t lmonths, ldays, lmicros; @@ -167,10 +174,14 @@ class Interval { static date_t Add(date_t left, interval_t right); //! Add an interval to a timestamp static timestamp_t Add(timestamp_t left, interval_t right); + //! Add an interval to a timestamp(ns) + static timestamp_ns_t Add(timestamp_ns_t left, interval_t right); //! Add an interval to a date, returns false instead of throwing if the result is out of range static bool TryAdd(date_t left, interval_t right, date_t &result); //! Add an interval to a timestamp, returns false instead of throwing if the result is out of range static bool TryAdd(timestamp_t left, interval_t right, timestamp_t &result); + //! Add an interval to a timestamp(ns), returns false instead of throwing if the result is out of range + static bool TryAdd(timestamp_ns_t left, interval_t right, timestamp_ns_t &result); //! Add an interval to a time. In case the time overflows or underflows, modify the date by the overflow. //! For example if we go from 23:00 to 02:00, we add a day to the date static dtime_t Add(dtime_t left, interval_t right, date_t &date); diff --git a/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp b/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp index 0da548cb9..960b9457e 100644 --- a/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp +++ b/src/duckdb/src/include/duckdb/common/types/uhugeint.hpp @@ -184,6 +184,8 @@ template <> DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, float &result); template <> DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, double &result); +template <> +DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, long double &result); template <> bool Uhugeint::TryConvert(int8_t value, uhugeint_t &result); diff --git a/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp b/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp index 0254be079..d1fb227b4 100644 --- a/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp +++ b/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp @@ -75,8 +75,8 @@ class SystemCatalogScanner { CatalogType type, SystemCatalogScannerStats &stats); //! get_metrics helper: writes the counters into input.operator_metrics via AddExtraInfo. static void ReportMetrics(TableFunctionGetMetricsInput &input, const SystemCatalogScannerStats &stats); - //! Enables filter pushdown on the identity columns only. get_metrics is per function because - //! it needs the function's own GlobalTableFunctionState type to reach the stats. + //! Enables filter pushdown on the identity columns only, for filters that cannot throw. get_metrics is per + //! function because it needs the function's own GlobalTableFunctionState type to reach the stats. static void RegisterPushdown(TableFunction &function); }; diff --git a/src/duckdb/src/include/duckdb/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/http/http_retry_budget.hpp b/src/duckdb/src/include/duckdb/main/http/http_retry_budget.hpp index f6e12da59..7dc213fde 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_storage.hpp b/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp index 5cd351ee5..6dfd69585 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret_storage.hpp @@ -156,6 +156,8 @@ class CatalogSetSecretStorage : public SecretStorage { unique_ptr secrets; //! DB instance for accessing the system catalog transaction DatabaseInstance &db; + //! Serializes stores and drops, WriteSecret and RemoveSecret included, so a secret's file and entry change together + mutex store_lock; }; class TemporarySecretStorage : public CatalogSetSecretStorage { diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index 3eeeef099..be380259c 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -1713,6 +1713,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"; diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp index 870931e3a..41dc7fb2f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp @@ -122,6 +122,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/parser/peg/ast/expression_chain.hpp b/src/duckdb/src/include/duckdb/parser/peg/ast/expression_chain.hpp index debc37fc0..71b43e76b 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 10b9cd3ef..46c74405f 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -1648,11 +1648,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, @@ -1735,9 +1732,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, 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 7d90db628..794da7f20 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 @@ -614,8 +614,6 @@ enum class PEGRuleId : uint32_t { SingleExpression, Expression, ColumnDefaultExpr, - LambdaArrowExpression, - SingleArrowPair, LogicalOrExpression, LogicalOrExpressionTail, ColDefOrExpr, @@ -687,6 +685,12 @@ enum class PEGRuleId : uint32_t { OtherOperatorTail, AnyAllSubqueryTail, OtherOperatorExpressionTail, + SingleArrowTail, + SingleArrowBody, + ArrowChainBody, + ArrowChainTail, + DoubleArrowTail, + ArrowFullBody, OtherOperator, AnyAllParsedOperator, NamedOtherOperator, 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 b91eca9aa..ec4c49acf 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 @@ -89,6 +89,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); @@ -2584,13 +2585,6 @@ class PEGTransformerFactory { static void InitializeColumnDefaultExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeColumnDefaultExprTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static void InitializeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static arena_ptr FinalizeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); - static void InitializeSingleArrowPairTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeSingleArrowPairTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process); static void InitializeLogicalOrExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeLogicalOrExpressionTrampoline(PEGTransformer &transformer, @@ -2825,6 +2819,24 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeOtherOperatorExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static void InitializeSingleArrowTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeSingleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static void InitializeSingleArrowBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeSingleArrowBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static void InitializeArrowChainBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeArrowChainBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static void InitializeArrowChainTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeArrowChainTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static void InitializeDoubleArrowTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeDoubleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static void InitializeArrowFullBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeArrowFullBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static void InitializeOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); @@ -5133,11 +5145,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 @@ -5252,6 +5259,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); diff --git a/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp b/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp index 09e2b307a..52174c334 100644 --- a/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp +++ b/src/duckdb/src/include/duckdb/planner/column_qualifier.hpp @@ -47,6 +47,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, @@ -55,6 +57,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_between_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp index 96f1d34b3..95c9e1e3b 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp @@ -32,13 +32,17 @@ struct BoundBetweenExpression { static unique_ptr &LowerBoundMutable(BoundFunctionExpression &between_expr); static unique_ptr &UpperBoundMutable(BoundFunctionExpression &between_expr); + static ExpressionType LowerComparisonType(bool lower_inclusive) { + return lower_inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; + } + static ExpressionType UpperComparisonType(bool upper_inclusive) { + return upper_inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN; + } static ExpressionType LowerComparisonType(const BoundFunctionExpression &between_expr) { - return LowerInclusive(between_expr) ? ExpressionType::COMPARE_GREATERTHANOREQUALTO - : ExpressionType::COMPARE_GREATERTHAN; + return LowerComparisonType(LowerInclusive(between_expr)); } static ExpressionType UpperComparisonType(const BoundFunctionExpression &between_expr) { - return UpperInclusive(between_expr) ? ExpressionType::COMPARE_LESSTHANOREQUALTO - : ExpressionType::COMPARE_LESSTHAN; + return UpperComparisonType(UpperInclusive(between_expr)); } }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/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/subquery/flatten_dependent_join.hpp b/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp index aaa865c3b..8e74f37ea 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/flatten_dependent_join.hpp @@ -21,6 +21,7 @@ namespace duckdb { class LogicalAggregate; class LogicalComparisonJoin; class LogicalCTERef; +class LogicalDependentJoin; class LogicalExpressionGet; class LogicalJoin; @@ -115,6 +116,7 @@ class FlattenDependentJoins { vector state, bool rewrite_parent = true, idx_t child_idx = 0); UnnestingState FinalizeDependentJoin(unique_ptr &plan, UnnestingState outer_state, const UnnestingState &right_state, DependentJoinOutput output); + void MaterializeCorrelatedAggregateRewrites(LogicalDependentJoin &op, UnnestingState &outer_state); UnnestingState AttachDelimToIndependentJoinLeft(unique_ptr &plan); UnnestingState PushDownSingleCorrelatedChild(unique_ptr &plan, bool propagate_null_values, vector state, bool correlated_left); diff --git a/src/duckdb/src/main/capi/v1/cast/utils-c.cpp b/src/duckdb/src/main/capi/v1/cast/utils-c.cpp index 321314ff4..d87a2eced 100644 --- a/src/duckdb/src/main/capi/v1/cast/utils-c.cpp +++ b/src/duckdb/src/main/capi/v1/cast/utils-c.cpp @@ -84,6 +84,10 @@ bool CanUseDeprecatedFetch(duckdb_result *result, idx_t col, idx_t row) { if (col >= result->deprecated_column_count || row >= result->deprecated_row_count) { return false; } + if (!result->deprecated_columns[col].deprecated_nullmask) { + // the column was not translated, e.g. because an earlier column failed to materialize + return false; + } return true; } diff --git a/src/duckdb/src/main/capi/v1/result-c.cpp b/src/duckdb/src/main/capi/v1/result-c.cpp index 2d8c7ec89..38933d9c3 100644 --- a/src/duckdb/src/main/capi/v1/result-c.cpp +++ b/src/duckdb/src/main/capi/v1/result-c.cpp @@ -184,6 +184,10 @@ duckdb_state deprecated_duckdb_translate_column(QueryResult &result, duckdb_colu } // then write the data switch (result.GetTypes()[col].id()) { + case LogicalTypeId::SQLNULL: + // every value of a SQLNULL column is NULL, which the nullmask already reflects - zero the data + memset(column->deprecated_data, 0, type_size * row_count); + break; case LogicalTypeId::BOOLEAN: WriteData(column, collection, column_ids); break; diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index f7e03bb9b..a7f4e34ce 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -195,6 +195,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), 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 756888a55..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 } @@ -235,8 +245,11 @@ bool HTTPRetryBudget::TryParseRetryAfterMs(const string &retry_after, uint64_t & delay_ms = seconds > MAX_BACKOFF_MS / 1000 ? MAX_BACKOFF_MS : seconds * 1000; return true; } + StrpTimeFormat::ParseResult parsed; timestamp_t target; - if (!RetryAfterDateFormat().TryParseTimestamp(value.c_str(), value.size(), target)) { + // The timestamp parser accepts the words epoch, infinity and -infinity, which are not HTTP-dates. + if (!RetryAfterDateFormat().Parse(value.c_str(), value.size(), parsed) || parsed.is_special || + !parsed.TryToTimestamp(target)) { return false; } const auto now_ms = Timestamp::GetEpochMs(Timestamp::GetCurrentTimestamp()); @@ -334,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; @@ -344,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++; @@ -356,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 cda55b22b..d58a86b11 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -573,12 +573,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 client_context = FileOpener::TryGetClientContext(opener); if (client_context) { logger = client_context->logger; } + if (client_context) { + // A session's own value wins over the database's + retry_quota_throttled = Settings::Get(*client_context); + retry_throttled_wait_ms = Settings::Get(*client_context); + } } unique_ptr HTTPUtil::InitializeParameters(DatabaseInstance &db, const string &url) { diff --git a/src/duckdb/src/main/secret/secret_storage.cpp b/src/duckdb/src/main/secret/secret_storage.cpp index 50eb6ff9e..924de1d7c 100644 --- a/src/duckdb/src/main/secret/secret_storage.cpp +++ b/src/duckdb/src/main/secret/secret_storage.cpp @@ -131,25 +131,27 @@ SecretMatch SecretStorage::SelectBestMatch(SecretEntry &secret_entry, const stri unique_ptr CatalogSetSecretStorage::StoreSecret(unique_ptr secret, OnCreateConflict on_conflict, optional_ptr transaction) { - if (secrets->GetEntry(GetTransactionOrDefault(transaction), secret->GetName())) { + lock_guard guard(store_lock); + auto secret_name = secret->GetName(); + auto existing = secrets->GetEntry(GetTransactionOrDefault(transaction), secret_name); + if (existing) { if (on_conflict == OnCreateConflict::ERROR_ON_CONFLICT) { string persist_string = persistent ? "Persistent" : "Temporary"; string storage_string = persistent ? " in secret storage '" + storage_name + "'" : ""; - throw InvalidInputException("%s secret with name %s already exists%s!", persist_string, secret->GetName(), + throw InvalidInputException("%s secret with name %s already exists%s!", persist_string, secret_name, storage_string); } else if (on_conflict == OnCreateConflict::IGNORE_ON_CONFLICT) { return nullptr; - } else if (on_conflict == OnCreateConflict::ALTER_ON_CONFLICT) { + } else if (on_conflict != OnCreateConflict::REPLACE_ON_CONFLICT) { throw InternalException("unknown OnCreateConflict found while registering secret"); - } else if (on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT) { - secrets->DropEntry(GetTransactionOrDefault(transaction), secret->GetName(), true, true); } } - // Call write function + // the secret is written completely before the catalog changes, so a failed write leaves the catalog as it was WriteSecret(*secret, on_conflict); - - auto secret_name = secret->GetName(); + if (existing) { + secrets->DropEntry(GetTransactionOrDefault(transaction), secret_name, true, true); + } auto secret_entry = make_uniq(std::move(secret), Catalog::GetSystemCatalog(db)); secret_entry->temporary = !persistent; secret_entry->secret->storage_mode = storage_name; @@ -174,6 +176,7 @@ vector CatalogSetSecretStorage::AllSecrets(optional_ptr transaction) { + lock_guard guard(store_lock); auto entry = secrets->GetEntry(GetTransactionOrDefault(transaction), Identifier(name)); if (!entry) { if (on_entry_not_found == OnEntryNotFound::THROW_EXCEPTION) { @@ -322,7 +325,7 @@ static void WriteSecretFileToDisk(FileSystem &fs, const string &path, const Base auto open_flags = FileFlags::FILE_FLAGS_WRITE; // Ensure we are writing to a private file with 600 permission open_flags |= FileFlags::FILE_FLAGS_PRIVATE; - // Ensure we overwrite anything that may have been placed there since our delete above + // Create the file, which must not exist yet open_flags |= FileFlags::FILE_FLAGS_FILE_CREATE_NEW; auto file_writer = BufferedFileWriter(fs, path, open_flags); @@ -332,7 +335,9 @@ static void WriteSecretFileToDisk(FileSystem &fs, const string &path, const Base secret.Serialize(serializer); serializer.End(); - file_writer.Flush(); + // a file system can report a failed write only when the file is synced or closed + file_writer.Sync(); + file_writer.Close(); } struct SecretNameEscape { @@ -401,27 +406,31 @@ void LocalFileSecretStorage::WriteSecret(const BaseSecret &secret, OnCreateConfl } auto &secret_name = secret.GetName(); - string file_path = fs.JoinPath(secret_path, SecretFileName(secret_name.GetIdentifierName())); - // the file of this secret, which can be a file written before names were escaped - string existing_path = files->Get(secret_name); - string other_secret; - if (files->TryGetOtherSecretAt(file_path, secret_name, other_secret)) { - throw IOException("Failed to write the file '%s' of the secret \"%s\": the file belongs to the secret \"%s\"", - file_path, secret_name.GetIdentifierName(), other_secret); + // a replaced secret keeps its file, which can predate escaped names, and a new secret gets its escaped name + string file_path = files->Get(secret_name); + if (file_path.empty()) { + file_path = fs.JoinPath(secret_path, SecretFileName(secret_name.GetIdentifierName())); + string other_secret; + if (files->TryGetOtherSecretAt(file_path, secret_name, other_secret)) { + throw IOException( + "Failed to write the file '%s' of the secret \"%s\": the file belongs to the secret \"%s\"", file_path, + secret_name.GetIdentifierName(), other_secret); + } } string temp_path = file_path + ".tmp-" + UUID::ToString(UUID::GenerateRandomUUID()); - // If persistent file already exists remove - if (!existing_path.empty()) { - fs.TryRemoveFile(existing_path); + // the complete file is renamed over the secret's file in one step, so a crash leaves the old file or the new one + try { + WriteSecretFileToDisk(fs, temp_path, secret); + fs.MoveFile(temp_path, file_path); + } catch (...) { + // the secret is not stored, so the temporary file goes, and its error cannot replace the one being reported + try { + fs.TryRemoveFile(temp_path); + } catch (...) { // NOLINT + } + throw; } - fs.TryRemoveFile(file_path); - // If temporary file already exists remove - fs.TryRemoveFile(temp_path); - - WriteSecretFileToDisk(fs, temp_path, secret); - - fs.MoveFile(temp_path, file_path); files->Set(secret_name, file_path); } diff --git a/src/duckdb/src/optimizer/filter_pushdown.cpp b/src/duckdb/src/optimizer/filter_pushdown.cpp index d262b32a9..7317b9ea1 100644 --- a/src/duckdb/src/optimizer/filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/filter_pushdown.cpp @@ -137,7 +137,7 @@ unique_ptr FilterPushdown::Rewrite(unique_ptr 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 +272,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 +303,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 +316,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..5eba5a7ea 100644 --- a/src/duckdb/src/optimizer/join_elimination.cpp +++ b/src/duckdb/src/optimizer/join_elimination.cpp @@ -29,6 +29,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; 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..86c354fae 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp @@ -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 21009431e..2c86e97f1 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp @@ -13,9 +13,9 @@ unique_ptr FilterPushdown::PushdownSemiAntiJoin(unique_ptrCast(); // push all current filters down the left side - op->children[0] = Rewrite(std::move(op->children[0])); + RewriteChild(*op, 0); FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); - op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); + 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/rule/struct_extract_struct_pack_folding.cpp b/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp index b74ae83fc..ab71037ed 100644 --- a/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp +++ b/src/duckdb/src/optimizer/rule/struct_extract_struct_pack_folding.cpp @@ -36,7 +36,10 @@ unique_ptr StructExtractStructPackFoldingRule::Apply(LogicalOperator } // struct_extract(struct_pack(e0, .., en), ki) is equivalent to ei auto result = std::move(packed_children[extract_data.index]); - return BoundCastExpression::AddCastToType(GetContext(), std::move(result), extract.Function().GetReturnType()); + auto &return_type = extract.GetReturnType(); + // AddCastToType skips the cast when only the collation differs - keep the collation of the extract + auto cast = BoundCastExpression::AddCastToType(GetContext(), std::move(result), return_type); + return Expression::PreserveReturnType(return_type, std::move(cast)); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index 4a2db83f6..588c01c67 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -959,6 +959,8 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo } reference op = *window.children[0]; + // Only a single cast per column can be re-applied, so a cast chain over several projections is not recreatable + vector column_is_cast(projections.size(), false); // Traverse projections to a single table scan while (!op.get().children.empty()) { @@ -979,6 +981,12 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo // cannot reconstruct. Fall back to carrying the computed value through the aggregate instead. return false; } + if (BoundCastExpression::IsCast(*projection.expressions[projection_idx])) { + if (column_is_cast[i]) { + return false; + } + column_is_cast[i] = true; + } if (!ExtractSingleBinding(&projection.expressions[projection_idx], projections[i])) { return false; } diff --git a/src/duckdb/src/parallel/executor.cpp b/src/duckdb/src/parallel/executor.cpp index 81819b85a..d9c38688b 100644 --- a/src/duckdb/src/parallel/executor.cpp +++ b/src/duckdb/src/parallel/executor.cpp @@ -651,6 +651,11 @@ idx_t Executor::GetPipelinesProgress(ProgressData &progress) { // LCOV_EXCL_STAR progress.total = 0; idx_t count_invalid = 0; for (auto &pipeline : pipelines) { + if (pipeline->GetSource()->type == PhysicalOperatorType::RESULT_COLLECTOR) { + // this pipeline only holds the result collector as the root of the plan: it never runs, so including it + // would add a row that never completes to the total + continue; + } ProgressData p; if (!pipeline->GetProgress(p)) { count_invalid++; diff --git a/src/duckdb/src/parallel/scan_read_ahead.cpp b/src/duckdb/src/parallel/scan_read_ahead.cpp index 1d0c7506e..a88f652d4 100644 --- a/src/duckdb/src/parallel/scan_read_ahead.cpp +++ b/src/duckdb/src/parallel/scan_read_ahead.cpp @@ -71,6 +71,8 @@ class ReadAheadIOTask : public BaseExecutorTask { completion->AddIOTask(); } ~ReadAheadIOTask() override { + // release the task's resources before waking the scan, they may outlive the database otherwise + task.reset(); // If we are done we decrement the pending completion->FinishIOTask(); } @@ -83,6 +85,8 @@ class ReadAheadIOTask : public BaseExecutorTask { // recording the error through the read-ahead also wakes the threads waiting for progress read_ahead.PushError(ErrorData(ex)); } + // release the task's resources while the executor still counts this task as running + task.reset(); } private: diff --git a/src/duckdb/src/parser/expression/window_expression.cpp b/src/duckdb/src/parser/expression/window_expression.cpp index b6d8f84f1..31f0ddb91 100644 --- a/src/duckdb/src/parser/expression/window_expression.cpp +++ b/src/duckdb/src/parser/expression/window_expression.cpp @@ -12,11 +12,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; @@ -105,14 +107,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); @@ -174,8 +171,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/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index 4b04ca531..7650b0ca1 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -613,8 +613,6 @@ static const char *const PEG_RULE_NAMES[] = { "SingleExpression", "Expression", "ColumnDefaultExpr", - "LambdaArrowExpression", - "SingleArrowPair", "LogicalOrExpression", "LogicalOrExpressionTail", "ColDefOrExpr", @@ -686,6 +684,12 @@ static const char *const PEG_RULE_NAMES[] = { "OtherOperatorTail", "AnyAllSubqueryTail", "OtherOperatorExpressionTail", + "SingleArrowTail", + "SingleArrowBody", + "ArrowChainBody", + "ArrowChainTail", + "DoubleArrowTail", + "ArrowFullBody", "OtherOperator", "AnyAllParsedOperator", "NamedOtherOperator", 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 1bfa4bb87..f3515c9c7 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp @@ -121,7 +121,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"); @@ -167,13 +166,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 63547a0ed..c28b5b52a 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_expression.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_expression.cpp @@ -575,25 +575,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, @@ -1341,6 +1322,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, @@ -1351,6 +1342,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; @@ -1455,6 +1453,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 67288f13f..9bf29089e 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -1667,12 +1667,6 @@ static const TransformFrameOps EXPRESSION_OPS = {"Expression", &PEGTransformerFa static const TransformFrameOps COLUMN_DEFAULT_EXPR_OPS = {"ColumnDefaultExpr", &PEGTransformerFactory::InitializeColumnDefaultExprTrampoline, &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline}; -static const TransformFrameOps LAMBDA_ARROW_EXPRESSION_OPS = { - "LambdaArrowExpression", &PEGTransformerFactory::InitializeLambdaArrowExpressionTrampoline, - &PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline}; -static const TransformFrameOps SINGLE_ARROW_PAIR_OPS = {"SingleArrowPair", - &PEGTransformerFactory::InitializeSingleArrowPairTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowPairTrampoline}; static const TransformFrameOps LOGICAL_OR_EXPRESSION_OPS = { "LogicalOrExpression", &PEGTransformerFactory::InitializeLogicalOrExpressionTrampoline, &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline}; @@ -1869,6 +1863,24 @@ static const TransformFrameOps ANY_ALL_SUBQUERY_TAIL_OPS = { static const TransformFrameOps OTHER_OPERATOR_EXPRESSION_TAIL_OPS = { "OtherOperatorExpressionTail", &PEGTransformerFactory::InitializeOtherOperatorExpressionTailTrampoline, &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline}; +static const TransformFrameOps SINGLE_ARROW_TAIL_OPS = {"SingleArrowTail", + &PEGTransformerFactory::InitializeSingleArrowTailTrampoline, + &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline}; +static const TransformFrameOps SINGLE_ARROW_BODY_OPS = {"SingleArrowBody", + &PEGTransformerFactory::InitializeSingleArrowBodyTrampoline, + &PEGTransformerFactory::FinalizeSingleArrowBodyTrampoline}; +static const TransformFrameOps ARROW_CHAIN_BODY_OPS = {"ArrowChainBody", + &PEGTransformerFactory::InitializeArrowChainBodyTrampoline, + &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline}; +static const TransformFrameOps ARROW_CHAIN_TAIL_OPS = {"ArrowChainTail", + &PEGTransformerFactory::InitializeArrowChainTailTrampoline, + &PEGTransformerFactory::FinalizeArrowChainTailTrampoline}; +static const TransformFrameOps DOUBLE_ARROW_TAIL_OPS = {"DoubleArrowTail", + &PEGTransformerFactory::InitializeDoubleArrowTailTrampoline, + &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline}; +static const TransformFrameOps ARROW_FULL_BODY_OPS = {"ArrowFullBody", + &PEGTransformerFactory::InitializeArrowFullBodyTrampoline, + &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline}; static const TransformFrameOps OTHER_OPERATOR_OPS = {"OtherOperator", &PEGTransformerFactory::InitializeOtherOperatorTrampoline, &PEGTransformerFactory::FinalizeOtherOperatorTrampoline}; @@ -3689,8 +3701,6 @@ const case_insensitive_map_t &PEGTransformerFactory:: {"SingleExpression", &SINGLE_EXPRESSION_OPS}, {"Expression", &EXPRESSION_OPS}, {"ColumnDefaultExpr", &COLUMN_DEFAULT_EXPR_OPS}, - {"LambdaArrowExpression", &LAMBDA_ARROW_EXPRESSION_OPS}, - {"SingleArrowPair", &SINGLE_ARROW_PAIR_OPS}, {"LogicalOrExpression", &LOGICAL_OR_EXPRESSION_OPS}, {"LogicalOrExpressionTail", &LOGICAL_OR_EXPRESSION_TAIL_OPS}, {"ColDefOrExpr", &COL_DEF_OR_EXPR_OPS}, @@ -3761,6 +3771,12 @@ const case_insensitive_map_t &PEGTransformerFactory:: {"OtherOperatorTail", &OTHER_OPERATOR_TAIL_OPS}, {"AnyAllSubqueryTail", &ANY_ALL_SUBQUERY_TAIL_OPS}, {"OtherOperatorExpressionTail", &OTHER_OPERATOR_EXPRESSION_TAIL_OPS}, + {"SingleArrowTail", &SINGLE_ARROW_TAIL_OPS}, + {"SingleArrowBody", &SINGLE_ARROW_BODY_OPS}, + {"ArrowChainBody", &ARROW_CHAIN_BODY_OPS}, + {"ArrowChainTail", &ARROW_CHAIN_TAIL_OPS}, + {"DoubleArrowTail", &DOUBLE_ARROW_TAIL_OPS}, + {"ArrowFullBody", &ARROW_FULL_BODY_OPS}, {"OtherOperator", &OTHER_OPERATOR_OPS}, {"AnyAllParsedOperator", &ANY_ALL_PARSED_OPERATOR_OPS}, {"NamedOtherOperator", &NAMED_OTHER_OPERATOR_OPS}, @@ -15669,7 +15685,7 @@ void PEGTransformerFactory::InitializeExpressionTrampoline(PEGTransformer &trans GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LambdaArrowExpression), list_pr.GetChild(0)}, 0); + process.PushChild({transformer.GetRule(PEGRuleId::LogicalOrExpression), list_pr.GetChild(0)}, 0); } arena_ptr @@ -15693,68 +15709,6 @@ PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } -void PEGTransformerFactory::InitializeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &repeat_opt = list_pr.GetChild(1).Cast(); - idx_t dynamic_child_count = 0; - if (repeat_opt.HasResult()) { - auto &repeat_pr = repeat_opt.GetResult().Cast(); - auto repeat_children = repeat_pr.GetChildren(); - dynamic_child_count = repeat_children.size(); - process.ReserveChildSlots(2 + dynamic_child_count - 1); - for (idx_t i = repeat_children.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({transformer.GetRule(PEGRuleId::SingleArrowPair), repeat_children[child_idx].get()}, - 1 + child_idx); - } - } else { - process.ReserveChildSlots(2 - 1); - } - process.PushChild({transformer.GetRule(PEGRuleId::LogicalOrExpression), list_pr.GetChild(0)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeLambdaArrowExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - 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)); -} - -void PEGTransformerFactory::InitializeSingleArrowPairTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - process.ReserveChildSlots(1); - process.PushChild({transformer.GetRule(PEGRuleId::LogicalOrExpression), list_pr.GetChild(1)}, 0); -} - -arena_ptr -PEGTransformerFactory::FinalizeSingleArrowPairTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto logical_or_expression = process.TakeResult>(0); - auto result = TransformSingleArrowPair(transformer, std::move(logical_or_expression)); - return transformer.MakeResult>(std::move(result)); -} - void PEGTransformerFactory::InitializeLogicalOrExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); @@ -17228,6 +17182,125 @@ PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline(PEGTransfor return transformer.MakeResult(std::move(result)); } +void PEGTransformerFactory::InitializeSingleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + process.ReserveChildSlots(1); + process.PushChild({transformer.GetRule(PEGRuleId::SingleArrowBody), list_pr.GetChild(1)}, 0); +} + +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)); +} + +void PEGTransformerFactory::InitializeSingleArrowBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + auto &choice_pr = list_pr.Child(0); + auto &choice_result = choice_pr.GetResult(); + process.ReserveChildSlots(1); + auto child_rule = choice_result.GetRule(); + auto has_transform_process = child_rule && child_rule->transform_process; + if (!has_transform_process) { + throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); + } + process.PushChild({*child_rule, choice_result}, 0); +} + +arena_ptr +PEGTransformerFactory::FinalizeSingleArrowBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto result = process.TakeResult(0); + return transformer.MakeResult(std::move(result)); +} + +void PEGTransformerFactory::InitializeArrowChainBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + auto &repeat_pr = list_pr.GetChild(1).Cast(); + auto repeat_children = repeat_pr.GetChildren(); + auto dynamic_child_count = repeat_children.size(); + process.ReserveChildSlots(2 + dynamic_child_count - 1); + for (idx_t i = repeat_children.size(); i > 0; i--) { + auto child_idx = i - 1; + process.PushChild({transformer.GetRule(PEGRuleId::ArrowChainTail), repeat_children[child_idx].get()}, + 1 + child_idx); + } + process.PushChild({transformer.GetRule(PEGRuleId::BitwiseExpression), list_pr.GetChild(0)}, 0); +} + +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)); +} + +void PEGTransformerFactory::InitializeArrowChainTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + auto &choice_pr = list_pr.Child(0); + auto &choice_result = choice_pr.GetResult(); + process.ReserveChildSlots(1); + auto child_rule = choice_result.GetRule(); + auto has_transform_process = child_rule && child_rule->transform_process; + if (!has_transform_process) { + throw InternalException("No transform process registered for rule '%s'", choice_result.Name()); + } + process.PushChild({*child_rule, choice_result}, 0); +} + +arena_ptr +PEGTransformerFactory::FinalizeArrowChainTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto result = process.TakeResult(0); + return transformer.MakeResult(std::move(result)); +} + +void PEGTransformerFactory::InitializeDoubleArrowTailTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + process.ReserveChildSlots(1); + process.PushChild({transformer.GetRule(PEGRuleId::BitwiseExpression), list_pr.GetChild(1)}, 0); +} + +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)); +} + +void PEGTransformerFactory::InitializeArrowFullBodyTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + process.ReserveChildSlots(1); + process.PushChild({transformer.GetRule(PEGRuleId::LogicalOrExpression), list_pr.GetChild(0)}, 0); +} + +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)); +} + void PEGTransformerFactory::InitializeOtherOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); diff --git a/src/duckdb/src/parser/peg/transformer/transform_select.cpp b/src/duckdb/src/parser/peg/transformer/transform_select.cpp index 116e2f354..b7b7e3739 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_select.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_select.cpp @@ -1044,37 +1044,49 @@ void PEGTransformerFactory::InitializeWithClauseTrampoline(PEGTransformer &trans GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); auto with_statement_list = ExtractParseResultsFromList(list_pr.Child(2)); - process.ReserveChildSlots(with_statement_list.size()); - for (idx_t i = with_statement_list.size(); i > 0; i--) { - auto child_idx = i - 1; - process.PushChild({with_statement_list[child_idx].get()}, child_idx); - } + auto entry_count = with_statement_list.size(); + // the last slot holds the CTE map that is built up while the CTEs are transformed + process.ReserveChildSlots(entry_count + 1); + process.SetChildResult(entry_count, transformer.MakeResult(CommonTableExpressionMap())); + // earlier CTEs are visible while transforming later ones (e.g. for PIVOT enum extraction) + transformer.stored_cte_map.push_back(process.GetResult(entry_count)); + process.manual_state = 0; + process.PushChild({with_statement_list[0].get()}, 0); } arena_ptr PEGTransformerFactory::FinalizeWithClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto &list_pr = process.parse_result.Cast(); bool is_recursive = list_pr.Child(1).HasResult(); - CommonTableExpressionMap result; - for (idx_t entry_idx = 0; entry_idx < process.child_results.size(); entry_idx++) { - auto with_entry = process.TakeResult>>(entry_idx); - if (is_recursive) { - auto &query_node = with_entry.second->query_node; - if (!query_node) { - throw ParserException("Recursive CTEs with DML statements are not supported"); - } - ValidateRecursiveCTEQueryNode(*query_node); - query_node = ToRecursiveCTE(std::move(query_node), with_entry.first, with_entry.second->aliases, - with_entry.second->key_targets); + auto entry_count = process.child_results.size() - 1; + auto &result = process.GetResult(entry_count); + + auto entry_idx = process.manual_state; + auto with_entry = process.TakeResult>>(entry_idx); + if (is_recursive) { + auto &query_node = with_entry.second->query_node; + if (!query_node) { + throw ParserException("Recursive CTEs with DML statements are not supported"); } - auto &cte_name = with_entry.first; - auto it = result.map.find(cte_name); - if (it != result.map.end()) { - throw ParserException("Duplicate CTE name %s", cte_name); - } - result.map.insert(with_entry.first, std::move(with_entry.second)); + ValidateRecursiveCTEQueryNode(*query_node); + query_node = ToRecursiveCTE(std::move(query_node), with_entry.first, with_entry.second->aliases, + with_entry.second->key_targets); + } + auto &cte_name = with_entry.first; + auto it = result.map.find(cte_name); + if (it != result.map.end()) { + throw ParserException("Duplicate CTE name %s", cte_name); + } + result.map.insert(with_entry.first, std::move(with_entry.second)); + + if (entry_idx + 1 < entry_count) { + process.manual_state = entry_idx + 1; + auto with_statement_list = ExtractParseResultsFromList(list_pr.Child(2)); + process.PushChild({with_statement_list[entry_idx + 1].get()}, entry_idx + 1); + return nullptr; } - return transformer.MakeResult(std::move(result)); + transformer.stored_cte_map.pop_back(); + return transformer.MakeResult(process.TakeResult(entry_count)); } pair> diff --git a/src/duckdb/src/parser/query_node/insert_query_node.cpp b/src/duckdb/src/parser/query_node/insert_query_node.cpp index 05dfe39d0..72a5b3c64 100644 --- a/src/duckdb/src/parser/query_node/insert_query_node.cpp +++ b/src/duckdb/src/parser/query_node/insert_query_node.cpp @@ -58,18 +58,18 @@ string InsertQueryNode::ToString() const { } if (!or_replace_shorthand_set && on_conflict_info) { auto &conflict_info = *on_conflict_info; - result += " ON CONFLICT "; + result += " ON CONFLICT"; // (optional) conflict target if (!conflict_info.indexed_columns.empty()) { - result += "("; + result += " ("; auto &cols = conflict_info.indexed_columns; for (auto it = cols.begin(); it != cols.end();) { - result += StringUtil::Lower(it->GetIdentifierName()); + result += SQLIdentifier(*it); if (++it != cols.end()) { result += ", "; } } - result += " )"; + result += ")"; } // (optional) where clause @@ -79,18 +79,8 @@ string InsertQueryNode::ToString() const { result += " " + OnConflictInfo::ActionToString(conflict_info.action_type); if (conflict_info.set_info) { D_ASSERT(conflict_info.action_type == OnConflictAction::UPDATE); - result += " SET "; auto &set_info = *conflict_info.set_info; - D_ASSERT(set_info.columns.size() == set_info.expressions.size()); - // SET = - for (idx_t i = 0; i < set_info.columns.size(); i++) { - auto &column = set_info.columns[i]; - auto &expr = set_info.expressions[i]; - if (i) { - result += ", "; - } - result += StringUtil::Lower(column.GetIdentifierName()) + " = " + expr->ToString(); - } + result += " " + set_info.ToString(); // (optional) where clause if (set_info.condition) { result += " WHERE " + set_info.condition->ToString(); diff --git a/src/duckdb/src/parser/query_node/merge_query_node.cpp b/src/duckdb/src/parser/query_node/merge_query_node.cpp index 5dd8f466f..c33e90faf 100644 --- a/src/duckdb/src/parser/query_node/merge_query_node.cpp +++ b/src/duckdb/src/parser/query_node/merge_query_node.cpp @@ -37,7 +37,7 @@ string MergeQueryNode::ToString() const { if (c > 0) { result += ", "; } - result += using_columns[c].GetIdentifierName(); + result += SQLIdentifier(using_columns[c]); } result += ")"; } diff --git a/src/duckdb/src/parser/tableref/delimgetref.cpp b/src/duckdb/src/parser/tableref/delimgetref.cpp index 71910ff3b..ec6952122 100644 --- a/src/duckdb/src/parser/tableref/delimgetref.cpp +++ b/src/duckdb/src/parser/tableref/delimgetref.cpp @@ -13,7 +13,9 @@ bool DelimGetRef::Equals(const TableRef &other) const { } unique_ptr DelimGetRef::Copy() { - return make_uniq(types); + auto copy = make_uniq(types); + CopyProperties(*copy); + return std::move(copy); } void DelimGetRef::Serialize(Serializer &serializer) const { diff --git a/src/duckdb/src/parser/tableref/emptytableref.cpp b/src/duckdb/src/parser/tableref/emptytableref.cpp index 0107aac9c..09eab0370 100644 --- a/src/duckdb/src/parser/tableref/emptytableref.cpp +++ b/src/duckdb/src/parser/tableref/emptytableref.cpp @@ -11,7 +11,9 @@ bool EmptyTableRef::Equals(const TableRef &other) const { } unique_ptr EmptyTableRef::Copy() { - return make_uniq(); + auto copy = make_uniq(); + CopyProperties(*copy); + return std::move(copy); } } // namespace duckdb diff --git a/src/duckdb/src/parser/tableref/joinref.cpp b/src/duckdb/src/parser/tableref/joinref.cpp index b4621cbb0..5f51e1b13 100644 --- a/src/duckdb/src/parser/tableref/joinref.cpp +++ b/src/duckdb/src/parser/tableref/joinref.cpp @@ -119,7 +119,6 @@ unique_ptr JoinRef::Copy() { } copy->type = type; copy->ref_type = ref_type; - copy->alias = alias; copy->using_columns = using_columns; copy->delim_flipped = delim_flipped; for (auto &col : duplicate_eliminated_columns) { @@ -132,6 +131,7 @@ unique_ptr JoinRef::Copy() { copy->nearest_count = nearest_count; copy->nearest_order_type = nearest_order_type; copy->nearest_approx = nearest_approx; + CopyProperties(*copy); return std::move(copy); } diff --git a/src/duckdb/src/parser/tableref/pivotref.cpp b/src/duckdb/src/parser/tableref/pivotref.cpp index f8197ba98..018ffc730 100644 --- a/src/duckdb/src/parser/tableref/pivotref.cpp +++ b/src/duckdb/src/parser/tableref/pivotref.cpp @@ -340,7 +340,7 @@ unique_ptr PivotRef::Copy() { copy->groups = groups; copy->column_name_alias = column_name_alias; copy->include_nulls = include_nulls; - copy->alias = alias; + CopyProperties(*copy); return std::move(copy); } diff --git a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp index e73429c7d..802ddf288 100644 --- a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp @@ -287,6 +287,15 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu } } + // EXPORT_STATE exports the state of the underlying (non-distinct) aggregate: it does not carry the set of values + // seen so far, so combining exported states of a DISTINCT aggregate would count repeated values again + if (aggr.Distinct() && aggr.ExportState()) { + throw BinderException(aggr, + "EXPORT_STATE is not supported for DISTINCT aggregates: the exported state does not " + "retain the set of distinct values, so combining states would produce incorrect " + "results"); + } + // Bind the function FunctionBinder function_binder(binder); auto aggregate = diff --git a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp index 3d4b2bcd8..237dac28d 100644 --- a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp @@ -262,7 +262,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/query_node/plan_select_node.cpp b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp index bffb3f123..07c84f370 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp @@ -41,6 +41,10 @@ bool Binder::DebugAggregateStateExportVerify(BoundSelectNode &statement, unique_ // already an aggregate state export - skip verification return false; } + if (aggr->Cast().IsDistinct()) { + // the exported state of a DISTINCT aggregate cannot be re-bound: EXPORT_STATE rejects DISTINCT + return false; + } } // we transform a query like "SELECT grp, SUM(col) FROM tbl GROUP BY grp" into diff --git a/src/duckdb/src/planner/column_qualifier.cpp b/src/duckdb/src/planner/column_qualifier.cpp index 35d55c4c0..621b11c5a 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 910006fd0..36dc1d6f9 100644 --- a/src/duckdb/src/planner/expression/bound_cast_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_cast_expression.cpp @@ -308,8 +308,11 @@ static bool NestedCastCanThrow(const LogicalType &source_type, const LogicalType } return BoundCastExpression::CastCanThrow(ListOrArrayChildType(source_type), ListOrArrayChildType(target_type), false); + // TUPLE is an unnamed STRUCT - same physical layout, positional child matching, and the same shared struct + // cast operators, so it can throw exactly when a STRUCT of the same children can. + case LogicalTypeId::TUPLE: case LogicalTypeId::STRUCT: { - if (target_type.id() != LogicalTypeId::STRUCT) { + if (target_type.id() != LogicalTypeId::STRUCT && target_type.id() != LogicalTypeId::TUPLE) { return true; } // Pair the fields as the cast executes them: positionally for unnamed structs, by name otherwise. diff --git a/src/duckdb/src/planner/expression/bound_constant_expression.cpp b/src/duckdb/src/planner/expression/bound_constant_expression.cpp index 41f8a477a..5e558567c 100644 --- a/src/duckdb/src/planner/expression/bound_constant_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_constant_expression.cpp @@ -32,8 +32,17 @@ string BoundConstantExpression::ToString() const { //! Two constants are the same expression if their values have the same representation. VARIANT values compare by //! meaning - 1::TINYINT and 1::INTEGER are equal - but as constants they are different: variant_typeof tells them -//! apart, and they hash differently. Vectors compare a VARIANT as the STRUCT it is stored as. +//! apart, and they hash differently. Vectors compare a VARIANT as the STRUCT it is stored as. INTERVALs that are +//! only not distinct after normalization (e.g. INTERVAL 1 MONTH vs INTERVAL 30 DAY) can have different effects in +//! expressions - DATE '2008-05-17' + INTERVAL 1 MONTH is 2008-06-17, but + INTERVAL 30 DAY is 2008-06-16 - so +//! they compare by their raw (months, days, micros) fields, not by normalized equality. static bool SameRepresentation(const Value &left, const Value &right) { + if (left.type().id() == LogicalTypeId::INTERVAL) { + if (left.IsNull() || right.IsNull()) { + return left.IsNull() == right.IsNull(); + } + return left.GetValueUnsafe().SameFields(right.GetValueUnsafe()); + } if (!TypeVisitor::Contains(left.type(), LogicalTypeId::VARIANT)) { return !ValueOperations::DistinctFrom(left, right); } @@ -47,11 +56,21 @@ bool BoundConstantExpression::Equals(const BaseExpression &other_p) const { return false; } auto &other = other_p.Cast(); - return value.type() == other.value.type() && SameRepresentation(value, other.value); + if (value.type() != other.value.type()) { + return false; + } + return SameRepresentation(value, other.value); } hash_t BoundConstantExpression::Hash() const { hash_t result = Expression::Hash(); + if (value.type().id() == LogicalTypeId::INTERVAL && !value.IsNull()) { + // Hash by the raw (months, days, micros) fields: Value::Hash normalizes first, which would put intervals + // that are only equal after normalization in the same bucket and make Equals the deciding factor + auto interval = value.GetValueUnsafe(); + return CombineHash(duckdb::Hash(interval.months) ^ duckdb::Hash(interval.days) ^ duckdb::Hash(interval.micros), + result); + } return CombineHash(value.Hash(), result); } diff --git a/src/duckdb/src/planner/sql_export/sql_export_dml.cpp b/src/duckdb/src/planner/sql_export/sql_export_dml.cpp index 631ad574c..591402bc8 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_dml.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_dml.cpp @@ -321,6 +321,11 @@ static LogicalPlanSQLExportResult ExportMergeNode(LogicalMergeInto &op, LogicalP set_info->columns.push_back(op.table.GetColumns().GetColumn(bound_action->columns[i]).Name()); set_info->expressions.push_back(std::move(value.GetValue())); } + if (set_info->columns.empty()) { + // an update without assignments is expressed as DO NOTHING + action->action_type = MergeActionType::MERGE_DO_NOTHING; + break; + } action->update_info = std::move(set_info); break; } diff --git a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp index c68bbe2a4..33ad90ec0 100644 --- a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp +++ b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp @@ -637,11 +637,44 @@ FlattenDependentJoins::AttachDelimToIndependentJoinLeft(unique_ptrGetColumnBindings(); + auto projection_index = binder.GenerateTableIndex(); + op.children[0] = LogicalProjection::CreateIdentity(projection_index, std::move(op.children[0])); + + BindingReplacementGraph replacements; + for (idx_t i = 0; i < old_left_bindings.size(); i++) { + replacements.Add(old_left_bindings[i], ColumnBinding(projection_index, ProjectionIndex(i))); + } + // The projection preserves the left layout, so positional projection maps remain valid. Only the join's own + // bindings move: the projection input keeps the original bindings so the deferred rewrite still finds them. + ColumnBindingRewrite::ApplyToOperatorBindings(op, replacements); + for (auto &binding : outer_state.bindings) { + binding = replacements.Resolve(binding); + } + outer_state.replacement_graph.Merge(replacements); +} + FlattenDependentJoins::UnnestingState FlattenDependentJoins::FinalizeDependentJoin(unique_ptr &plan, UnnestingState outer_state, const UnnestingState &right_state, DependentJoinOutput output) { auto &op = plan->Cast(); + MaterializeCorrelatedAggregateRewrites(op, outer_state); RewriteCorrelatedBindings(op, outer_state.bindings); vector> duplicate_eliminated_columns; diff --git a/src/duckdb/src/storage/metadata/metadata_manager.cpp b/src/duckdb/src/storage/metadata/metadata_manager.cpp index 58063aa06..6f7295f9e 100644 --- a/src/duckdb/src/storage/metadata/metadata_manager.cpp +++ b/src/duckdb/src/storage/metadata/metadata_manager.cpp @@ -236,8 +236,8 @@ MetadataPointer MetadataManager::FromDiskPointerInternal(unique_lock &blo auto entry = blocks.find(block_id); if (entry == blocks.end()) { // LCOV_EXCL_START - throw InternalException("Failed to load metadata pointer (id %llu, idx %llu, ptr %llu)\n", block_id, index, - pointer.block_pointer); + throw DataCorruptionException("Failed to load metadata pointer (id %llu, idx %llu, ptr %llu)\n", block_id, + index, pointer.block_pointer); } // LCOV_EXCL_STOP MetadataPointer result; result.block_index = UnsafeNumericCast(block_id); diff --git a/src/duckdb/src/storage/serialization/serialize_nodes.cpp b/src/duckdb/src/storage/serialization/serialize_nodes.cpp index bcf0d7215..1cf779197 100644 --- a/src/duckdb/src/storage/serialization/serialize_nodes.cpp +++ b/src/duckdb/src/storage/serialization/serialize_nodes.cpp @@ -435,6 +435,7 @@ Literal Literal::Deserialize(Deserializer &deserializer) { deserializer.ReadProperty(100, "kind", result.kind); deserializer.ReadPropertyWithDefault(101, "text", result.text); result.Verify(); + deserializer.CheckAllowed(result.kind); return result; } diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index f9cf9244e..3e3b1e751 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -268,10 +268,6 @@ bool StorageManager::WALStartCheckpoint(MetaBlockPointer meta_block, CheckpointO return false; } // start the checkpoint process around the WAL - if (GetWALSize() == 0) { - // no WAL - we don't need to do anything here - return false; - } // verify the main WAL is the active WAL currently if (wal->GetPath() != wal_path) { throw InternalException("Current WAL path \"%s\" does not match base WAL path \"%s\" in WALStartCheckpoint", diff --git a/src/duckdb/src/storage/table/row_id_column_data.cpp b/src/duckdb/src/storage/table/row_id_column_data.cpp index a285c42e4..a92de67b2 100644 --- a/src/duckdb/src/storage/table/row_id_column_data.cpp +++ b/src/duckdb/src/storage/table/row_id_column_data.cpp @@ -96,8 +96,8 @@ void RowIdColumnData::Filter(TransactionData transaction, idx_t vector_index, Co return; } - // Now apply the filter - ColumnSegment::FilterSelection(sel, result, filter_state, count, count); + // the selection indexes the whole vector, so the filter needs max_count as its scan count + ColumnSegment::FilterSelection(sel, result, filter_state, max_count, count); } void RowIdColumnData::Select(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result, diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index b8eebc5dc..1340451a2 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -120,7 +120,7 @@ class WriteAheadLogDeserializer { auto offset = stream.CurrentOffset(); auto file_size = stream.FileSize(); - if (offset + size > file_size) { + if (offset > file_size || size > file_size - offset) { throw SerializationException( "Corrupt WAL file: entry size exceeded remaining data in file at byte position %llu " "(found entry with size %llu bytes, file size %llu bytes)", @@ -144,6 +144,9 @@ class WriteAheadLogDeserializer { } if (state_p.wal_version == 3) { + if (!state_p.db.GetStorageManager().IsEncrypted()) { + throw IOException("Failed to read WAL: the WAL is marked as encrypted, but the database is not"); + } auto &database = state_p.db.GetDatabase(); //! Version 3 means that the WAL is encrypted //! For encryption, the length field remains plaintext @@ -180,7 +183,8 @@ class WriteAheadLogDeserializer { tag.SetSize(0); } - if (offset + nonce.size() + ciphertext_size + tag.size() > file_size) { + const auto trailer_size = nonce.size() + sizeof(uint64_t) + tag.size(); + if (offset > file_size || trailer_size > file_size - offset || size > file_size - offset - trailer_size) { throw SerializationException( "Corrupt Encrypted WAL file: entry size exceeded remaining data in file at byte position %llu " "(found entry with size %llu bytes, file size %llu bytes)", @@ -788,7 +792,7 @@ void WriteAheadLogDeserializer::ReplayEntry(WALType entry_type) { ReplayDropTrigger(); break; default: - throw InternalException("Invalid WAL entry type!"); + throw DataCorruptionException("Invalid WAL entry type %d - corrupt WAL?", static_cast(entry_type)); } } @@ -857,12 +861,27 @@ static QualifiedName ReplayQualifiedName(Catalog &catalog, const QualifiedName & return entry_name.WithCatalog(catalog.GetName()).WithName(name); } +//! The catalog information of a (checksum-valid) WAL entry can still be missing or of the wrong type +template +static T &CheckedCreateInfo(const unique_ptr &info, CatalogType expected_type) { + if (!info) { + throw DataCorruptionException("Corrupt WAL file: entry is missing its catalog information"); + } + if (info->type != expected_type) { + throw DataCorruptionException("Corrupt WAL file: entry carries catalog information of an unexpected type"); + } + return info->Cast(); +} + //===--------------------------------------------------------------------===// // Replay Table //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateTable() { auto entry = WALCreateTable::Deserialize(deserializer); auto info = std::move(entry.table); + if (!info) { + throw DataCorruptionException("Corrupt WAL file: entry is missing its catalog information"); + } if (DeserializeOnly()) { return; } @@ -955,7 +974,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()); @@ -1026,11 +1057,11 @@ void WriteAheadLogDeserializer::ReplayAlter() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateView() { auto wal_entry = WALCreateView::Deserialize(deserializer); - auto &entry = wal_entry.view; + auto &entry = CheckedCreateInfo(wal_entry.view, CatalogType::VIEW_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateView(context, entry->Cast()); + catalog.CreateView(context, entry); } void WriteAheadLogDeserializer::ReplayDropView() { @@ -1084,12 +1115,12 @@ void WriteAheadLogDeserializer::ReplayDropSchema() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateType() { auto wal_entry = WALCreateType::Deserialize(deserializer); - auto &info = wal_entry.type; - info->on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + auto &info = CheckedCreateInfo(wal_entry.type, CatalogType::TYPE_ENTRY); + info.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; if (DeserializeOnly()) { return; } - catalog.CreateType(context, info->Cast()); + catalog.CreateType(context, info); } void WriteAheadLogDeserializer::ReplayDropType() { @@ -1110,12 +1141,14 @@ void WriteAheadLogDeserializer::ReplayDropType() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateTrigger() { auto wal_entry = WALCreateTrigger::Deserialize(deserializer); - auto &info = wal_entry.trigger; - info->on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + auto &trigger_info = CheckedCreateInfo(wal_entry.trigger, CatalogType::TRIGGER_ENTRY); + trigger_info.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; if (DeserializeOnly()) { return; } - auto &trigger_info = info->Cast(); + if (!trigger_info.base_table) { + throw DataCorruptionException("Corrupt WAL file: trigger entry is missing its base table"); + } // the trigger lives in the same (possibly nested) schema as its base table auto &table = Catalog::GetEntry( context, ReplayQualifiedName(catalog, trigger_info.GetQualifiedName(), trigger_info.base_table->Table())); @@ -1150,12 +1183,12 @@ void WriteAheadLogDeserializer::ReplayDropTrigger() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateSequence() { auto wal_entry = WALCreateSequence::Deserialize(deserializer); - auto &entry = wal_entry.sequence; + auto &entry = CheckedCreateInfo(wal_entry.sequence, CatalogType::SEQUENCE_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateSequence(context, entry->Cast()); + catalog.CreateSequence(context, entry); } void WriteAheadLogDeserializer::ReplayDropSequence() { @@ -1192,12 +1225,12 @@ void WriteAheadLogDeserializer::ReplaySequenceValue() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateMacro() { auto wal_entry = WALCreateMacro::Deserialize(deserializer); - auto &entry = wal_entry.macro; + auto &entry = CheckedCreateInfo(wal_entry.macro, CatalogType::MACRO_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateFunction(context, entry->Cast()); + catalog.CreateFunction(context, entry); } void WriteAheadLogDeserializer::ReplayDropMacro() { @@ -1217,11 +1250,11 @@ void WriteAheadLogDeserializer::ReplayDropMacro() { //===--------------------------------------------------------------------===// void WriteAheadLogDeserializer::ReplayCreateTableMacro() { auto wal_entry = WALCreateTableMacro::Deserialize(deserializer); - auto &entry = wal_entry.table_macro; + auto &entry = CheckedCreateInfo(wal_entry.table_macro, CatalogType::TABLE_MACRO_ENTRY); if (DeserializeOnly()) { return; } - catalog.CreateFunction(context, entry->Cast()); + catalog.CreateFunction(context, entry); } void WriteAheadLogDeserializer::ReplayDropTableMacro() { @@ -1242,12 +1275,12 @@ void WriteAheadLogDeserializer::ReplayDropTableMacro() { void WriteAheadLogDeserializer::ReplayCreateIndex() { auto create_info = deserializer.ReadProperty>(101, "index_catalog_entry"); auto index_info = deserializer.ReadProperty(102, "index_storage_info"); + auto &info = CheckedCreateInfo(create_info, CatalogType::INDEX_ENTRY); ReplayIndexData(index_info); if (DeserializeOnly()) { return; } - auto &info = create_info->Cast(); // Ensure that the index type exists. if (info.index_type.empty()) { diff --git a/src/duckdb/third_party/fmt/include/fmt/format-inl.h b/src/duckdb/third_party/fmt/include/fmt/format-inl.h index b92c914b5..2dc5b6c4c 100644 --- a/src/duckdb/third_party/fmt/include/fmt/format-inl.h +++ b/src/duckdb/third_party/fmt/include/fmt/format-inl.h @@ -922,7 +922,7 @@ void fallback_format(Double d, buffer& buf, int& exp10) { upper = &upper_store; } denominator.assign_pow10(exp10); - denominator <<= 1; + denominator <<= shift; } else if (exp10 < 0) { numerator.assign_pow10(-exp10); lower.assign(numerator); diff --git a/src/duckdb/third_party/jemalloc/src/pages.c b/src/duckdb/third_party/jemalloc/src/pages.c index 1657fa811..2167e1f31 100644 --- a/src/duckdb/third_party/jemalloc/src/pages.c +++ b/src/duckdb/third_party/jemalloc/src/pages.c @@ -79,6 +79,8 @@ static int madvise_MADV_DONTNEED_zeroes_pages(void) if (opt_abort) { abort(); } + /* DuckDB treats MADV_DONTNEED as faulty without memory to probe it. */ + return 0; } memset(addr, 'A', size); diff --git a/src/duckdb/third_party/utf8proc/utf8proc.cpp b/src/duckdb/third_party/utf8proc/utf8proc.cpp index bfea42744..917b64cc8 100644 --- a/src/duckdb/third_party/utf8proc/utf8proc.cpp +++ b/src/duckdb/third_party/utf8proc/utf8proc.cpp @@ -673,7 +673,7 @@ UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_normalize_utf32(utf8proc_int32_t *b (hangul_sindex % UTF8PROC_HANGUL_TCOUNT) == 0) { utf8proc_int32_t hangul_tindex; hangul_tindex = current_char - UTF8PROC_HANGUL_TBASE; - if (hangul_tindex >= 0 && hangul_tindex < UTF8PROC_HANGUL_TCOUNT) { + if (hangul_tindex > 0 && hangul_tindex < UTF8PROC_HANGUL_TCOUNT) { *starter += hangul_tindex; starter_property = NULL; continue;