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
Original file line number Diff line number Diff line change
Expand Up @@ -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++;
}
Expand Down Expand Up @@ -392,7 +401,8 @@ unique_ptr<FunctionData> HistogramBinBindFunction(BindAggregateFunctionInput &in
}
}

function.ReplaceImplementation(GetHistogramBinFunction<HIST>(arguments[0]->GetReturnType()));
// the template signature resolved both parameters to the deduced bin type
function.ReplaceImplementation(GetHistogramBinFunction<HIST>(function.GetArguments()[0]));
return nullptr;
}

Expand All @@ -402,17 +412,17 @@ AggregateFunction HistogramFun::BinnedHistogramFunction() {
AggregateFunction function("histogram", {}, LogicalTypeId::MAP, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, HistogramBinBindFunction<HistogramRange>, 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;
}

AggregateFunction HistogramExactFun::GetFunction() {
AggregateFunction function("histogram_exact", {}, LogicalTypeId::MAP, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, HistogramBinBindFunction<HistogramExact>, 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;
}

Expand Down
18 changes: 1 addition & 17 deletions src/duckdb/extension/core_functions/scalar/list/list_sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -318,20 +318,11 @@ static void ListSortFunction(DataChunk &args, ExpressionState &state, Vector &re
static unique_ptr<FunctionData> ListSortBind(ClientContext &context, BoundScalarFunction &bound_function,
vector<unique_ptr<Expression>> &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<ListSortBindData>(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());
Expand Down Expand Up @@ -365,13 +356,6 @@ static unique_ptr<FunctionData> 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<ListSortBindData>(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");
Expand Down
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
56 changes: 54 additions & 2 deletions src/duckdb/extension/core_functions/scalar/string/hex.cpp
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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 <uint8_t BITS_PER_DIGIT>
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<uint32_t>::Leading(value.GetAbsoluteByte(NumericCast<int64_t>(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<int64_t>(i));
idx_t digits = i == start ? leading_digits : DIGITS_PER_BYTE;
for (idx_t d = digits; d >= 1; d--) {
auto digit = static_cast<uint8_t>((byte >> ((d - 1) * BITS_PER_DIGIT)) & DIGIT_MASK);
*output++ = Blob::HEX_TABLE[digit];
}
}

target.Finalize();
return target;
}

struct HexStrOperator {
template <class INPUT_TYPE, class RESULT_TYPE>
static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) {
Expand Down Expand Up @@ -167,6 +205,13 @@ struct HexUhugeIntOperator {
}
};

struct HexBignumOperator {
template <class INPUT_TYPE, class RESULT_TYPE>
static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) {
return WriteBignumDigits<4>(input, heap);
}
};

template <class INPUT, class OP>
static void ToHexFunction(DataChunk &args, ExpressionState &state, Vector &result) {
D_ASSERT(args.ColumnCount() == 1);
Expand Down Expand Up @@ -276,6 +321,13 @@ struct BinaryUhugeIntOperator {
}
};

struct BinaryBignumOperator {
template <class INPUT_TYPE, class RESULT_TYPE>
static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) {
return WriteBignumDigits<1>(input, heap);
}
};

struct FromHexOperator {
template <class INPUT_TYPE, class RESULT_TYPE>
static RESULT_TYPE Operation(INPUT_TYPE input, StringHeap &heap) {
Expand Down Expand Up @@ -389,7 +441,7 @@ ScalarFunctionSet HexFun::GetFunctions() {
AddHexParam(string_fun, LogicalType::VARCHAR, "string");
to_hex.AddFunction(string_fun);

ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToHexFunction<string_t, HexStrOperator>);
ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToHexFunction<bignum_t, HexBignumOperator>);
AddHexParam(bignum_fun, LogicalType::BIGNUM, "value");
to_hex.AddFunction(bignum_fun);

Expand Down Expand Up @@ -430,7 +482,7 @@ ScalarFunctionSet BinFun::GetFunctions() {
AddHexParam(string_fun, LogicalType::VARCHAR, "string");
to_binary.AddFunction(string_fun);

ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToBinaryFunction<string_t, BinaryStrOperator>);
ScalarFunction bignum_fun({}, LogicalType::VARCHAR, ToBinaryFunction<bignum_t, BinaryBignumOperator>);
AddHexParam(bignum_fun, LogicalType::BIGNUM, "value");
to_binary.AddFunction(bignum_fun);

Expand Down
68 changes: 55 additions & 13 deletions src/duckdb/extension/icu/icu-dateadd.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,39 @@ timestamp_tz_t ICUCalendarAdd::Operation(interval_t interval, timestamp_tz_t tim
return Operation<timestamp_tz_t, interval_t, timestamp_tz_t>(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<timestamp_tz_t, interval_t, timestamp_tz_t>(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_tz_ns_t, interval_t, timestamp_tz_ns_t>(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_tz_t, interval_t, timestamp_tz_t>(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<timestamp_tz_ns_t, interval_t, timestamp_tz_ns_t>(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()) {
Expand Down Expand Up @@ -249,24 +276,33 @@ struct ICUDateAdd : public ICUDateFunc {
ICUBindIntervalMonths);
}

template <typename TA, typename TB, typename OP>
static ScalarFunction GetDateAddFunction(const LogicalTypeId &left_type, const LogicalTypeId &right_type) {
return GetBinaryDateFunction<TA, TB, timestamp_tz_t, OP>(left_type, right_type, LogicalType::TIMESTAMP_TZ);
template <typename TA, typename TB, typename TR, typename OP>
static ScalarFunction GetDateAddFunction(const LogicalTypeId &left_type, const LogicalTypeId &right_type,
const LogicalTypeId &result_type) {
return GetBinaryDateFunction<TA, TB, TR, OP>(left_type, right_type, result_type);
}

static void AddDateAddOperators(const Identifier &name, ExtensionLoader &loader) {
template <typename T>
static void AddDateAddFunctions(ScalarFunctionSet &set, const LogicalTypeId &type) {
// temporal + interval
ScalarFunctionSet set {name};
auto tstz_interval_fun = GetDateAddFunction<timestamp_tz_t, interval_t, ICUCalendarAdd>(
LogicalType::TIMESTAMP_TZ, LogicalType::INTERVAL);
auto tstz_interval_fun =
GetDateAddFunction<T, interval_t, T, ICUCalendarAdd>(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<interval_t, timestamp_tz_t, ICUCalendarAdd>(
LogicalType::INTERVAL, LogicalType::TIMESTAMP_TZ);

// interval + temporal
auto interval_tstz_fun =
GetDateAddFunction<interval_t, T, T, ICUCalendarAdd>(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<timestamp_tz_t>(set, LogicalType::TIMESTAMP_TZ);
AddDateAddFunctions<timestamp_tz_ns_t>(set, LogicalType::TIMESTAMP_TZ_NS);
// throws for dates that overflow the timestamp range
set.SetFallible();
set.SetStability(FunctionStability::CONSISTENT_WITHIN_QUERY);
Expand All @@ -283,14 +319,20 @@ struct ICUDateAdd : public ICUDateFunc {
return GetBinaryDateFunction<TA, TB, interval_t, OP>(left_type, right_type, LogicalType::INTERVAL);
}

static void AddDateSubOperators(const Identifier &name, ExtensionLoader &loader) {
template <typename T>
static void AddDateSubFunction(ScalarFunctionSet &set, const LogicalTypeId &type) {
// temporal - interval
ScalarFunctionSet set {name};
auto tstz_interval_fun = GetDateAddFunction<timestamp_tz_t, interval_t, ICUCalendarSub>(
LogicalType::TIMESTAMP_TZ, LogicalType::INTERVAL);
auto tstz_interval_fun =
GetDateAddFunction<T, interval_t, T, ICUCalendarSub>(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<timestamp_tz_t>(set, LogicalType::TIMESTAMP_TZ);
AddDateSubFunction<timestamp_tz_ns_t>(set, LogicalType::TIMESTAMP_TZ_NS);

// temporal - temporal
auto tstz_tstz_fun = GetBinaryAgeFunction<timestamp_tz_t, timestamp_tz_t, ICUCalendarSub>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -194,13 +195,18 @@ static vector<unique_ptr<SelectStatement>> DeserializeSelectStatement(string_t i
throw ParserException("Error parsing json: no statements");
}

DeserializationPolicy policy;
policy.Disallow(LogicalTypeId::POINTER);
policy.Disallow(LiteralKind::POINTER);

vector<unique_ptr<SelectStatement>> result;

idx_t idx;
idx_t max;
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");
Expand Down
3 changes: 1 addition & 2 deletions src/duckdb/extension/json/json_functions/json_transform.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 15 additions & 17 deletions src/duckdb/extension/json/json_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading