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
80 changes: 77 additions & 3 deletions src/duckdb/extension/core_functions/scalar/date/date_sub.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "duckdb/common/types/timestamp.hpp"
#include "duckdb/common/vector_operations/ternary_executor.hpp"
#include "duckdb/optimizer/statistics_propagator.hpp"
#include "duckdb/storage/statistics/numeric_stats.hpp"

namespace duckdb {

Expand Down Expand Up @@ -446,8 +447,84 @@ void DateSubFunction(DataChunk &args, ExpressionState &state, Vector &result) {

} // namespace

static int64_t CalendarMonthNumber(timestamp_t timestamp) {
int32_t year, month, day;
Date::Convert(Timestamp::GetDate(timestamp), year, month, day);
return int64_t(year) * Interval::MONTHS_PER_YEAR + month;
}

static unique_ptr<BaseStatistics> DateSubMonthStatistics(ClientContext &, FunctionStatisticsInput &input) {
const auto &starts = input.child_stats[1];
const auto &ends = input.child_stats[2];
if (!NumericStats::HasMinMax(starts) || !NumericStats::HasMinMax(ends)) {
return nullptr;
}
const auto start_min = NumericStats::GetMin<timestamp_t>(starts);
const auto start_max = NumericStats::GetMax<timestamp_t>(starts);
const auto end_min = NumericStats::GetMin<timestamp_t>(ends);
const auto end_max = NumericStats::GetMax<timestamp_t>(ends);
if (!start_min.IsFinite() || !start_max.IsFinite() || !end_min.IsFinite() || !end_max.IsFinite()) {
return nullptr;
}
const auto first_start_month = CalendarMonthNumber(start_min);
const auto first_end_month = CalendarMonthNumber(end_min);
// Leave the partial first month, where finite extrema can enclose -infinity, to scalar evaluation.
static const auto first_month = CalendarMonthNumber(timestamp_t(NumericLimits<int64_t>::Minimum()));
if (first_start_month == first_month || first_end_month == first_month) {
return nullptr;
}
const auto min_months = first_end_month - CalendarMonthNumber(start_max);
const auto max_months = CalendarMonthNumber(end_max) - first_start_month;
// An incomplete month can move the signed calendar-month difference one step toward zero.
auto result = BaseStatistics::CreateUnknown(LogicalType::BIGINT);
NumericStats::SetMin(result, min_months > 0 ? min_months - 1 : min_months);
NumericStats::SetMax(result, max_months < 0 ? max_months + 1 : max_months);
return result.ToUnique();
}

static unique_ptr<FunctionData> BindDateSub(BindScalarFunctionInput &input) {
auto part = input.TryGetConstant(0);
DatePartSpecifier unit;
if (!part || part->IsNull() || !TryGetDatePartSpecifier(part->ToString(), unit)) {
return nullptr;
}
auto &function = input.GetBoundFunction();
switch (unit) {
case DatePartSpecifier::MONTH:
if (function.GetArguments()[1].id() == LogicalTypeId::TIMESTAMP) {
function.SetStatisticsCallback(DateSubMonthStatistics);
}
return nullptr;
case DatePartSpecifier::WEEK:
case DatePartSpecifier::YEARWEEK:
case DatePartSpecifier::DAY:
case DatePartSpecifier::DOW:
case DatePartSpecifier::ISODOW:
case DatePartSpecifier::DOY:
case DatePartSpecifier::JULIAN_DAY:
if (function.GetArguments()[1].id() == LogicalTypeId::TIME) {
return nullptr;
}
break;
case DatePartSpecifier::MICROSECONDS:
case DatePartSpecifier::MILLISECONDS:
case DatePartSpecifier::SECOND:
case DatePartSpecifier::EPOCH:
case DatePartSpecifier::MINUTE:
case DatePartSpecifier::HOUR:
break;
default:
return nullptr;
}
function.SetArgProperties(1, ArgProperties().NonIncreasing());
function.SetArgProperties(2, ArgProperties().NonDecreasing());
function.SetStatisticsCallback(StatisticsPropagator::PropagateFiniteMonotoneBounds);
return nullptr;
}

// Names the "part,startdate,enddate" triple shared by date_sub's per-type overloads.
static ScalarFunction NameDateSubPartStartEndArguments(ScalarFunction fun, const LogicalType &type) {
fun.SetBindCallback(BindDateSub);
fun.GetSignature()
.AddParameter("part", LogicalType::VARCHAR)
.AddParameter("startdate", type)
Expand All @@ -465,9 +542,6 @@ ScalarFunctionSet DateSubFun::GetFunctions() {
ScalarFunction({}, LogicalType::BIGINT, DateSubFunction<dtime_t>), LogicalType::TIME));
// throws for unsupported date parts, and when the difference overflows
date_sub.SetFallible();
date_sub.SetArgProperties(1, ArgProperties().NonIncreasing());
date_sub.SetArgProperties(2, ArgProperties().NonDecreasing());
date_sub.SetStatisticsCallback(StatisticsPropagator::PropagateFiniteMonotoneBounds);
return date_sub;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,9 @@ static void JsonSerializePlanFunction(DataChunk &args, ExpressionState &state, V

} catch (std::exception &ex) {
ErrorData error(ex);
if (error.Type() == ExceptionType::OUT_OF_MEMORY) {
throw;
}
yyjson_mut_obj_add_true(doc, result_obj, "error");
// error type and message
yyjson_mut_obj_add_strcpy(doc, result_obj, "error_type",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ static void JsonSerializeFunction(DataChunk &args, ExpressionState &state, Vecto

} catch (std::exception &ex) {
ErrorData error(ex);
if (error.Type() == ExceptionType::OUT_OF_MEMORY) {
throw;
}
yyjson_mut_obj_add_true(doc, result_obj, "error");
yyjson_mut_obj_add_strcpy(doc, result_obj, "error_type",
StringUtil::Lower(Exception::ExceptionTypeToString(error.Type())).c_str());
Expand Down
8 changes: 4 additions & 4 deletions src/duckdb/generated_extension_loader_package_build.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.1.0-alpha57181";
descriptor->api_version = "v2.1.0-alpha57291";
descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init;
return 0;
}
Expand Down Expand Up @@ -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.1.0-alpha57181";
descriptor->api_version = "v2.1.0-alpha57291";
descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init;
return 0;
}
Expand Down Expand Up @@ -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.1.0-alpha57181";
descriptor->api_version = "v2.1.0-alpha57291";
descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init;
return 0;
}
Expand Down Expand Up @@ -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.1.0-alpha57181";
descriptor->api_version = "v2.1.0-alpha57291";
descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init;
return 0;
}
Expand Down
7 changes: 5 additions & 2 deletions src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,12 @@ optional_ptr<CatalogEntry> DuckSchemaEntry::AddEntryInternal(CatalogTransaction
auto existing_entry = set.GetEntry(transaction, entry_name);
auto existing_type = existing_entry ? existing_entry->type : entry_type;
throw CatalogException::EntryAlreadyExists(existing_type, entry_name);
} else {
return nullptr;
}
if (on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT) {
// the entry was created after it was dropped: by a concurrent statement of this transaction
throw TransactionException("Catalog write-write conflict on create or replace of %s", entry_name);
}
return nullptr;
}
return result;
}
Expand Down
3 changes: 2 additions & 1 deletion src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ unique_ptr<CatalogEntry> MacroCatalogEntry::AlterEntry(CatalogTransaction transa
if (!temporary && attached.HasStorageManager() && !attached.IsTemporary()) {
auto &storage_manager = attached.GetStorageManager();
const auto since = StorageCompatibility::FromString("v2.1.0").storage_version;
if (!storage_manager.InMemory() && storage_manager.GetStorageVersion() < since) {
// a committed record replays regardless of the version in the file header
if (storage_manager.IsLoaded() && !storage_manager.InMemory() && storage_manager.GetStorageVersion() < since) {
string msg = "Dropping a single overload is only supported for storage versions v2.1.0 and higher.\n";
msg += "Use an in-memory database, ATTACH with (STORAGE_VERSION v2.1.0), or a TEMP macro";
throw CatalogException(msg);
Expand Down
19 changes: 15 additions & 4 deletions src/duckdb/src/common/sort/hashed_sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class HashedSortGroup {
using Orders = vector<BoundOrderByNode>;
using Types = vector<LogicalType>;

HashedSortGroup(ClientContext &client, Sort &sort, idx_t group_idx);
HashedSortGroup(Sort &sort, idx_t group_idx);

const idx_t group_idx;
atomic<idx_t> count;
Expand All @@ -42,9 +42,8 @@ class HashedSortGroup {
ColumnDataAppendState direct_append_state;
};

HashedSortGroup::HashedSortGroup(ClientContext &client, Sort &sort, idx_t group_idx)
HashedSortGroup::HashedSortGroup(Sort &sort, idx_t group_idx)
: group_idx(group_idx), count(0), sort(sort), tasks_completed(0) {
sort_global = sort.GetGlobalSinkState(client);
}

//===--------------------------------------------------------------------===//
Expand Down Expand Up @@ -293,7 +292,7 @@ void HashedSortGlobalSinkState::CombineLocalPartition(GroupingPartition &local_p

auto &group_data = groups[group_idx];
if (group_data->Count()) {
hash_group = make_uniq<HashedSortGroup>(client, *hashed_sort.sort, group_idx);
hash_group = make_uniq<HashedSortGroup>(*hashed_sort.sort, group_idx);
}
}

Expand Down Expand Up @@ -339,6 +338,17 @@ SinkFinalizeType HashedSort::Finalize(ClientContext &client, OperatorSinkFinaliz
continue;
}

// The partition is complete: register the group's sort now, reserving its size if below the default minimum
if (!gsink.CanBypassSort(hash_bin)) {
hash_group->sort_global = sort->GetGlobalSinkState(client);
const auto count = partition.Count();
const auto row_size = count * partition.GetLayout().GetRowWidth();
D_ASSERT(partition.SizeInBytes() >= row_size);
// the variable-size data is what the partition holds beyond its fixed-size rows
const auto variable_data_size = partition.SizeInBytes() - row_size;
sort->SetExpectedSize(client, *hash_group->sort_global, count, variable_data_size);
}

// Prepare to scan into the sort
auto &parallel_scan = hash_group->parallel_scan;
partition.InitializeScan(parallel_scan, partition_ids);
Expand Down Expand Up @@ -564,6 +574,7 @@ void HashedSort::SortColumnData(ExecutionContext &context, hash_t hash_bin, Oper
TupleDataLocalScanState local_scan;
partition.InitializeScan(local_scan);

D_ASSERT(hash_group.sort_global);
auto sort_local = sort->GetLocalSinkState(context);
OperatorSinkInput sink {*hash_group.sort_global, *sort_local, finalize.interrupt_state};
idx_t combined = 0;
Expand Down
17 changes: 17 additions & 0 deletions src/duckdb/src/common/sort/sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,23 @@ OperatorPartitionData Sort::GetPartitionData(ExecutionContext &context, DataChun
//===--------------------------------------------------------------------===//
// Non-Standard Interface
//===--------------------------------------------------------------------===//
void Sort::SetExpectedSize(ClientContext &context, GlobalSinkState &gstate, idx_t count,
idx_t variable_data_size) const {
auto &sink = gstate.Cast<SortGlobalSinkState>();
D_ASSERT(sink.sunk_tuples == 0);
// key and payload rows, variable-size data and merge buffer, as SizeInBytesForSorting measures them
const auto key_width = key_layout->GetRowWidth();
auto expected_size = count * (key_width + payload_layout->GetRowWidth()) + variable_data_size +
SortMergeBuffer::MaximumSize(count, key_width);
auto &state = *sink.temporary_memory_state;
// only lower the reservation: a larger sort keeps the default minimum and grows on demand
expected_size = MinValue(expected_size, state.GetMinimumReservation());
if (expected_size == 0) {
return;
}
state.SetRemainingSizeAndUpdateReservation(context.GetContext(), expected_size);
}

SourceResultType Sort::MaterializeColumnData(ExecutionContext &context, OperatorSourceInput &input) const {
auto &gstate = input.global_state.Cast<SortGlobalSourceState>();

Expand Down
16 changes: 3 additions & 13 deletions src/duckdb/src/common/sort/sorted_run.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "duckdb/common/types/row/tuple_data_collection.hpp"
#include "duckdb/common/sorting/sort.hpp"
#include "duckdb/common/sorting/sort_key.hpp"
#include "duckdb/common/sorting/sort_key_prefix.hpp"
#include "duckdb/common/sorting/buffered_merge.hpp"
#include "duckdb/common/types/row/block_iterator.hpp"

Expand Down Expand Up @@ -338,24 +339,13 @@ static void SortTiedBucket(ClientContext &context, const ITERATOR &begin, const
}
varying_bits |= words[0] ^ SUFFIX::ExtractWord(*it, offset);
}
// The common first word can cache the suffix during this synchronous refinement.
struct PrefixRestorer {
ITERATOR begin;
ITERATOR end;
uint64_t prefix;

~PrefixRestorer() {
for (auto it = begin; it != end; ++it) {
it->part0 = prefix;
}
}
} restore {begin, end, samples[0].part0};
SortKeyPrefixScope<ITERATOR> prefix_scope(begin, end);
scanned = 0;
for (auto it = begin; it != end; ++it) {
if (++scanned % STANDARD_VECTOR_SIZE == 0) {
context.FastInterruptCheck();
}
it->part0 = SUFFIX::ExtractWord(*it, offset);
prefix_scope.Set(*it, SUFFIX::ExtractWord(*it, offset));
}
SUFFIX suffix(extract_key, varying_bits);
duckdb_ska_sort::ska_sort(begin, end, suffix, merge);
Expand Down
12 changes: 12 additions & 0 deletions src/duckdb/src/common/sort/sorted_run_merger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "duckdb/common/thread_annotation.hpp"
#include "duckdb/common/sorting/sorted_run.hpp"
#include "duckdb/common/sorting/sort_key.hpp"
#include "duckdb/common/sorting/sort_key_prefix.hpp"
#include "duckdb/common/sorting/buffered_merge.hpp"
#include "duckdb/common/types/row/block_iterator.hpp"
#include "duckdb/common/types/row/tuple_data_collection.hpp"
Expand Down Expand Up @@ -83,6 +84,9 @@ struct MergePrefixLess {
}

bool operator()(const SORT_KEY &lhs, const SORT_KEY &rhs) const {
if (lhs.part0 != rhs.part0) {
return lhs.part0 < rhs.part0;
}
const auto lhs_size = lhs.GetHeapSize();
const auto rhs_size = rhs.GetHeapSize();
D_ASSERT(lhs_size > SORT_KEY::INLINE_LENGTH && rhs_size > SORT_KEY::INLINE_LENGTH);
Expand Down Expand Up @@ -782,6 +786,14 @@ void SortedRunMergerLocalState::TemplatedMergePartition(SortedRunMergerGlobalSta
unsafe_array_ptr<const SORT_KEY>(merged_partition_keys, merged_partition_count), run_boundaries);
if (prefix != 0) {
// Sorted endpoints establish this prefix for every key in each gathered fragment.
unsafe_array_ptr<SORT_KEY> keys(merged_partition_keys, merged_partition_count);
SortKeyPrefixScope<array_ptr_iterator<SORT_KEY>> prefix_scope(keys.begin(), keys.end());
for (auto &key : keys) {
D_ASSERT(key.GetHeapSize() >= prefix);
uint64_t word = 0;
memcpy(&word, key.GetData() + prefix, MinValue<idx_t>(sizeof(word), key.GetHeapSize() - prefix));
prefix_scope.Set(key, BSwapIfLE(word));
}
const MergePrefixLess<SORT_KEY> compare(prefix);
const auto prefix_fallback = [&](SORT_KEY *begin, SORT_KEY *end) {
duckdb_pdqsort::pdqsort_branchless(begin, end, compare);
Expand Down
4 changes: 4 additions & 0 deletions src/duckdb/src/common/types/type_manager.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "duckdb/common/types/type_manager.hpp"

#include "duckdb/common/type_visitor.hpp"
#include "duckdb/common/error_data.hpp"
#include "duckdb/function/cast/cast_function_set.hpp"
#include "duckdb/parser/parser.hpp"
#include "duckdb/planner/binder.hpp"
Expand All @@ -26,6 +27,9 @@ static LogicalType TransformStringToUnboundType(const string &str, ClientContext
try {
column_list = Parser(context).ParseColumnList("dummy " + str);
} catch (const std::runtime_error &e) {
if (ErrorData(e).Type() == ExceptionType::OUT_OF_MEMORY) {
throw;
}
const vector<string> suggested_types {"BIGINT",
"INT8",
"LONG",
Expand Down
19 changes: 0 additions & 19 deletions src/duckdb/src/execution/join_hashtable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2778,25 +2778,6 @@ idx_t JoinHashTable::FillWithHTOffsets(JoinHTScanState &state, Vector &addresses
return key_count;
}

idx_t JoinHashTable::ScanKeyColumn(Vector &addresses, Vector &result, idx_t column_index) const {
FlatVector::SetSize(result, count_t(0));
// nothing to scan if the build side is empty
if (data_collection->ChunkCount() == 0) {
return 0;
}
D_ASSERT(result.GetType() == layout_ptr->GetTypes()[column_index]);
JoinHTScanState join_ht_state(*data_collection, 0, data_collection->ChunkCount(), output_columns.size(),
TupleDataPinProperties::KEEP_EVERYTHING_PINNED);
auto key_count = FillWithHTOffsets(join_ht_state, addresses);
if (key_count == 0) {
return 0;
}
const auto &sel = *FlatVector::IncrementalSelectionVector();
data_collection->Gather(addresses, sel, key_count, column_index, result, sel, nullptr);
FlatVector::SetSize(result, count_t(key_count));
return key_count;
}

idx_t JoinHashTable::GetTotalSize(const vector<idx_t> &partition_sizes, const vector<idx_t> &partition_counts,
idx_t &max_partition_size, idx_t &max_partition_count) const {
const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
Expand Down
Loading
Loading