Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ set(DUCKDB_SRC_FILES
src/duckdb/src/main/extension/linked_extension_registry.cpp
src/duckdb/src/main/http/http_client_httplib.cpp
src/duckdb/src/optimizer/matcher/expression_matcher.cpp
src/duckdb/src/storage/block_allocator/block_allocator.cpp
src/duckdb/third_party/brotli/common/constants.cpp
src/duckdb/third_party/brotli/common/context.cpp
src/duckdb/third_party/brotli/common/dictionary.cpp
Expand Down Expand Up @@ -461,6 +462,7 @@ set(DUCKDB_SRC_FILES
src/duckdb/ub_src_main_settings.cpp
src/duckdb/ub_src_optimizer.cpp
src/duckdb/ub_src_optimizer_compressed_materialization.cpp
src/duckdb/ub_src_optimizer_duplicate_eliminated_domain.cpp
src/duckdb/ub_src_optimizer_join_order.cpp
src/duckdb/ub_src_optimizer_pullup.cpp
src/duckdb/ub_src_optimizer_pushdown.cpp
Expand Down
220 changes: 213 additions & 7 deletions duckdb_java.def

Large diffs are not rendered by default.

220 changes: 213 additions & 7 deletions duckdb_java.exp

Large diffs are not rendered by default.

220 changes: 213 additions & 7 deletions duckdb_java.map

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ void BignumAvgExportState(Vector &state_vector, AggregateFinalizeInputData &, Ve

void BignumAvgImportState(AggregateImportInputData &input) {
auto entries = input.input_vec.Values<VectorStructType<uint64_t, string_t>>();
for (idx_t i = 0; i < input.input_vec.size(); i++) {
for (idx_t i = 0; i < entries.size(); i++) {
auto &state = *reinterpret_cast<BignumAvgState *>(input.dest_buffer + i * input.layout.total_state_size);
BignumAvgOperation::Initialize(state);
const auto entry = entries[i];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -869,7 +869,7 @@ void BignumSumExportState(Vector &state_vector, AggregateFinalizeInputData &, Ve

void BignumSumImportState(AggregateImportInputData &input) {
auto entries = input.input_vec.Values<string_t>();
for (idx_t i = 0; i < input.input_vec.size(); i++) {
for (idx_t i = 0; i < entries.size(); i++) {
auto &state = *reinterpret_cast<BignumState *>(input.dest_buffer + i * input.layout.total_state_size);
const auto entry = entries[i];
state.is_set = entry.IsValid();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "duckdb/common/operator/add.hpp"
#include "duckdb/common/types/bignum_decimal.hpp"
#include "duckdb/common/types/decimal.hpp"
#include "duckdb/common/vector/string_vector.hpp"
#include "duckdb/common/vector/flat_vector.hpp"
#include "duckdb/common/vector/vector_iterator.hpp"
#include "duckdb/common/vector/list_vector.hpp"
Expand All @@ -11,6 +13,7 @@
#include "duckdb/common/serializer/serializer.hpp"
#include "duckdb/common/serializer/deserializer.hpp"

#include <cmath>
#include <stdlib.h>

namespace duckdb {
Expand All @@ -23,8 +26,9 @@ struct ApproxQuantileState {
};

struct ApproxQuantileCoding {
//! Encodes an input value for the sketch; type is the type of the input, which only the wide decimals read
template <typename INPUT_TYPE, typename SAVE_TYPE>
static SAVE_TYPE Encode(const INPUT_TYPE &input) {
static SAVE_TYPE Encode(const INPUT_TYPE &input, const LogicalType &type) {
return Cast::template Operation<INPUT_TYPE, SAVE_TYPE>(input);
}

Expand All @@ -41,9 +45,11 @@ struct ApproxQuantileCoding {
return false;
}

//! Decodes a quantile of the sketch into a value of the type of the result vector
template <typename SAVE_TYPE, typename TARGET_TYPE>
static void Decode(const SAVE_TYPE &source, TARGET_TYPE &target, const LogicalType &type) {
static void Decode(const SAVE_TYPE &source, TARGET_TYPE &target, Vector &result) {
Decode(source, target);
const auto &type = result.GetType();
if (type.id() != LogicalTypeId::DECIMAL) {
return;
}
Expand All @@ -58,9 +64,58 @@ struct ApproxQuantileCoding {
}
};

//! The bignum_t tier of decimals (above 38 digits) sketches the value of the decimal (the unscaled value divided by
//! the power of ten of its scale) as a DOUBLE, so that the magnitude of a value decides whether the sketch holds it,
//! not the number of digits of its width or scale: the unscaled value of 1 as a DECIMAL(310,309) has 310 digits
template <>
double ApproxQuantileCoding::Encode(const dtime_t &input) {
return Encode<int64_t, double>(input.value);
double ApproxQuantileCoding::Encode(const bignum_t &input, const LogicalType &type) {
const auto val = DecimalHelper<bignum_t>::ToDouble(input, DecimalType::GetScale(type));
if (!Value::DoubleIsFinite(val)) {
// skipping the value like an infinite DOUBLE would change the result
throw OutOfRangeException("approx_quantile sketches its input as DOUBLE: a %s value with a magnitude "
"beyond the DOUBLE range (about 1.8e308) cannot be added to the sketch",
type.ToString());
}
return val;
}

//! A quantile of the sketch is converted to the nearest value of the DECIMAL type
template <>
void ApproxQuantileCoding::Decode(const double &source, bignum_t &target, Vector &result) {
const auto &type = result.GetType();
const auto width = DecimalType::GetWidth(type);
const auto scale = DecimalType::GetScale(type);
if (!Value::DoubleIsFinite(source)) {
// the arithmetic of the sketch overflowed (values close to the limits of the DOUBLE range)
throw OutOfRangeException("approx_quantile: the sketch of the %s values overflowed the DOUBLE range, the "
"approximate quantile is not a finite value",
type.ToString());
}
string unscaled;
if (DecimalHelper<bignum_t>::TryFromDouble(source, width, scale, unscaled)) {
target = bignum_t(StringVector::AddStringOrBlob(result, unscaled));
return;
}
// The DOUBLE nearest to a value at the top of the width can lie just beyond the largest value of the type
// (the DOUBLE of forty nines is 1e40): such a quantile is the largest value. Anything further out is not a
// quantile of values of this type (an imported state can carry any sketch)
string digits = source < 0 ? "-" : "";
digits.append(width, '9');
string limit;
if (!DecimalHelper<bignum_t>::TryParse(digits.c_str(), digits.size(), width, 0, limit)) {
throw InternalException("approx_quantile: could not construct the DECIMAL limit");
}
const auto limit_double = DecimalHelper<bignum_t>::ToDouble(bignum_t(string_t(limit)), scale);
if (std::fabs(source) > std::fabs(limit_double)) {
throw OutOfRangeException("approx_quantile: the approximate quantile %s is out of the range of %s",
Value::DOUBLE(source).ToString(), type.ToString());
}
target = bignum_t(StringVector::AddStringOrBlob(result, limit));
}

template <>
double ApproxQuantileCoding::Encode(const dtime_t &input, const LogicalType &type) {
return Encode<int64_t, double>(input.value, type);
}

template <>
Expand All @@ -76,8 +131,8 @@ bool ApproxQuantileCoding::Decode(const double &source, dtime_t &target) {
}

template <>
double ApproxQuantileCoding::Encode(const dtime_tz_t &input) {
return Encode<uint64_t, double>(input.sort_key());
double ApproxQuantileCoding::Encode(const dtime_tz_t &input, const LogicalType &type) {
return Encode<uint64_t, double>(input.sort_key(), type);
}

template <>
Expand All @@ -100,8 +155,8 @@ bool ApproxQuantileCoding::Decode(const double &source, dtime_tz_t &target) {
}

template <>
double ApproxQuantileCoding::Encode(const timestamp_t &input) {
return Encode<int64_t, double>(input.value);
double ApproxQuantileCoding::Encode(const timestamp_t &input, const LogicalType &type) {
return Encode<int64_t, double>(input.value, type);
}

template <>
Expand Down Expand Up @@ -169,7 +224,8 @@ struct ApproxQuantileOperation {

template <class INPUT_TYPE, class STATE, class OP>
static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) {
auto val = ApproxQuantileCoding::template Encode<INPUT_TYPE, SAVE_TYPE>(input);
const auto &type = unary_input.input.function.GetArguments()[0];
const auto val = ApproxQuantileCoding::template Encode<INPUT_TYPE, SAVE_TYPE>(input, type);
if (!Value::DoubleIsFinite(val)) {
return;
}
Expand Down Expand Up @@ -219,7 +275,7 @@ struct ApproxQuantileScalarOperation : public ApproxQuantileOperation {
auto &bind_data = finalize_data.input.bind_data->template Cast<ApproximateQuantileBindData>();
D_ASSERT(bind_data.quantiles.size() == 1);
const auto source = state.h->quantile(bind_data.quantiles[0]);
ApproxQuantileCoding::Decode(source, target, finalize_data.result.GetType());
ApproxQuantileCoding::Decode(source, target, finalize_data.result);
}
};

Expand Down Expand Up @@ -401,26 +457,32 @@ AggregateFunction GetApproximateQuantileAggregateFunction(const LogicalType &typ
case PhysicalType::DOUBLE:
return AggregateFunction::UnaryAggregate<ApproxQuantileState, double, double, ApproxQuantileScalarOperation>(
type, type);
case PhysicalType::VARCHAR: {
if (type.id() != LogicalTypeId::DECIMAL) {
throw NotImplementedException("Unimplemented quantile aggregate");
}
// the bignum_t tier of decimals (above 38 digits)
auto function =
AggregateFunction::UnaryAggregate<ApproxQuantileState, bignum_t, bignum_t, ApproxQuantileScalarOperation>(
type, type);
// a value beyond the DOUBLE range does not fit the sketch
function.SetFallible();
return function;
}
default:
throw NotImplementedException("Unimplemented quantile aggregate");
}
}

//! Wide decimals have no approximate quantile of their own, they are aggregated as DOUBLE
LogicalType ApproxQuantileInputType(const LogicalType &type) {
if (type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type))) {
return LogicalType::DOUBLE;
}
return type;
}

AggregateFunction GetApproximateQuantileDecimalAggregateFunction(const LogicalType &type) {
switch (type.InternalType()) {
case PhysicalType::INT8:
case PhysicalType::INT16:
case PhysicalType::INT32:
case PhysicalType::INT64:
case PhysicalType::INT128:
case PhysicalType::VARCHAR:
// plans serialized before the bignum_t tier had an approximate quantile aggregated wide decimals as DOUBLE
case PhysicalType::DOUBLE:
// keep the DECIMAL type as the input and return type so that the width and scale survive the bind
return GetApproximateQuantileAggregateFunction(type);
Expand Down Expand Up @@ -492,7 +554,7 @@ void ReplaceApproxQuantileImplementation(BoundAggregateFunction &function, const
unique_ptr<FunctionData> BindApproxQuantileDecimal(BindAggregateFunctionInput &input) {
auto &function = input.GetBoundFunction();
auto &arguments = input.GetArguments();
auto decimal_type = ApproxQuantileInputType(arguments[0]->GetReturnType());
auto decimal_type = arguments[0]->GetReturnType();
auto bind_data = BindApproxQuantile(input);
ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(decimal_type));
return bind_data;
Expand Down Expand Up @@ -536,8 +598,7 @@ struct ApproxQuantileListOperation : public ApproxQuantileOperation {
for (size_t q = 0; q < entry.length; ++q) {
const auto &quantile = bind_data.quantiles[q];
const auto &source = state.h->quantile(quantile);
auto &target = rdata[ridx + q];
ApproxQuantileCoding::Decode(source, target, result.GetType());
ApproxQuantileCoding::Decode(source, rdata[ridx + q], result);
}

ListVector::SetListSize(finalize_data.result, entry.offset + entry.length);
Expand Down Expand Up @@ -599,6 +660,13 @@ AggregateFunction GetApproxQuantileListAggregateFunction(const LogicalType &type
return GetTypedApproxQuantileListAggregateFunction<int64_t, int64_t>(type);
case PhysicalType::INT128:
return GetTypedApproxQuantileListAggregateFunction<hugeint_t, hugeint_t>(type);
case PhysicalType::VARCHAR: {
// the bignum_t tier of decimals (above 38 digits)
auto function = GetTypedApproxQuantileListAggregateFunction<bignum_t, bignum_t>(type);
// a value beyond the DOUBLE range does not fit the sketch
function.SetFallible();
return function;
}
default:
throw NotImplementedException("Unimplemented approximate quantile list decimal aggregate");
}
Expand All @@ -619,7 +687,7 @@ AggregateFunction ApproxQuantileDecimalListFunction(const LogicalType &type) {
unique_ptr<FunctionData> BindApproxQuantileDecimalList(BindAggregateFunctionInput &input) {
auto &function = input.GetBoundFunction();
auto &arguments = input.GetArguments();
auto decimal_type = ApproxQuantileInputType(arguments[0]->GetReturnType());
auto decimal_type = arguments[0]->GetReturnType();
auto bind_data = BindApproxQuantile(input);
ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(decimal_type));
return bind_data;
Expand Down
38 changes: 37 additions & 1 deletion src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#include "core_functions/aggregate/holistic_functions.hpp"
#include "core_functions/aggregate/quantile_state.hpp"
#include "duckdb/common/bignum.hpp"
#include "duckdb/common/helper.hpp"
#include "duckdb/common/operator/abs.hpp"
#include "duckdb/common/operator/cast_operators.hpp"
#include "duckdb/common/operator/subtract.hpp"
#include "duckdb/common/smaller_binary.hpp"
#include "duckdb/common/typedefs.hpp"
#include "duckdb/common/types/string_heap.hpp"
#include "duckdb/planner/expression.hpp"

namespace duckdb {
Expand Down Expand Up @@ -41,6 +43,27 @@ struct MadAccessor {
}
};

// bignum_t - bignum_t => bignum_t
template <>
struct MadAccessor<bignum_t, bignum_t, bignum_t> {
using INPUT_TYPE = bignum_t;
using RESULT_TYPE = bignum_t;
using MEDIAN_TYPE = bignum_t;
const MEDIAN_TYPE &median;
//! the deviations are BIGNUM blobs, which live in the heap of the accessor
mutable StringHeap heap;
explicit MadAccessor(const MEDIAN_TYPE &median_p) : median(median_p) {
}
inline RESULT_TYPE operator()(const INPUT_TYPE &input) const {
// the blobs order like their values: the absolute deviation is the larger value minus the smaller one
const auto &larger = input < median ? median : input;
const auto &smaller = input < median ? input : median;
const BignumIntermediate lhs(larger);
const BignumIntermediate rhs(smaller);
return bignum_t(BignumIntermediate::Add(heap, lhs, rhs, true));
}
};

// hugeint_t - double => undefined
template <>
struct MadAccessor<hugeint_t, double, double> {
Expand Down Expand Up @@ -166,7 +189,17 @@ struct MedianAbsoluteDeviationOperation : QuantileOperation {
const auto med = interp.template Operation<INPUT_TYPE, MEDIAN_TYPE>(flattened.Data(), finalize_data.result);

MadAccessor<INPUT_TYPE, T, MEDIAN_TYPE> accessor(med);
target = interp.template Operation<INPUT_TYPE, T>(flattened.Data(), finalize_data.result, accessor);
if constexpr (std::is_same<T, bignum_t>::value) {
// BIGNUM deviations are allocated blobs: compute each one once instead of inside every comparison of the
// selection, replacing the flattened values (scratch space) by their deviations
auto values = flattened.Data();
for (idx_t i = 0; i < state.linked_list.total_capacity; i++) {
values[i] = accessor(values[i]);
}
target = interp.template Operation<INPUT_TYPE, T>(values, finalize_data.result);
} else {
target = interp.template Operation<INPUT_TYPE, T>(flattened.Data(), finalize_data.result, accessor);
}
}

template <class STATE, class INPUT_TYPE, class RESULT_TYPE>
Expand Down Expand Up @@ -306,6 +339,9 @@ AggregateFunction GetMedianAbsoluteDeviationAggregateFunctionInternal(const Logi
return GetTypedMedianAbsoluteDeviationAggregateFunction<int64_t, int64_t, int64_t>(type, type);
case PhysicalType::INT128:
return GetTypedMedianAbsoluteDeviationAggregateFunction<hugeint_t, hugeint_t, hugeint_t>(type, type);
case PhysicalType::VARCHAR:
// the bignum_t tier (above 38 digits): the BIGNUM blobs of the unscaled values
return GetTypedMedianAbsoluteDeviationAggregateFunction<bignum_t, bignum_t, bignum_t>(type, type);
default:
throw NotImplementedException("Unimplemented Median Absolute Deviation DECIMAL aggregate");
}
Expand Down
Loading
Loading