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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 99 additions & 9 deletions src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
#include "core_functions/aggregate/sum_helpers.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/bignum.hpp"
#include "duckdb/common/bignum_limbs.hpp"
#include "duckdb/common/types/bignum.hpp"
#include "duckdb/common/types/hugeint.hpp"
#include "duckdb/common/types/decimal.hpp"
#include "duckdb/function/aggregate/distributive_function_utils.hpp"
#include "duckdb/planner/expression/bound_aggregate_expression.hpp"
Expand Down Expand Up @@ -509,26 +512,97 @@ unique_ptr<FunctionData> BindDecimalSum(BindAggregateFunctionInput &input) {

struct BignumState {
bool is_set;
BignumIntermediate value;
//! Whether the sum has outgrown the hugeint_t accumulator and lives in the arena-allocated wide value
bool is_wide;
//! The sum while it fits a hugeint_t
hugeint_t small;
//! The sum once it does not
BignumIntermediate wide;
};

struct BignumOperation {
//! The magnitude of an input of at most 16 bytes as a hugeint_t; false when it does not fit
static bool TryGetSmall(const BignumIntermediate &input, hugeint_t &result) {
if (input.size > 2 * BignumLimb::BYTES) {
return false;
}
const int64_t end = input.size;
uint64_t lo = BignumLimb::LoadAbsolute(input.data, input.is_negative, end);
uint64_t hi =
BignumLimb::LoadAbsolute(input.data, input.is_negative, end - static_cast<int64_t>(BignumLimb::BYTES));
if (hi >> 63) {
// a magnitude of 2^127 or more
return false;
}
if (input.is_negative) {
// two's complement of the magnitude
hi = ~hi + (lo == 0);
lo = ~lo + 1;
}
result = hugeint_t(static_cast<int64_t>(hi), lo);
return true;
}

//! Writes a hugeint_t as a BIGNUM blob and returns its size; blob needs room for 16 + header bytes
static idx_t EncodeSmall(hugeint_t value, char *blob) {
const bool is_negative = value.upper < 0;
uint64_t hi = static_cast<uint64_t>(value.upper);
uint64_t lo = value.lower;
if (is_negative) {
hi = ~hi + (lo == 0);
lo = ~lo + 1;
}
const idx_t byte_count = BignumLimb::ByteCount(hi, lo);
Bignum::SetHeader(blob, byte_count, is_negative);
BignumLimb::StoreMagnitude(reinterpret_cast<data_ptr_t>(blob + Bignum::BIGNUM_HEADER_SIZE), byte_count, hi, lo,
is_negative);
return byte_count + Bignum::BIGNUM_HEADER_SIZE;
}

//! Adds a hugeint_t to the wide value
static void AddSmallToWide(BignumState &state, hugeint_t value, ArenaAllocator &allocator) {
char blob[2 * BignumLimb::BYTES + Bignum::BIGNUM_HEADER_SIZE];
const auto size = EncodeSmall(value, blob);
BignumIntermediate rhs(reinterpret_cast<uint8_t *>(blob), size);
state.wide.AddInPlace(allocator, rhs);
}

//! Moves the sum from the hugeint_t accumulator to the wide value
static void Widen(BignumState &state, ArenaAllocator &allocator) {
D_ASSERT(!state.is_wide);
state.wide.Initialize(allocator);
AddSmallToWide(state, state.small, allocator);
state.is_wide = true;
}

template <class INPUT_TYPE, class STATE, class OP>
static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input,
idx_t count) {
hugeint_t value;
hugeint_t total;
if (!state.is_wide && TryGetSmall(BignumIntermediate(input), value) &&
Hugeint::TryMultiply(value, hugeint_t(static_cast<int64_t>(count)), total) &&
Hugeint::TryAddInPlace(state.small, total)) {
state.is_set = true;
return;
}
for (idx_t i = 0; i < count; i++) {
Operation<INPUT_TYPE, STATE, OP>(state, input, unary_input);
}
}

template <class INPUT_TYPE, class STATE, class OP>
static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) {
if (!state.is_set) {
state.is_set = true;
state.value.Initialize(unary_input.input.allocator);
const BignumIntermediate rhs(input);
state.is_set = true;
if (!state.is_wide) {
hugeint_t value;
if (TryGetSmall(rhs, value) && Hugeint::TryAddInPlace(state.small, value)) {
return;
}
Widen(state, unary_input.input.allocator);
}
BignumIntermediate rhs(input);
state.value.AddInPlace(unary_input.input.allocator, rhs);
state.wide.AddInPlace(unary_input.input.allocator, rhs);
}

template <class STATE, class OP>
Expand All @@ -537,18 +611,34 @@ struct BignumOperation {
return;
}
if (!target.is_set) {
target.value.Initialize(input.allocator);
// the target is still zero: a plain add, the small sum is copied, the wide one needs its own allocation
target.is_set = true;
}
target.value.AddInPlace(input.allocator, source.value);
if (!target.is_wide) {
if (!source.is_wide && Hugeint::TryAddInPlace(target.small, source.small)) {
return;
}
Widen(target, input.allocator);
}
if (source.is_wide) {
target.wide.AddInPlace(input.allocator, source.wide);
} else {
AddSmallToWide(target, source.small, input.allocator);
}
}

