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
  •  
  •  
  •  
10 changes: 10 additions & 0 deletions src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "duckdb/common/likely.hpp"
#include "duckdb/function/function_set.hpp"
#include "duckdb/planner/expression.hpp"
#include "duckdb/planner/expression/bound_aggregate_expression.hpp"

namespace duckdb {

Expand Down Expand Up @@ -500,6 +501,14 @@ static AggregateFunction NameXParameter(AggregateFunction fun) {
return fun;
}

unique_ptr<BaseStatistics> AveragePropagateStats(ClientContext &context, BoundAggregateExpression &expr,
AggregateStatisticsInput &input) {
auto bounds = SumAccumulatorBounds::TryGet(input);
expr.FunctionMutable().SetErrorMode(bounds ? FunctionErrors::CANNOT_ERROR
: FunctionErrors::CAN_THROW_RUNTIME_ERROR);
return nullptr;
}

AggregateFunction GetAverageAggregate(PhysicalType type) {
switch (type) {
case PhysicalType::INT16: {
Expand All @@ -522,6 +531,7 @@ AggregateFunction GetAverageAggregate(PhysicalType type) {
AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, hugeint_t, double, HugeintAverageOperation>(
LogicalType::HUGEINT, LogicalType::DOUBLE);
function.SetFallible(); // adding HUGEINT values to the HUGEINT accumulator throws on overflow
function.SetStatisticsCallback(AveragePropagateStats);
return NameXParameter(std::move(function));
}
case PhysicalType::INTERVAL: {
Expand Down
103 changes: 61 additions & 42 deletions src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,54 @@

namespace duckdb {

optional<SumAccumulatorBounds> SumAccumulatorBounds::TryGet(const AggregateStatisticsInput &input) {
if (!input.node_stats || !input.node_stats->has_max_cardinality) {
return {};
}
auto &numeric_stats = input.child_stats[0];
if (!NumericStats::HasMinMax(numeric_stats)) {
return {};
}
hugeint_t min_value;
hugeint_t max_value;
switch (numeric_stats.GetType().InternalType()) {
case PhysicalType::BOOL:
min_value = NumericStats::Min(numeric_stats).GetValueUnsafe<bool>() ? 1 : 0;
max_value = NumericStats::Max(numeric_stats).GetValueUnsafe<bool>() ? 1 : 0;
break;
case PhysicalType::INT16:
min_value = NumericStats::Min(numeric_stats).GetValueUnsafe<int16_t>();
max_value = NumericStats::Max(numeric_stats).GetValueUnsafe<int16_t>();
break;
case PhysicalType::INT32:
min_value = NumericStats::Min(numeric_stats).GetValueUnsafe<int32_t>();
max_value = NumericStats::Max(numeric_stats).GetValueUnsafe<int32_t>();
break;
case PhysicalType::INT64:
min_value = NumericStats::Min(numeric_stats).GetValueUnsafe<int64_t>();
max_value = NumericStats::Max(numeric_stats).GetValueUnsafe<int64_t>();
break;
case PhysicalType::INT128:
min_value = NumericStats::Min(numeric_stats).GetValueUnsafe<hugeint_t>();
max_value = NumericStats::Max(numeric_stats).GetValueUnsafe<hugeint_t>();
break;
default:
return {};
}
if (min_value > max_value) {
return {};
}
const auto max_count = Hugeint::Convert(input.node_stats->max_cardinality);
SumAccumulatorBounds bounds;
if (!Hugeint::TryMultiply(min_value, max_count, bounds.min) ||
!Hugeint::TryMultiply(max_value, max_count, bounds.max)) {
return {};
}
bounds.min = MinValue(min_value, bounds.min);
bounds.max = MaxValue(max_value, bounds.max);
return bounds;
}

namespace {

struct SumSetOperation {
Expand Down Expand Up @@ -354,64 +402,35 @@ unique_ptr<FunctionData> SumNoOverflowBind(BindAggregateFunctionInput &input) {

unique_ptr<BaseStatistics> SumPropagateStats(ClientContext &context, BoundAggregateExpression &expr,
AggregateStatisticsInput &input) {
if (!input.node_stats || !input.node_stats->has_max_cardinality) {
return nullptr;
}
auto &numeric_stats = input.child_stats[0];
if (!NumericStats::HasMinMax(numeric_stats)) {
return nullptr;
}
auto internal_type = numeric_stats.GetType().InternalType();
hugeint_t max_negative = 0;
hugeint_t max_positive = 0;
switch (internal_type) {
case PhysicalType::BOOL:
max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe<bool>() ? 1 : 0;
max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe<bool>() ? 1 : 0;
break;
case PhysicalType::INT16:
max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe<int16_t>();
max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe<int16_t>();
break;
case PhysicalType::INT32:
max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe<int32_t>();
max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe<int32_t>();
break;
case PhysicalType::INT64:
max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe<int64_t>();
max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe<int64_t>();
break;
case PhysicalType::INT128:
max_negative = NumericStats::Min(numeric_stats).GetValueUnsafe<hugeint_t>();
max_positive = NumericStats::Max(numeric_stats).GetValueUnsafe<hugeint_t>();
break;
default:
throw InternalException("Unsupported type for propagate sum stats");
auto bounds = SumAccumulatorBounds::TryGet(input);
if (internal_type == PhysicalType::INT128) {
bool cannot_overflow = bounds.has_value();
if (cannot_overflow && expr.GetReturnType().id() == LogicalTypeId::DECIMAL) {
const auto decimal_limit = Hugeint::POWERS_OF_TEN[Decimal::MAX_WIDTH_DECIMAL];
cannot_overflow = bounds->min > -decimal_limit && bounds->max < decimal_limit;
}
expr.FunctionMutable().SetErrorMode(cannot_overflow ? FunctionErrors::CANNOT_ERROR
: FunctionErrors::CAN_THROW_RUNTIME_ERROR);
}

const auto max_card = Hugeint::Convert(input.node_stats->max_cardinality);
hugeint_t wide_negative = 0;
hugeint_t wide_positive = 0;
if (!Hugeint::TryMultiply(max_negative, max_card, wide_negative) ||
!Hugeint::TryMultiply(max_positive, max_card, wide_positive)) {
if (!bounds) {
return nullptr;
}

// Replace with fast implementation when possible: only INT32/INT64 have a narrower no-overflow implementation to
// swap in.
const bool has_no_overflow_variant = internal_type == PhysicalType::INT32 || internal_type == PhysicalType::INT64;
const bool sum_fits_in_int64 =
wide_negative > NumericLimits<int64_t>::Minimum() && wide_positive < NumericLimits<int64_t>::Maximum();
bounds->min > NumericLimits<int64_t>::Minimum() && bounds->max < NumericLimits<int64_t>::Maximum();
if (has_no_overflow_variant && sum_fits_in_int64) {
expr.FunctionMutable().ReplaceImplementation(GetSumAggregateNoOverflow(internal_type));
}

// Propagate stats.
auto sum_min = max_negative <= 0 ? wide_negative : max_negative;
auto sum_max = max_positive >= 0 ? wide_positive : max_positive;
auto result = NumericStats::CreateEmpty(expr.GetReturnType()).ToUnique();
NumericStats::SetMin(*result, Value::HUGEINT(sum_min));
NumericStats::SetMax(*result, Value::HUGEINT(sum_max));
NumericStats::SetMin(*result, Value::HUGEINT(bounds->min));
NumericStats::SetMax(*result, Value::HUGEINT(bounds->max));
result->Set(StatsInfo::CAN_HAVE_NULL_AND_VALID_VALUES);
return result;
}
Expand Down
24 changes: 16 additions & 8 deletions src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ struct ModeStandard {
return new MAP_TYPE();
}

static ModeAttr &GetOrCreate(MAP_TYPE &map, const T &key, ArenaAllocator &) {
return map[key];
}

template <class INPUT_TYPE, class RESULT_TYPE>
static RESULT_TYPE Assign(Vector &result, INPUT_TYPE input) {
return RESULT_TYPE(input);
Expand All @@ -136,13 +140,17 @@ struct ModeStandard {
struct ModeString {
using MAP_TYPE = OwningStringMap<ModeAttr>;

static MAP_TYPE *CreateEmpty(ArenaAllocator &allocator) {
return new MAP_TYPE(allocator);
static MAP_TYPE *CreateEmpty(ArenaAllocator &) {
return new MAP_TYPE();
}
static MAP_TYPE *CreateEmpty(Allocator &allocator) {
return new MAP_TYPE(allocator);
}

static ModeAttr &GetOrCreate(MAP_TYPE &map, const string_t &key, ArenaAllocator &allocator) {
return map.GetOrCreate(key, allocator);
}

template <class INPUT_TYPE, class RESULT_TYPE>
static RESULT_TYPE Assign(Vector &result, INPUT_TYPE input) {
return StringVector::AddStringOrBlob(result, input);
Expand Down Expand Up @@ -376,7 +384,7 @@ struct BaseModeFunction {
if (!state.frequency_map) {
state.frequency_map = TYPE_OP::CreateEmpty(input_data.allocator);
}
auto &i = (*state.frequency_map)[key];
auto &i = TYPE_OP::GetOrCreate(*state.frequency_map, key, input_data.allocator);
++i.count;
i.first_row = MinValue<idx_t>(i.first_row, state.count);
++state.count;
Expand All @@ -396,7 +404,7 @@ struct BaseModeFunction {
target.frequency_map = TYPE_OP::CreateEmpty(aggr_input_data.allocator);
}
for (auto &val : *source.frequency_map) {
auto &i = (*target.frequency_map)[val.first];
auto &i = TYPE_OP::GetOrCreate(*target.frequency_map, val.first, aggr_input_data.allocator);
i.count += val.second.count;
i.first_row = MinValue(i.first_row, val.second.first_row);
}
Expand All @@ -420,7 +428,7 @@ struct TypedModeFunction : BaseModeFunction<TYPE_OP> {
if (!state.frequency_map) {
state.frequency_map = TYPE_OP::CreateEmpty(aggr_input.input.allocator);
}
auto &i = (*state.frequency_map)[key];
auto &i = TYPE_OP::GetOrCreate(*state.frequency_map, key, aggr_input.input.allocator);
i.count += count;
i.first_row = MinValue<idx_t>(i.first_row, state.count);
state.count += count;
Expand Down Expand Up @@ -667,9 +675,9 @@ static FrequencyAggregateFinalizeResult FinalizeEntropyRewrite(FrequencyAggregat
auto log_total = BindScalar(context, "log2", total_ref->Copy());
auto normalized = BindScalar(context, "/", std::move(weighted_ref), std::move(total_ref));
auto entropy = BindScalar(context, "-", std::move(log_total), std::move(normalized));
auto coalesce = make_uniq<BoundOperatorExpression>(ExpressionType::OPERATOR_COALESCE, LogicalType::DOUBLE);
coalesce->GetChildrenMutable().push_back(std::move(entropy));
coalesce->GetChildrenMutable().push_back(make_uniq<BoundConstantExpression>(Value::DOUBLE(0)));
auto coalesce =
make_uniq<BoundOperatorExpression>(ExpressionType::OPERATOR_COALESCE, LogicalType::DOUBLE, std::move(entropy),
make_uniq<BoundConstantExpression>(Value::DOUBLE(0)));
result.result = std::move(coalesce);
return result;
}
Expand Down
17 changes: 13 additions & 4 deletions src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ struct HistogramFunction {
target.hist = MAP_TYPE::CreateEmpty(input_data.allocator);
}
for (auto &entry : *source.hist) {
(*target.hist)[entry.first] += entry.second;
MAP_TYPE::GetOrCreate(*target.hist, entry.first, input_data.allocator) += entry.second;
}
}
};
Expand All @@ -75,14 +75,23 @@ struct DefaultMapType {
static TYPE *CreateEmpty(ArenaAllocator &) {
return new TYPE();
}

template <class KEY>
static typename TYPE::mapped_type &GetOrCreate(TYPE &map, const KEY &key, ArenaAllocator &) {
return map[key];
}
};

template <class TYPE>
struct StringMapType {
using MAP_TYPE = TYPE;

static TYPE *CreateEmpty(ArenaAllocator &allocator) {
return new TYPE(allocator);
static TYPE *CreateEmpty(ArenaAllocator &) {
return new TYPE();
}

static typename TYPE::mapped_type &GetOrCreate(TYPE &map, const string_t &key, ArenaAllocator &allocator) {
return map.GetOrCreate(key, allocator);
}
};

Expand All @@ -109,7 +118,7 @@ void HistogramUpdateFunction(Vector inputs[], AggregateInputData &aggr_input, id
state.hist = MAP_TYPE::CreateEmpty(aggr_input.allocator);
}
auto &input_value = input_values[idx];
++(*state.hist)[input_value];
++MAP_TYPE::GetOrCreate(*state.hist, input_value, aggr_input.allocator);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "duckdb/common/operator/add.hpp"
#include "duckdb/common/operator/multiply.hpp"
#include "duckdb/common/types/value.hpp"
#include "duckdb/common/optional.hpp"
#include "duckdb/function/aggregate_state.hpp"
#include "duckdb/function/aggregate_state_layout.hpp"
#include "duckdb/common/operator/cast_operators.hpp"
Expand All @@ -22,6 +23,15 @@

namespace duckdb {

struct AggregateStatisticsInput;

struct SumAccumulatorBounds {
hugeint_t min;
hugeint_t max;

static optional<SumAccumulatorBounds> TryGet(const AggregateStatisticsInput &input);
};

struct RepeatedStateValue {
template <class T>
static T Multiply(const T &input, idx_t count) {
Expand Down Expand Up @@ -171,14 +181,9 @@ struct AddToHugeint {
result.lower += value;
// now handle overflows
int overflow = result.lower < value;
// we consider two situations:
// (1) input[idx] is positive, and current value is lower than value: overflow
// (2) input[idx] is negative, and current value is higher than value: underflow
if (!(overflow ^ positive)) {
// in the case of an overflow or underflow we either increment or decrement the upper base
// positive: +1, negative: -1
result.upper += -1 + 2 * positive;
}
D_ASSERT(positive == 0 || positive == 1);
// Add the unsigned carry and the sign extension of the input.
result.upper += overflow + positive - 1;
}

template <class STATE, class T>
Expand Down
5 changes: 3 additions & 2 deletions src/duckdb/extension/core_functions/lambda_functions.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "duckdb/function/lambda_functions.hpp"
#include "duckdb/common/exception/binder_exception.hpp"
#include "duckdb/main/client_context.hpp"
#include "duckdb/main/context.hpp"

#include "duckdb/common/serializer/serializer.hpp"
#include "duckdb/common/serializer/deserializer.hpp"
Expand All @@ -20,8 +21,8 @@ namespace duckdb {
//! LambdaExecuteInfo holds information for executing the lambda expression on an input chunk and
//! a resulting lambda chunk.
struct LambdaExecuteInfo {
LambdaExecuteInfo(ClientContext &context, const Expression &lambda_expr, const DataChunk &args,
const bool has_index, const Vector &child_vector)
LambdaExecuteInfo(Context &context, const Expression &lambda_expr, const DataChunk &args, const bool has_index,
const Vector &child_vector)
: has_index(has_index) {
expr_executor = make_uniq<ExpressionExecutor>(context, lambda_expr);

Expand Down
2 changes: 1 addition & 1 deletion src/duckdb/extension/core_functions/scalar/date/age.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ static void AgeFunctionStandard(DataChunk &input, ExpressionState &state, Vector
// plain TZ when ICU is not loaded, we implement this in UTC (like everything else)
// To get the PG behaviour, we overload these functions in ICU for TSTZ arguments.
auto current_date = Timestamp::FromDatetime(
Timestamp::GetDate(MetaTransaction::Get(state.GetContext()).start_timestamp), dtime_t(0));
Timestamp::GetDate(MetaTransaction::Get(state.GetClientContext()).start_timestamp), dtime_t(0));

UnaryExecutor::Execute<timestamp_t, interval_t>(input.data[0], result,
[&](timestamp_t input) -> optional<interval_t> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
namespace duckdb {

static timestamp_t GetTransactionTimestamp(ExpressionState &state) {
return MetaTransaction::Get(state.GetContext()).start_timestamp;
return MetaTransaction::Get(state.GetClientContext()).start_timestamp;
}

static void CurrentTimestampFunction(DataChunk &input, ExpressionState &state, Vector &result) {
Expand Down
28 changes: 14 additions & 14 deletions src/duckdb/extension/core_functions/scalar/date/date_part.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ struct DatePart {
return OP::template TryOperation<T, TR>(input, result);
}
template <class OP, class T, class TR>
static bool TryDatePartOperation(T input, TR &result, long) {
static bool TryDatePartOperation(T input, TR &result, int64_t) {
result = OP::template Operation<T, TR>(input);
return true;
}
Expand Down Expand Up @@ -2150,19 +2150,19 @@ void DatePartFunction(DataChunk &args, ExpressionState &state, Vector &result) {
const auto &spec_arg = args.data[0];
const auto &date_arg = args.data[1];

BinaryExecutor::Execute<string_t, T, double>(
spec_arg, date_arg, result, [&](string_t specifier, T date) -> optional<double> {
if (date.IsFinite()) {
const auto part_code = GetDatePartSpecifier(specifier.GetString());
if (IsBigintDatepart(part_code)) {
return ExtractElement<T>(part_code, date);
} else {
return ExtractDoubleElement<T>(part_code, date);
}
} else {
return nullopt;
}
});
BinaryExecutor::Execute<string_t, T, double>(spec_arg, date_arg, result,
[&](string_t specifier, T date) -> optional<double> {
if (date.IsFinite()) {
const auto part_code = GetDatePartSpecifier(specifier);
if (IsBigintDatepart(part_code)) {
return ExtractElement<T>(part_code, date);
} else {
return ExtractDoubleElement<T>(part_code, date);
}
} else {
return nullopt;
}
});
}

template <typename RESULT_TYPE, typename OP>
Expand Down
Loading
Loading