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
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ set(DUCKDB_SRC_FILES
src/duckdb/extension/parquet/parquet_int96.cpp
src/duckdb/extension/parquet/parquet_metadata.cpp
src/duckdb/extension/parquet/parquet_multi_file_info.cpp
src/duckdb/extension/parquet/parquet_page_index.cpp
src/duckdb/extension/parquet/parquet_prefetch_cost_model.cpp
src/duckdb/extension/parquet/parquet_reader.cpp
src/duckdb/extension/parquet/parquet_shredding.cpp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,8 @@ double CheckReservoirQuantile(const Value &quantile_val) {
unique_ptr<FunctionData> BindReservoirQuantile(BindAggregateFunctionInput &input) {
Value quantile_val = input.GetConstant(1);
vector<double> quantiles;
if (quantile_val.type().id() != LogicalTypeId::LIST) {
// a NULL list is rejected like a NULL quantile
if (quantile_val.IsNull() || quantile_val.type().id() != LogicalTypeId::LIST) {
quantiles.push_back(CheckReservoirQuantile(quantile_val));
} else {
for (const auto &element_val : ListValue::GetChildren(quantile_val)) {
Expand Down
2 changes: 2 additions & 0 deletions src/duckdb/extension/core_functions/scalar/generic/hash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ ScalarFunction HashFun::GetFunction() {
hash_fun.GetSignature().AddParameter("value", LogicalType::ANY);
hash_fun.GetSignature().AddArgs("args", LogicalType::ANY);
hash_fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING);
// hash the arguments after their combinable collations
hash_fun.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS);
return hash_fun;
}

Expand Down
63 changes: 63 additions & 0 deletions src/duckdb/extension/core_functions/scalar/list/list_transform.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
#include "duckdb/function/lambda_functions.hpp"
#include "duckdb/planner/expression/bound_cast_expression.hpp"
#include "duckdb/planner/expression/bound_lambda_expression.hpp"
#include "duckdb/planner/expression/bound_function_expression.hpp"
#include "duckdb/planner/filter/expression_filter.hpp"
#include "duckdb/storage/statistics/list_stats.hpp"

namespace duckdb {

Expand Down Expand Up @@ -30,6 +33,65 @@ static LogicalType ListTransformBindLambda(ClientContext &context, const vector<
return LambdaFunctions::BindBinaryChildren(function_child_types, parameter_idx);
}

//! Whether the expression is the element, or a monotone function of it whose bounds come only from those of the element
static bool IsMonotoneInElement(const Expression &expr) {
if (expr.GetExpressionClass() == ExpressionClass::BOUND_REF) {
return true;
}
if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) {
return false;
}
auto &func = expr.Cast<BoundFunctionExpression>();
auto &children = func.GetChildren();
if (children.size() != 1 || func.Function().HasStatisticsCallback()) {
return false;
}
auto monotonicity = func.Function().GetArgProperties(0).monotonicity;
if (!IsMonotonicIncreasing(monotonicity) && !IsMonotonicDecreasing(monotonicity)) {
return false;
}
return IsMonotoneInElement(*children[0]);
}

//! The elements of the result have the statistics of the lambda applied to the elements of the list
static unique_ptr<BaseStatistics> ListTransformStats(ClientContext &context, FunctionStatisticsInput &input) {
// only a lambda that reads the element alone, without its index or other columns
if (!input.bind_data || input.child_stats.size() != 2) {
return nullptr;
}
auto &bind_data = input.bind_data->Cast<ListLambdaBindData>();
auto &list_stats = input.child_stats[0];
if (!bind_data.lambda_expr || bind_data.has_index || list_stats.GetStatsType() != StatisticsType::LIST_STATS) {
return nullptr;
}
// statistics can let the optimizer skip the call, which must not hide errors or side effects of the list or lambda
auto &list_expr = *input.expr.GetChildren()[0];
// only the list of a scan column in a table filter: the statistics of any other list can stem from a producer
// with side effects that the optimizer removes once the statistics fold its use
if (list_expr.GetExpressionClass() != ExpressionClass::BOUND_REF) {
return nullptr;
}
if (list_expr.IsVolatile() || list_expr.CanThrow() || bind_data.lambda_expr->IsVolatile() ||
bind_data.lambda_expr->CanThrow()) {
return nullptr;
}
// the statistics of the list argument may not show that its producer has side effects or can throw, so derive
// nothing that does not follow from the statistics of the elements
if (!IsMonotoneInElement(*bind_data.lambda_expr)) {
return nullptr;
}
auto &element_stats = ListStats::GetChildStats(list_stats);
auto lambda_stats = ExpressionFilter::TryGetExpressionStatistics(
context, *bind_data.lambda_expr, array_ptr<const BaseStatistics>(&element_stats, 1));
if (!lambda_stats) {
return nullptr;
}
auto result = ListStats::CreateUnknown(input.expr.GetReturnType());
result.CopyValidity(list_stats);
ListStats::SetChildStats(result, std::move(lambda_stats));
return result.ToUnique();
}

ScalarFunction ListTransformFun::GetFunction() {
ScalarFunction fun({}, LogicalType::LIST(LogicalType::ANY), LambdaFunctions::ListTransformFunction,
ListTransformBind, nullptr, nullptr);
Expand All @@ -41,6 +103,7 @@ ScalarFunction ListTransformFun::GetFunction() {
fun.SetSerializeCallback(ListLambdaBindData::Serialize);
fun.SetDeserializeCallback(ListLambdaBindData::Deserialize);
fun.SetBindLambdaCallback(ListTransformBindLambda);
fun.SetStatisticsCallback(ListTransformStats);
// the lambda expression that is executed for every element can throw
fun.SetFallible();

Expand Down
6 changes: 2 additions & 4 deletions src/duckdb/extension/core_functions/scalar/math/numeric.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -976,10 +976,8 @@ inline T RoundDivide(T input, T power_of_ten) {
struct RoundHalfAwayFromZero {
static constexpr const char *Name = "ROUND";

// std::round is wrong for the largest double below 0.5 on some platforms (MinGW rounds it up to 1)
static double Nearest(double value) {
double truncated = std::trunc(value);
return std::fabs(value - truncated) >= 0.5 ? truncated + std::copysign(1.0, value) : truncated;
return RoundToNearestAwayFromZero(value);
}
template <class T>
static bool RoundsAway(T) {
Expand Down Expand Up @@ -1054,7 +1052,7 @@ struct RoundOperatorPrecision {
struct RoundOperator {
template <class TA, class TR>
static inline TR Operation(TA input) {
double rounded_value = RoundHalfAwayFromZero::Nearest(input);
double rounded_value = RoundToNearestAwayFromZero(static_cast<double>(input));
if (std::isinf(rounded_value) || std::isnan(rounded_value)) {
return input;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "duckdb/common/case_insensitive_map.hpp"
#include "duckdb/storage/statistics/struct_stats.hpp"
#include "duckdb/planner/expression_binder.hpp"
#include "duckdb/common/serializer/deserializer.hpp"

namespace duckdb {

Expand Down Expand Up @@ -39,8 +40,33 @@ struct StructUpdateBindData : public FunctionData {
static unique_ptr<FunctionData> Deserialize(Deserializer &deserializer, BoundScalarFunction &bound_function) {
auto stype = deserializer.ReadProperty<LogicalType>(100, "variable_return_type");
auto field_indexes = deserializer.ReadPropertyWithDefault<vector<idx_t>>(101, "field_indexes");
if (field_indexes.empty()) {
// Binding always records a field for every updated argument, so the mapping is only missing from plans
// that were serialized before it existed
field_indexes = FieldIndexesFromAliases(stype, deserializer.Get<const const_expression_list_t &>());
}
return make_uniq<StructUpdateBindData>(std::move(stype), std::move(field_indexes));
}

//! Plans serialized before v2.0 only name the field every argument updates through the alias of that argument
static vector<idx_t> FieldIndexesFromAliases(const LogicalType &stype, const const_expression_list_t &children) {
identifier_tree_t<idx_t> result_fields;
auto &result_children = StructType::GetChildTypes(stype);
for (idx_t field_idx = 0; field_idx < result_children.size(); field_idx++) {
result_fields.emplace(result_children[field_idx].first, field_idx);
}
vector<idx_t> field_indexes;
for (idx_t arg_idx = 1; arg_idx < children.size(); arg_idx++) {
auto &alias = children[arg_idx].get().GetAlias();
auto entry = result_fields.find(alias);
if (entry == result_fields.end()) {
throw SerializationException("struct_update argument \"%s\" does not name a field of the result",
alias.GetIdentifierName());
}
field_indexes.push_back(entry->second);
}
return field_indexes;
}
};

//! For every result field, the argument that provides it - fields without one keep the value of the source struct
Expand Down
134 changes: 129 additions & 5 deletions src/duckdb/extension/icu/collation/collation_collator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "collation_data.hpp"
#include "collation_normalizer.hpp"
#include "duckdb/common/algorithm.hpp"
#include "duckdb/common/string_util.hpp"

namespace duckdb {
Expand Down Expand Up @@ -464,7 +465,8 @@ static void WriteSortKey(const vector<collation_element_t> &elements, const Coll
const auto alternate_shifted = settings.alternate_shifted;
const auto backward_secondary = settings.backward_secondary;
const auto primary_strength = settings.strength == CollationStrength::PRIMARY;
uint32_t variable_top = alternate_shifted ? variable_top_primary + 1 : 0;
uint32_t variable_top =
alternate_shifted ? variable_top_primaries[static_cast<uint8_t>(settings.max_variable)] + 1 : 0;

SortKeyLevel secondaries(buffer.levels[0]);
SortKeyLevel cases(buffer.levels[1]);
Expand Down Expand Up @@ -808,21 +810,143 @@ static const CollationInfo *FindCollation(const string &collation) {
return nullptr;
}

Collator::Collator(const string &collation) {
auto info = FindCollation(StringUtil::Lower(collation));
//! The settings of a collation, or of the root collation for nullptr
static CollationSettings GetCollationSettings(const CollationInfo *info) {
CollationSettings settings;
if (info) {
// the tables of the collation are decompressed here, the sort keys only read them
tailoring = &GetCollationTailoring(info->unit);
settings.strength = static_cast<CollationStrength>(info->strength);
settings.case_level = info->case_level;
settings.case_first = static_cast<CaseFirst>(info->case_first);
settings.alternate_shifted = info->alternate_shifted;
settings.backward_secondary = info->backward_secondary;
settings.normalization = info->normalization;
}
return settings;
}

Collator::Collator(const CollationInfo *info, CollationSettings settings_p) : settings(settings_p) {
if (info) {
// the tables of the collation are decompressed here, the sort keys only read them
tailoring = &GetCollationTailoring(info->unit);
}
BuildFastPath();
}

Collator::Collator(const string &collation) : Collator(FindCollation(StringUtil::Lower(collation))) {
}

Collator::Collator(const CollationInfo *info) : Collator(info, GetCollationSettings(info)) {
}

//! Looks the value of a collation keyword up among its options, a keyword without a value is true
template <class T>
static T GetKeywordValue(const string &tag, const string &key, const string &value,
std::initializer_list<pair<const char *, T>> options) {
auto name = value.empty() ? string("true") : value;
for (auto &option : options) {
if (name == option.first) {
return option.second;
}
}
throw InvalidInputException("Invalid value \"%s\" for the collation keyword \"%s\" in \"%s\"", value, key, tag);
}

static bool GetBooleanKeyword(const string &tag, const string &key, const string &value) {
return GetKeywordValue<bool>(tag, key, value, {{"true", true}, {"false", false}});
}

//! Applies a collation keyword of the "-u-" extension of a language tag, as Unicode Technical Standard #35 defines it
static void ApplyCollationKeyword(const string &tag, const string &key, const string &value,
CollationSettings &settings) {
if (key == "ka") {
settings.alternate_shifted = GetKeywordValue<bool>(tag, key, value, {{"shifted", true}, {"noignore", false}});
} else if (key == "ks") {
settings.strength = GetKeywordValue<CollationStrength>(tag, key, value,
{{"level1", CollationStrength::PRIMARY},
{"level2", CollationStrength::SECONDARY},
{"level3", CollationStrength::TERTIARY},
{"level4", CollationStrength::QUATERNARY},
{"identic", CollationStrength::IDENTICAL}});
} else if (key == "kf") {
settings.case_first = GetKeywordValue<CaseFirst>(
tag, key, value,
{{"upper", CaseFirst::UPPER_FIRST}, {"lower", CaseFirst::LOWER_FIRST}, {"false", CaseFirst::DEFAULT}});
} else if (key == "kv") {
settings.max_variable = GetKeywordValue<MaxVariable>(tag, key, value,
{{"space", MaxVariable::SPACE},
{"punct", MaxVariable::PUNCTUATION},
{"symbol", MaxVariable::SYMBOL},
{"currency", MaxVariable::CURRENCY}});
} else if (key == "kc") {
settings.case_level = GetBooleanKeyword(tag, key, value);
} else if (key == "kb") {
settings.backward_secondary = GetBooleanKeyword(tag, key, value);
} else if (key == "kk") {
settings.normalization = GetBooleanKeyword(tag, key, value);
} else if ((key == "co" && value != "standard") || key == "kn" || key == "kr" || key == "kh" || key == "vt") {
throw NotImplementedException("The collation keyword \"%s\" in \"%s\" is not supported", key, tag);
}
// the other keywords, such as the calendar or the numbering system, do not change the collation
}

Collator Collator::FromLanguageTag(const string &tag) {
// subtags are case insensitive, and "_" separates them as well, as in "en_US"
auto subtags = StringUtil::Split(StringUtil::Replace(StringUtil::Lower(tag), "_", "-"), '-');
for (auto &subtag : subtags) {
bool valid = !subtag.empty() && subtag.size() <= 8;
for (auto c : subtag) {
valid = valid && StringUtil::CharacterIsAlphaNumeric(c);
}
if (!valid) {
throw InvalidInputException("Invalid collation \"%s\"", tag);
}
}
// the language, script, region and variants come before the first single character subtag
idx_t locale_end = 0;
while (locale_end < subtags.size() && subtags[locale_end].size() > 1) {
locale_end++;
}
// a locale without a collation of its own uses the one of its language, as "sv_se" uses "sv"
const CollationInfo *info = nullptr;
for (idx_t count = locale_end; count > 0 && !info; count--) {
info = FindCollation(StringUtil::Join(subtags, count, "_", [](const string &subtag) { return subtag; }));
}
auto settings = GetCollationSettings(info);
// the "u" extension holds attributes, then keywords: a two character key followed by the subtags of its value
idx_t pos = locale_end;
while (pos < subtags.size()) {
auto singleton = subtags[pos++];
if (singleton == "x") {
// the rest of the tag is for private use
break;
}
auto end = pos;
while (end < subtags.size() && subtags[end].size() > 1) {
end++;
}
if (singleton == "u") {
while (pos < end && subtags[pos].size() != 2) {
pos++;
}
// when a key is repeated, its first value counts
vector<string> keys;
while (pos < end) {
auto key = subtags[pos++];
string value;
while (pos < end && subtags[pos].size() != 2) {
value += (value.empty() ? "" : "-") + subtags[pos++];
}
if (std::find(keys.begin(), keys.end(), key) == keys.end()) {
keys.push_back(key);
ApplyCollationKeyword(tag, key, value, settings);
}
}
}
pos = end;
}
return Collator(info, settings);
}

void Collator::BuildFastPath() {
auto &root = GetCollationRoot();
if (tailoring) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31742,7 +31742,7 @@ const CollationInfo collation_infos[] = {
};

const uint32_t collation_count = 140;
const uint32_t variable_top_primary = 0x0BFFFFFF;
const uint32_t variable_top_primaries[] = {0x0505FFFF, 0x0BFFFFFF, 0x0DA2FFFF, 0x0EFFFFFF};

} // namespace collation
} // namespace duckdb
12 changes: 12 additions & 0 deletions src/duckdb/extension/icu/collation/include/collation_collator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,25 @@ enum class CollationStrength : uint8_t { PRIMARY = 0, SECONDARY = 1, TERTIARY =

enum class CaseFirst : uint8_t { DEFAULT = 0, LOWER_FIRST = 1, UPPER_FIRST = 2 };

//! The last group of characters that are variable, each group includes the ones before it
enum class MaxVariable : uint8_t { SPACE = 0, PUNCTUATION = 1, SYMBOL = 2, CURRENCY = 3 };

struct CollationSettings {
CollationStrength strength = CollationStrength::TERTIARY;
//! Whether to add a separate case level after the secondary level
bool case_level = false;
CaseFirst case_first = CaseFirst::DEFAULT;
//! Whether variable (punctuation, symbol, ...) weights are shifted to the quaternary level
bool alternate_shifted = false;
//! Which characters are variable when alternate_shifted is set
MaxVariable max_variable = MaxVariable::PUNCTUATION;
//! Whether secondary weights are compared backwards, as in Canadian French
bool backward_secondary = false;
//! Whether text that is not in canonical order is normalized before it is collated
bool normalization = false;
};

struct CollationInfo;
struct CollationTailoring;

//! An index of the code points a locale tailors: a bitmap that rejects the characters it
Expand Down Expand Up @@ -91,6 +97,8 @@ class Collator {
//! Creates a collator for a collation name such as "de" or "fr_ca", falling back to the
//! root collation when the locale is unknown
explicit Collator(const string &collation);
//! Creates a collator for a BCP 47 language tag such as "sv-SE" or "en-u-ka-shifted"
static Collator FromLanguageTag(const string &tag);

//! Whether a collation with this name exists
static bool HasCollation(const string &collation);
Expand All @@ -106,6 +114,10 @@ class Collator {
}

private:
//! Creates a collator for a collation (nullptr for the root collation) with its own settings
explicit Collator(const CollationInfo *info);
//! Creates a collator for a collation (nullptr for the root collation) with the given settings
Collator(const CollationInfo *info, CollationSettings settings_p);
//! Fills the table of ASCII characters that map to a single collation element
void BuildFastPath();
//! Writes the sort key of a string of simple characters, returns false when the string
Expand Down
Loading
Loading