template <class TARGET_TYPE, class STATE>
static void Finalize(STATE &state, TARGET_TYPE &target, AggregateFinalizeData &finalize_data) {
// the state is only read: it is exported while other threads may still read it
if (!state.is_set) {
finalize_data.ReturnNull();
} else if (state.is_wide) {
target = state.wide.ToBignum(finalize_data.input.allocator);
} else {
target = state.value.ToBignum(finalize_data.input.allocator);
auto blob = reinterpret_cast<char *>(
finalize_data.input.allocator.Allocate(2 * BignumLimb::BYTES + Bignum::BIGNUM_HEADER_SIZE));
const auto size = EncodeSmall(state.small, blob);
target = bignum_t(string_t(blob, UnsafeNumericCast<uint32_t>(size)));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ void ArrayValueFunction(DataChunk &args, ExpressionState &state, Vector &result)

for (idx_t i = 0; i < num_rows; i++) {
for (idx_t j = 0; j < num_columns; j++) {
auto val = args.GetValue(j, i).DefaultCastAs(child_type);
auto val = args.GetValue(j, i).CastAs(state.GetContext(), child_type);
child.SetValue((i * num_columns) + j, val);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ void EquiWidthBinFunction(DataChunk &args, ExpressionState &state, Vector &resul
}
return result_bins;
});
VectorOperations::DefaultCast(intermediate_result, result, args.size());
VectorOperations::Cast(state.GetContext(), intermediate_result, result, args.size());
}

void UnsupportedEquiWidth(DataChunk &args, ExpressionState &state, Vector &) {
Expand Down
6 changes: 3 additions & 3 deletions src/duckdb/extension/core_functions/scalar/math/numeric.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ static unique_ptr<BaseStatistics> 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<double, double>(current_min);
max_val = AbsOperator::Operation<double, double>(current_max);
Expand Down Expand Up @@ -751,7 +751,7 @@ unique_ptr<FunctionData> ResolveDecimalRoundPrecision(BoundScalarFunction &bound

template <typename NEGOP, typename POSOP, bool CAN_CARRY = false>
void DecimalRoundPrecisionResolveTypes(ResolveScalarFunctionTypesInput &input) {
auto val = input.GetNonNullConstant(1).DefaultCastAs(LogicalType::INTEGER);
auto val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::INTEGER);
ResolveDecimalRoundPrecision<NEGOP, POSOP, CAN_CARRY>(input.GetBoundFunction(), input.GetArgumentType(0),
IntegerValue::Get(val));
}
Expand All @@ -760,7 +760,7 @@ void DecimalRoundPrecisionResolveTypes(ResolveScalarFunctionTypesInput &input) {
template <typename NEGOP, typename POSOP, bool CAN_CARRY = false>
unique_ptr<FunctionData> BindDecimalRoundPrecision(BindScalarFunctionInput &input) {
auto &bound_function = input.GetBoundFunction();
auto val = input.GetNonNullConstant(1).DefaultCastAs(LogicalType::INTEGER);
auto val = input.GetNonNullConstant(1).CastAs(input.GetClientContext(), LogicalType::INTEGER);
return ResolveDecimalRoundPrecision<NEGOP, POSOP, CAN_CARRY>(
bound_function, bound_function.GetLogicalArguments()[0], IntegerValue::Get(val));
}
Expand Down
2 changes: 1 addition & 1 deletion src/duckdb/extension/json/include/json_executors.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ struct JSONExecutors {
casted_paths = make_uniq<Vector>(Vector::Ref(args.data[1]));
} else {
casted_paths = make_uniq<Vector>(LogicalTypeId::VARCHAR);
VectorOperations::DefaultCast(args.data[1], *casted_paths, args.size(), true);
VectorOperations::Cast(state.GetContext(), args.data[1], *casted_paths, args.size(), true);
}
BinaryExecutor::Execute<string_t, string_t, T>(
inputs, *casted_paths, result, args.size(), [&](string_t input, string_t path) -> optional<T> {
Expand Down
2 changes: 1 addition & 1 deletion src/duckdb/extension/json/include/json_functions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ struct JSONReadFunctionData : public FunctionData {
JSONReadFunctionData(bool constant, string path_p, idx_t len, JSONCommon::JSONPathType path_type);
unique_ptr<FunctionData> Copy() const override;
bool Equals(const FunctionData &other_p) const override;
static JSONCommon::JSONPathType CheckPath(const Value &path_val, string &path, idx_t &len);
static JSONCommon::JSONPathType CheckPath(Context &context, const Value &path_val, string &path, idx_t &len);
static void ResolveTypes(ResolveScalarFunctionTypesInput &input);
static unique_ptr<FunctionData> Bind(BindScalarFunctionInput &input);

Expand Down
10 changes: 6 additions & 4 deletions src/duckdb/extension/json/json_functions.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "duckdb/main/client_context.hpp"
#include "duckdb/common/vector/flat_vector.hpp"
#include "duckdb/common/vector/list_vector.hpp"
#include "duckdb/common/vector/string_vector.hpp"
Expand All @@ -17,11 +18,11 @@ namespace duckdb {

using JSONPathType = JSONCommon::JSONPathType;

JSONPathType JSONReadFunctionData::CheckPath(const Value &path_val, string &path, idx_t &len) {
JSONPathType JSONReadFunctionData::CheckPath(Context &context, const Value &path_val, string &path, idx_t &len) {
if (path_val.IsNull()) {
throw BinderException("JSON path cannot be NULL");
}
const auto path_str_val = path_val.DefaultCastAs(LogicalType::VARCHAR);
const auto path_str_val = path_val.CastAs(context, LogicalType::VARCHAR);
auto path_str = path_str_val.GetValueUnsafe<string_t>();
len = path_str.GetSize();
const auto ptr = path_str.GetData();
Expand Down Expand Up @@ -84,7 +85,7 @@ unique_ptr<FunctionData> JSONReadFunctionData::Bind(BindScalarFunctionInput &inp
auto path_val = input.TryGetConstant(1);
if (path_val && !path_val->IsNull()) {
constant = true;
path_type = CheckPath(*path_val, path, len);
path_type = CheckPath(input.GetClientContext().GetContext(), *path_val, path, len);
}
if (path_type == JSONCommon::JSONPathType::WILDCARD) {
bound_function.SetReturnType(LogicalType::LIST(bound_function.GetReturnType()));
Expand Down Expand Up @@ -128,7 +129,8 @@ unique_ptr<FunctionData> JSONReadManyFunctionData::Bind(BindScalarFunctionInput
for (auto &path_val : ListValue::GetChildren(paths_val)) {
paths.emplace_back("");
lens.push_back(0);
if (JSONReadFunctionData::CheckPath(path_val, paths.back(), lens.back()) == JSONPathType::WILDCARD) {
if (JSONReadFunctionData::CheckPath(input.GetClientContext().GetContext(), path_val, paths.back(),
lens.back()) == JSONPathType::WILDCARD) {
throw BinderException("Cannot have wildcards in JSON path when supplying multiple paths");
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/duckdb/extension/json/json_functions/copy_json.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,8 @@ static BoundStatement CopyToJSONPlanInternal(Binder &binder, CopyStatement &stmt
if (!option_values.empty() && option_values.back().IsNull()) {
ThrowJSONCopyNullException(format, option_name);
}
array_output =
option_values.empty() || BooleanValue::Get(option_values.back().DefaultCastAs(LogicalTypeId::BOOLEAN));
array_output = option_values.empty() ||
BooleanValue::Get(option_values.back().CastAs(binder.context, LogicalTypeId::BOOLEAN));
} else if (is_geojson && (option_name == "geometry_column" || option_name == "id_column")) {
// NULL explicitly unsets these, so unlike the other options a NULL value is meaningful here
if (option_values.size() != 1) {
Expand Down
2 changes: 1 addition & 1 deletion src/duckdb/extension/json/json_functions/json_modify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ struct JSONModifyFunctionData : public FunctionData {
const auto path_val = ExpressionExecutor::EvaluateScalar(context, *arguments[1]);
if (!path_val.IsNull()) {
constant = true;
path = path_val.DefaultCastAs(LogicalType::VARCHAR).GetValue<string>();
path = path_val.CastAs(context, LogicalType::VARCHAR).GetValue<string>();
}
}
return make_uniq<JSONModifyFunctionData>(constant, std::move(path));
Expand Down
13 changes: 8 additions & 5 deletions src/duckdb/extension/json/json_functions/json_table_in_out.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "duckdb/main/client_context.hpp"
#include "json_common.hpp"
#include "json_functions.hpp"
#include "duckdb/common/atomic.hpp"
Expand Down Expand Up @@ -309,7 +310,8 @@ struct JSONTableInOutResult {
};

template <JSONTableInOutType TYPE>
static void InitializeLocalState(JSONTableInOutLocalState &lstate, DataChunk &input, JSONTableInOutResult &result) {
static void InitializeLocalState(Context &context, JSONTableInOutLocalState &lstate, DataChunk &input,
JSONTableInOutResult &result) {
lstate.total_count = 0;

// Parse path, default to root if not given
Expand All @@ -322,7 +324,8 @@ static void InitializeLocalState(JSONTableInOutLocalState &lstate, DataChunk &in
path_value = path_values[lstate.input_row].GetValue();
}

if (JSONReadFunctionData::CheckPath(path_value, lstate.path, lstate.len) == JSONCommon::JSONPathType::WILDCARD) {
if (JSONReadFunctionData::CheckPath(context, path_value, lstate.path, lstate.len) ==
JSONCommon::JSONPathType::WILDCARD) {
throw BinderException("Wildcard JSON path not supported in json_each/json_tree");
}

Expand Down Expand Up @@ -383,8 +386,8 @@ static bool JSONTableInOutHandleValue(JSONTableInOutLocalState &lstate, JSONTabl
}

template <JSONTableInOutType TYPE>
static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFunctionInput &data_p, DataChunk &input,
DataChunk &output) {
static OperatorResultType JSONTableInOutFunction(ExecutionContext &context, TableFunctionInput &data_p,
DataChunk &input, DataChunk &output) {
auto &gstate = data_p.global_state->Cast<JSONTableInOutGlobalState>();
auto &lstate = data_p.local_state->Cast<JSONTableInOutLocalState>();

Expand All @@ -393,7 +396,7 @@ static OperatorResultType JSONTableInOutFunction(ExecutionContext &, TableFuncti
if (lstate.input_row >= input.size()) {
return OperatorResultType::NEED_MORE_INPUT;
}
InitializeLocalState<TYPE>(lstate, input, result);
InitializeLocalState<TYPE>(context.client.GetContext(), lstate, input, result);
lstate.initialized = true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ static unique_ptr<FunctionData> JSONTransformBind(BindScalarFunctionInput &input
if (structure_val.IsNull() || arguments[1]->GetReturnType() == LogicalTypeId::SQLNULL) {
bound_function.SetReturnType(LogicalTypeId::SQLNULL);
} else {
auto json_structure_val = structure_val.DefaultTryCastAs(LogicalType::JSON());
auto json_structure_val = structure_val.TryCastAs(input.GetClientContext(), LogicalType::JSON());
if (!json_structure_val) {
throw BinderException("Cannot cast JSON structure to string");
}
Expand Down
Loading
Loading